Prompt Ingestion Is a Write Path: Poisoned Documents in Vector and Search Indexes
Content reflects the state as of October 2026. AI tooling and model capabilities in this area change frequently.
Anything that can write to your retrieval index can write instructions directly into your model’s context window—making RAG ingestion a privileged code-execution path, not a passive ETL job.
TL;DR
- Problem: Retrieval-augmented generation (RAG) pipelines routinely index unauthenticated external text alongside verified internal runbooks, allowing as few as five crafted chunks to hijack model answers across millions of documents.
- Answer: Treat index ingestion as a production write path: authenticate writers, stamp every chunk with a
trust_tierand tenant ACL, separate trusted and untrusted indexes, and enforce pre-filtering inside the database engine.- Watch out: OpenSearch Document-Level Security (DLS) restricts reads only—not writes—and text-level sanitizers like perplexity scoring fail against natural-sounding poisoned documents.
Situation
In Post 1 of this series, we established that an agent combining private data, untrusted input, and external egress is exploitable by design. Most engineering teams immediately recognize that a user chat box or an inbound email is untrusted input. Far fewer treat their vector store or search cluster the same way.
In practice, enterprise RAG architectures pull from dozens of heterogeneous sources: Git repositories, Confluence wikis, Jira tickets, customer support portals, Slack exports, and public web documentation. Those chunks are embedded and written into a shared pgvector table, an OpenSearch k-NN index, or a dedicated vector database such as Qdrant. Once indexed, every retrieved chunk is injected into the LLM prompt at inference time, carrying the implicit authority of the enterprise knowledge base.
The OWASP Top 10 for LLM Applications (2025) explicitly pairs LLM01:2025 (Prompt Injection) with LLM08:2025 (Vector and Embedding Weaknesses) to capture this exact failure mode. When an attacker controls any document that enters the ingestion pipeline—a public forum post scraped by a crawler, a support ticket filed by an external user, or an unreviewed wiki edit—they gain persistent, asynchronous control over what the model sees whenever a matching query arrives.
The Problem
RAG pipelines break because similarity search optimizes for semantic proximity, not source integrity. An adversary does not need to compromise your database credentials or breach your VPC to steer an agent; they only need to land a small payload in a document your indexer already ingests.
Four concrete constraints explain why naive ingestion and retrieval architectures fail under adversarial input:
- Five poisoned chunks can dominate millions of clean documents (TB-1 to TB-2). In the PoisonedRAG study presented at the USENIX Security Symposium (2025) by Wei Zou et al., researchers demonstrated that injecting roughly 5 malicious texts per target question into a corpus of millions of clean documents achieved a 90% to 97% attack success rate (including roughly 97% on GPT-4 with the Natural Questions dataset), even in a black-box setting without access to model weights. An attacker satisfies two conditions simultaneously: the retrieval condition (crafting a prefix or semantic anchor whose embedding sits closer to the target question than legitimate documents) and the generation condition (embedding authoritative-sounding claims or indirect directives that compel the LLM to ignore conflicting clean context). When
top_k = 5and all five slots are captured by poisoned chunks, clean documents never even enter the context window. - Engine-level read filters do not protect the write path (TB-1). Teams often assume that enabling access controls on their search cluster secures the pipeline. In OpenSearch, however, Document-Level Security (DLS) evaluates Query DSL
bool.filterclauses strictly on read and search operations; it does not prevent an authorized writer from indexing or overwriting documents outside its own DLS scope. Furthermore, when a user holds multiple OpenSearch roles with different DLS rules, OpenSearch combines them with a logicalOR, expanding visibility rather than restricting it. - Post-filtering in application code leaks existence and destroys recall (TB-2). If an application queries
top_k = 10nearest neighbors from a shared vector index and filters out unauthorized tenants in Python afterward, two failures occur: first, if 10 chunks belong to Tenant B, Tenant A receives zero results (recall collapse); second, timing and empty-result patterns leak whether matching documents exist in another tenant’s namespace. - Raw embeddings are not anonymized. As documented under OWASP LLM08:2025, embedding inversion attacks can reconstruct sensitive source text directly from stored floating-point vectors. Leaving vector tables readable to broad analytics roles exposes confidential text even if the raw
contentcolumn is masked.
How do you ingest multi-source enterprise knowledge into vector and search indexes without letting one untrusted document poison model behavior or leak across tenants?
Options Considered
Teams typically attempt one of three strategies to defend RAG pipelines against poisoned documents and cross-tenant leakage.
How the Options Compare
| Option | Enforcement Layer | What It Gets Right | Where It Breaks | Verdict |
|---|---|---|---|---|
| Open scraping + XML delimiters | Ingestion + prompt template | Fast to wire up; zero schema changes | 5 PoisonedRAG chunks override clean docs; XML tags are easily closed inside chunk text | Rejected |
| Perplexity & paraphrasing filters | Ingestion text sanitizer | Catches garbled, high-perplexity adversarial suffixes | Fails against natural-language poisons (demonstrated in USENIX 2025); adds no tenant ACLs | Insufficient alone |
| Authenticated write path + trust tiers + pre-filtered ACLs | Ingestion gate + DB engine | Authenticates writers, isolates untrusted chunks from high-privilege sessions, enforces ACLs before top_k | Requires source classification, metadata schema discipline, and separate indexes per trust tier | Chosen target architecture |
Text-level sanitizers fail as a primary control because modern knowledge-corruption payloads look like normal technical prose. Paraphrasing a well-written false runbook preserves its semantic meaning—and therefore preserves both its vector proximity and its misleading directive—while breaking checksums that would otherwise trace it back to the original author.
Treating prompt ingestion as a production write path solves the structural flaw. Every write requires an authenticated principal, a deterministic trust_tier, and explicit ACL metadata, and every retrieval executes inside the database engine’s pre-filter before top_k ranking completes.
Trust-Tiered Write Path and Retrieval Architecture
The target-state architecture treats the vector or search index with the same rigor as a transactional system of record, separating Ingestion Gate, Quarantine Check, Partitioned Index, and Permission-Aware Retriever.
Source Trust Tiers and Index Separation
Every ingestion connector must stamp each document chunk with an immutable trust_tier at TB-1 before generating embeddings:
- Tier 1 (Verified Internal): Signed Git repositories, reviewed architecture decision records, and approved operational runbooks. Changes require code review or cryptographic commit signatures.
- Tier 2 (Internal Mutable): Shared internal wikis, Slack channels, and internal issue comments where any authenticated employee can edit text without peer review.
- Tier 3 (Untrusted External): Customer support tickets, inbound emails, uploaded PDFs, and public web crawls.
Never store Tier 1 and Tier 3 chunks in the same unpartitioned index without a mandatory query filter. When an agent session holds write tools or external egress (Profile B from Post 1), the retriever must restrict queries to trust_tier = 1 only. Any session that retrieves Tier 2 or Tier 3 chunks must run under a no-egress, read-only session profile so a poisoned ticket cannot trigger outbound exfiltration.
Comparing Engine Controls: pgvector, OpenSearch, and Dedicated Vector DBs
Different data platforms enforce write authentication, read isolation, and pre-filtering through very different primitives. Choosing the right engine depends on where your authoritative ACLs live.
| Control Dimension | pgvector (PostgreSQL) | OpenSearch (Security Plugin) | Dedicated Vector DB (e.g., Qdrant) |
|---|---|---|---|
| Write-path authentication | Standard PostgreSQL ROLE + INSERT/UPDATE GRANTs | OpenSearch RBAC index-level write permissions (DLS does not restrict writes) | API key / JWT scoped to collection write operations |
| Read-path tenant / ACL isolation | Native Row-Level Security (RLS) policies + relational joins | Document-Level Security (DLS) bool.filter with ${user.name} substitution | Payload-based partitioning (tenant_id, acl) passed in query_filter |
| Pre-filtering vs. ANN recall | SQL WHERE + scalar indexes; tune hnsw.iterative_scan to avoid recall drop | Executes DLS filter alongside k-NN search; heavy filters add CPU overhead | Co-optimizes HNSW graph traversal with payload indexes (must / should) |
| Multi-role / group logic | Arbitrary SQL ANY(array) or join tables; deterministic AND/OR | Multiple roles with DLS combine via logical OR (watch for over-broad union) | Nested must, should, must_not filter clauses supplied by gateway |
| Operational tradeoff | Zero sync lag with relational ACLs; scales to ~1M–5M vectors before tuning | Native enterprise RBAC + SAML/JWT mapping; careful wildcard index hygiene required | Fast filtered ANN at >10M vectors; requires syncing ACLs from system of record |
In pgvector, access control is ordinary PostgreSQL. You can enforce tenant isolation and trust-tier boundaries directly inside the database engine using Row-Level Security so even a buggy application query cannot cross tenants:
-- PostgreSQL + pgvector: enforce tenant ACL and trust-tier ceiling via RLS
ALTER TABLE rag_chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE rag_chunks FORCE ROW LEVEL SECURITY; -- the table owner is otherwise exempt from RLS
CREATE POLICY tenant_and_tier_isolation ON rag_chunks
FOR SELECT
USING (
tenant_id = NULLIF(current_setting('app.tenant_id', true), '')
AND trust_tier <= COALESCE(NULLIF(current_setting('app.max_trust_tier', true), ''), '-1')::int -- unset means no rows
);
-- Query runs after SET LOCAL app.tenant_id and app.max_trust_tier
SELECT id, content, embedding <=> $1 AS distance
FROM rag_chunks
ORDER BY distance
LIMIT 5;
In OpenSearch, use separate index patterns for Tier 1 (kb-verified-*) and Tier 3 (kb-untrusted-*), grant write permissions strictly to the dedicated ingestion service role per index, and enforce DLS with attribute substitution ({"term": {"tenant_id": "${user.attr.tenant_id}"}}) on read roles. Because OpenSearch evaluates DLS filters on every search request, index the tenant_id and trust_tier fields as keyword and integer types so filter bitsets are cached across queries rather than triggering expensive script evaluations.
In dedicated vector engines such as Qdrant, avoid spinning up thousands of separate collections when tenant counts grow, because per-collection HNSW graph overhead fragments memory. Instead, store tenants in a shared collection with payload indexes on tenant_id and trust_tier, and wrap every search call inside an identity-enforcing gateway that injects the must filter deterministically before the query reaches the HNSW graph. Never accept raw filter JSON directly from the agent runtime or LLM tool arguments.
Attacker and Defender Threat Matrix
| Threat Vector | Trust Boundary Crossed | Attacker Objective (OWASP / ATLAS) | Defender Control (Deterministic) | Verification Signal |
|---|---|---|---|---|
| External ticket / web scrape poisoning | TB-1 (Source → Index) | Plant 5 crafted chunks to hijack answers (PoisonedRAG / LLM01) | Tag source as trust_tier = 3; block Tier 3 from egress-enabled sessions | Poisoned ticket chunk never retrieved in Profile B agent query |
| OpenSearch DLS write bypass | TB-1 (Writer → Index) | Overwrite or inject docs into another tenant’s index via writer role | Separate ingestion indices; revoke write/index from all query roles | Query service role receives HTTP 403 on PUT _doc |
| Post-filter cross-tenant leak | TB-2 (Index → Retriever) | Infer or read Tenant B chunks from shared HNSW index (LLM08) | Enforce pre-filtering inside engine (RLS, DLS, or Qdrant payload filter) | Cross-tenant query returns 0 chunks and identical recall for Tenant A |
| Wiki / internal mutable drift | TB-1 (Internal → Tier 1) | Edit unreviewed wiki page to redirect agent to malicious endpoint | Classify wikis as trust_tier = 2; require PR/approval for Tier 1 | Unreviewed wiki edit cannot enter kb-verified-* index |
| Burst topic injection | TB-1 (Connector → Index) | Flood index with semantically clustered chunks for a target query | Quarantine connectors; alert on high-similarity cluster bursts per writer_id | Anomaly detector flags >3 near-duplicate chunks from one writer |
| Embedding inversion | TB-2 (Vector Store → Reader) | Reconstruct PII or secrets from raw embedding vectors (LLM08) | Restrict SELECT on embedding columns; encrypt at rest; apply same RLS | Analytics role without PII clearance denied access to embedding column |
How It Rolls Out
Securing the RAG pipeline requires deterministic pre-filtering on every read and a staged migration that stamps provenance before enforcing hard isolation.
Runtime Retrieval Flow
- 01 Caller Token: The MCP gateway or application extracts
tenant_id, group memberships, and caller identity from a verified OIDC/JWT token. Prompt-supplied tenant IDs are ignored. - 02 Trust Policy: The gateway inspects the active agent session’s capabilities. If the session can call external webhooks, send emails, or execute state-changing tools,
max_trust_tieris locked to1. - 03 Pre-Filter ANN: The retriever passes the
tenant_id, ACL group list, andmax_trust_tierdirectly into the database query (SET LOCALfor PostgreSQL RLS, DLS for OpenSearch, orquery_filterfor Qdrant) so unauthorized chunks are excluded beforetop_kranking. - 04 Trace and Quarantine: Every retrieved
chunk_id,doc_id,trust_tier, andwriter_idis logged alongside the request trace ID. If a poisoned document is discovered later, operators can purge or quarantine every chunk from thatwriter_idin one deterministic operation.
Phased Rollout and Rollback Gates
- Phase 1 — Source Inventory and Provenance Schema: Add
trust_tier,tenant_id,acl_principals,writer_id, andcontent_sha256to all index schemas. Backfill existing documents with conservative default tiers (Tier 2orTier 3until verified). Gate: 100% of indexed chunks carry non-nulltrust_tierandwriter_id. Rollback: N/A (additive metadata). - Phase 2 — Write-Path Role Separation: Revoke
INSERT/UPDATE/DELETEprivileges from all query/agent roles acrosspgvector, OpenSearch, and vector DBs. Assign each ingestion connector a distinctwriter_idscoped to its designated trust-tier index or partition. Gate: Read-only agent credentials fail write tests with permission denied. Rollback: Temporarily re-grant write only to named emergency backfill jobs. - Phase 3 — Engine-Level Pre-Filtering: Enable PostgreSQL RLS, OpenSearch DLS, or mandatory Qdrant
query_filterwrappers in the retriever service. Remove application-layer post-filtering. Gate: Multi-tenant isolation test passes with zero cross-tenant leaks and verifiedtop_krecall. Rollback: Feature-flag fallback to strict per-tenant physical tables/collections if query latency exceeds SLA while tuninghnsw.iterative_scan. - Phase 4 — Trust-Tier Session Coupling: Bind
max_trust_tierto agent session profiles so egress-capable or write-capable agents only read Tier 1 verified indexes. Gate: Synthetic PoisonedRAG test in a Tier 3 ticket fails to influence any egress-capable agent. Rollback: Route specific workflows through an explicit HITL review queue before promoting Tier 2/3 summaries.
In Practice
I have not operated every vector engine at multi-billion-vector scale personally, so the controls above are grounded in peer-reviewed research, published standards, and documented engine behavior:
- Knowledge corruption math (Pattern A — Peer-Reviewed Research): The USENIX Security 2025 PoisonedRAG paper reported that injecting five malicious texts per target question into a knowledge base of millions of texts reached about a 90% attack success rate, and that the defenses it evaluated were insufficient.
- Vector and embedding risk taxonomy (Pattern A — Standard): OWASP LLM08:2025, Vector and Embedding Weaknesses documents RAG data poisoning, broken multi-tenant access control, and embedding inversion as first-class architectural risks requiring retrieval-layer authorization and source authentication.
- OpenSearch DLS vs. PostgreSQL RLS behavior (Pattern B — System Mechanics): Per the OpenSearch document-level security documentation, DLS filters apply strictly to read/search operations (
bool.filter) and combine multiple roles with logicalOR, leaving write paths governed separately by index-level permissions. In PostgreSQL withpgvector, Row-Level Security (CREATE POLICY) governsSELECT,INSERT, andUPDATEuniformly inside the same relational engine.
Where It Breaks
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
| Selectivity collapse with pre-filtering | A tenant owns only 0.1% of a massive pgvector HNSW table; WHERE tenant_id = ... returns fewer than LIMIT k results | Sudden drop in retrieved chunk count (< k) for small tenants | Enable hnsw.iterative_scan in pgvector or partition large multi-tenant tables by tenant_id |
| Over-broad OpenSearch role union | User holds Role A (region: us) and Role B (*); OpenSearch ORs DLS rules and exposes all documents | Automated ACL audit shows unexpected document count for dual-role test user | Never combine wildcard index patterns with DLS; test effective permissions per role combination |
| Tier 2 wiki edit promoted without review | Attacker with employee wiki access plants an indirect injection that gets synced into a Tier 1 runbook index | Provenance audit detects unreviewed writer_id in Tier 1 index | Enforce Git PR approval + commit verification for all Tier 1 ingestion pipelines |
| ACL sync lag in external vector DB | Employee loses access to a confidential HR doc in PostgreSQL, but Qdrant payload still lists their group for hours | Access-revocation latency exceeds security SLA during offboarding tests | Stream ACL changes via CDC/webhooks to vector DB or query pgvector directly for high-churn ACLs |
| Stale poisoned chunks remain after source deletion | Source ticket is deleted, but chunk remains orphaned in vector index and keeps matching queries | Orphan-chunk reconciliation job flags IDs missing from source of record | Run daily tombstone/reconciliation sweeps keyed by doc_id and content_sha256 |
Key Takeaways
- RAG ingestion is a production write path: Any connector or user input that can write chunks into your index can inject instructions into your LLM’s context window.
- Sanitizers cannot replace write-path authentication: Perplexity filters and paraphrasing fail against natural-language PoisonedRAG payloads; authenticate writers and track provenance with
writer_idandcontent_sha256. - Separate trust tiers at the index and session layers: Never mix unreviewed external text (Tier 3) with verified internal runbooks (Tier 1) in an agent session that holds write or egress capabilities.
- Enforce ACLs inside the engine before
top_k: Use PostgreSQL RLS (pgvector), OpenSearch DLS (with write-path separation), or Qdrant payload pre-filters—never post-filter in application code. - Protect raw embeddings as sensitive data: Treat vector columns with the same access controls as raw text to mitigate embedding inversion attacks.
What to Do Next
- Problem: Unauthenticated or unlabelled RAG ingestion allows a handful of poisoned documents to hijack model outputs and leak cross-tenant context.
- Solution: Add
trust_tier,tenant_id, andwriter_idmetadata to every chunk, separate read and write credentials, and enforce pre-filtered ACLs inside your vector or search engine. - Proof: Inject a synthetic canary phrase inside a Tier 3 test ticket and verify that an egress-capable agent session cannot retrieve it and a cross-tenant query returns zero rows.
- Action: Audit every active RAG ingestion connector this week, assign each source a Tier 1–3 label, and revoke index
writepermissions from all query-serving roles.