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_tier and 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.

Anything that writes to the index writes instructions to the model

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.

Label every ingestion source by trust tier before indexing

Four concrete constraints explain why naive ingestion and retrieval architectures fail under adversarial input:

  1. 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 = 5 and all five slots are captured by poisoned chunks, clean documents never even enter the context window.
  2. 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.filter clauses 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 logical OR, expanding visibility rather than restricting it.
  3. Post-filtering in application code leaks existence and destroys recall (TB-2). If an application queries top_k = 10 nearest 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.
  4. 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 content column 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.

Perplexity filters fail; authenticated write paths and ACLs hold

How the Options Compare

OptionEnforcement LayerWhat It Gets RightWhere It BreaksVerdict
Open scraping + XML delimitersIngestion + prompt templateFast to wire up; zero schema changes5 PoisonedRAG chunks override clean docs; XML tags are easily closed inside chunk textRejected
Perplexity & paraphrasing filtersIngestion text sanitizerCatches garbled, high-perplexity adversarial suffixesFails against natural-language poisons (demonstrated in USENIX 2025); adds no tenant ACLsInsufficient alone
Authenticated write path + trust tiers + pre-filtered ACLsIngestion gate + DB engineAuthenticates writers, isolates untrusted chunks from high-privilege sessions, enforces ACLs before top_kRequires source classification, metadata schema discipline, and separate indexes per trust tierChosen 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.

Separate write ingestion, trust-tiered storage, and ACL retrieval

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 Dimensionpgvector (PostgreSQL)OpenSearch (Security Plugin)Dedicated Vector DB (e.g., Qdrant)
Write-path authenticationStandard PostgreSQL ROLE + INSERT/UPDATE GRANTsOpenSearch RBAC index-level write permissions (DLS does not restrict writes)API key / JWT scoped to collection write operations
Read-path tenant / ACL isolationNative Row-Level Security (RLS) policies + relational joinsDocument-Level Security (DLS) bool.filter with ${user.name} substitutionPayload-based partitioning (tenant_id, acl) passed in query_filter
Pre-filtering vs. ANN recallSQL WHERE + scalar indexes; tune hnsw.iterative_scan to avoid recall dropExecutes DLS filter alongside k-NN search; heavy filters add CPU overheadCo-optimizes HNSW graph traversal with payload indexes (must / should)
Multi-role / group logicArbitrary SQL ANY(array) or join tables; deterministic AND/ORMultiple roles with DLS combine via logical OR (watch for over-broad union)Nested must, should, must_not filter clauses supplied by gateway
Operational tradeoffZero sync lag with relational ACLs; scales to ~1M–5M vectors before tuningNative enterprise RBAC + SAML/JWT mapping; careful wildcard index hygiene requiredFast 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 VectorTrust Boundary CrossedAttacker Objective (OWASP / ATLAS)Defender Control (Deterministic)Verification Signal
External ticket / web scrape poisoningTB-1 (Source → Index)Plant 5 crafted chunks to hijack answers (PoisonedRAG / LLM01)Tag source as trust_tier = 3; block Tier 3 from egress-enabled sessionsPoisoned ticket chunk never retrieved in Profile B agent query
OpenSearch DLS write bypassTB-1 (Writer → Index)Overwrite or inject docs into another tenant’s index via writer roleSeparate ingestion indices; revoke write/index from all query rolesQuery service role receives HTTP 403 on PUT _doc
Post-filter cross-tenant leakTB-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 driftTB-1 (Internal → Tier 1)Edit unreviewed wiki page to redirect agent to malicious endpointClassify wikis as trust_tier = 2; require PR/approval for Tier 1Unreviewed wiki edit cannot enter kb-verified-* index
Burst topic injectionTB-1 (Connector → Index)Flood index with semantically clustered chunks for a target queryQuarantine connectors; alert on high-similarity cluster bursts per writer_idAnomaly detector flags >3 near-duplicate chunks from one writer
Embedding inversionTB-2 (Vector Store → Reader)Reconstruct PII or secrets from raw embedding vectors (LLM08)Restrict SELECT on embedding columns; encrypt at rest; apply same RLSAnalytics 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.

Pre-filter ACLs and trust tiers before top-k similarity search

Runtime Retrieval Flow

  1. 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.
  2. 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_tier is locked to 1.
  3. 03 Pre-Filter ANN: The retriever passes the tenant_id, ACL group list, and max_trust_tier directly into the database query (SET LOCAL for PostgreSQL RLS, DLS for OpenSearch, or query_filter for Qdrant) so unauthorized chunks are excluded before top_k ranking.
  4. 04 Trace and Quarantine: Every retrieved chunk_id, doc_id, trust_tier, and writer_id is logged alongside the request trace ID. If a poisoned document is discovered later, operators can purge or quarantine every chunk from that writer_id in one deterministic operation.

Phased Rollout and Rollback Gates

  1. Phase 1 — Source Inventory and Provenance Schema: Add trust_tier, tenant_id, acl_principals, writer_id, and content_sha256 to all index schemas. Backfill existing documents with conservative default tiers (Tier 2 or Tier 3 until verified). Gate: 100% of indexed chunks carry non-null trust_tier and writer_id. Rollback: N/A (additive metadata).
  2. Phase 2 — Write-Path Role Separation: Revoke INSERT/UPDATE/DELETE privileges from all query/agent roles across pgvector, OpenSearch, and vector DBs. Assign each ingestion connector a distinct writer_id scoped 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.
  3. Phase 3 — Engine-Level Pre-Filtering: Enable PostgreSQL RLS, OpenSearch DLS, or mandatory Qdrant query_filter wrappers in the retriever service. Remove application-layer post-filtering. Gate: Multi-tenant isolation test passes with zero cross-tenant leaks and verified top_k recall. Rollback: Feature-flag fallback to strict per-tenant physical tables/collections if query latency exceeds SLA while tuning hnsw.iterative_scan.
  4. Phase 4 — Trust-Tier Session Coupling: Bind max_trust_tier to 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 logical OR, leaving write paths governed separately by index-level permissions. In PostgreSQL with pgvector, Row-Level Security (CREATE POLICY) governs SELECT, INSERT, and UPDATE uniformly inside the same relational engine.

Where It Breaks

Poisoned chunks succeed via open writes, DLS blind spots, and post-filters

ConditionBreaks HowDetectMitigate
Selectivity collapse with pre-filteringA tenant owns only 0.1% of a massive pgvector HNSW table; WHERE tenant_id = ... returns fewer than LIMIT k resultsSudden drop in retrieved chunk count (< k) for small tenantsEnable hnsw.iterative_scan in pgvector or partition large multi-tenant tables by tenant_id
Over-broad OpenSearch role unionUser holds Role A (region: us) and Role B (*); OpenSearch ORs DLS rules and exposes all documentsAutomated ACL audit shows unexpected document count for dual-role test userNever combine wildcard index patterns with DLS; test effective permissions per role combination
Tier 2 wiki edit promoted without reviewAttacker with employee wiki access plants an indirect injection that gets synced into a Tier 1 runbook indexProvenance audit detects unreviewed writer_id in Tier 1 indexEnforce Git PR approval + commit verification for all Tier 1 ingestion pipelines
ACL sync lag in external vector DBEmployee loses access to a confidential HR doc in PostgreSQL, but Qdrant payload still lists their group for hoursAccess-revocation latency exceeds security SLA during offboarding testsStream ACL changes via CDC/webhooks to vector DB or query pgvector directly for high-churn ACLs
Stale poisoned chunks remain after source deletionSource ticket is deleted, but chunk remains orphaned in vector index and keeps matching queriesOrphan-chunk reconciliation job flags IDs missing from source of recordRun 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_id and content_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, and writer_id metadata 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 write permissions from all query-serving roles.