Permission-Aware RAG: Search Without Data Leaks
Similarity search cannot decide who may read a result. Carry source permissions into every chunk and filter in the database before the model sees anything.
- Topics
- Secure AI Agents
- Level
- Founder / builder
- Read
- 4 min
- Published
- 2026-11-12
- Reviewed
- 2026-11-12
The problem
On July 30, 2025, IBM published its annual breach study, covering 600 organizations. It found that 13% had a breach of AI models or applications, and that 97% of those had no AI access controls in place. Of the AI-related incidents, 60% led to compromised data [1].
Retrieval-augmented generation (RAG) is one common place where that access gap opens. The typical prototype runs an ingestion job under a service account, splits every document it can reach into chunks, embeds them and writes them to one vector index. The source system knew who could read each document. The index does not. A question from any user now ranks every chunk by similarity, and similarity has no concept of permission.
Microsoft states the correct rule for its own product plainly: Copilot only surfaces organizational data to which individual users have at least view permissions [2]. The same vendor publishes a separate deployment blueprint devoted to finding and fixing oversharing [3], because an assistant that honors permissions still exposes every permission that was wrong.
An illustrative case: two client companies share one knowledge base in a bookkeeping product. An accountant at one asks about payroll and receives a passage from the other's payroll memo, because the vector query had no tenant filter. Nothing was hacked. The system did what it was built to do.
How it works
Permission-aware retrieval splits the request into five responsibilities, in order, and the model appears only in the fourth.
- Authenticate. Establish who is asking, from the session, never from the prompt.
- Authorize. Resolve the tenant, the user's groups and roles, and the version of the access policy in force.
- Filtered retrieval. Query only chunks the user may read. The filter runs in the data store, server side, and fails closed when the identity context is missing.
- Generation. The model sees permitted context only. It cannot leak what it was never given.
- Response validation. Check citations and snippets before returning them. A cited title or a filename can disclose information on its own.
The mechanism that makes step three work is ACL propagation. At ingestion, copy the source document's access list onto every chunk derived from it, together with the source ID and the policy version. Summaries, extracted entities and cached answers are derivatives too and carry the same fields.
Permissions change after ingestion. A user leaves a project, a folder is unshared, a client offboards. Route every such change through a revocation queue that updates or removes the affected chunks, and measure the lag. Until the queue drains, the index holds stale grants. OWASP lists this class of failure, including cross-context leaks between tenants sharing one vector store, as LLM08 in its 2025 Top 10, and recommends permission-aware stores with logical partitioning [4].
Do not filter in the prompt. An instruction such as "only use documents the user may see" asks the model to enforce a rule it has no data to evaluate. Do not filter only after ranking either: top-k results from an unfiltered query leak through counts, timing and gaps, and can return zero permitted chunks when permitted ones exist.
Authorization happens before the model sees anything
Fig. 03- AuthenticateWho is asking
- AuthorizeTenant, role, policy version
- Filtered retrievalOnly permitted chunks
- GenerationModel sees permitted context
- Response validationCitations and snippets
Technical detail
Source ACLs are carried into chunks and derived indexes. Keep source IDs and policy versions with every derivative, and process revocations through a queue so reindex lag cannot reopen access.
Cited titles and snippets can leak information too, so validate the response, not only the retrieval.
By the numbers
- of 600 organizations studied reported breaches of AI models or applications [1]
- 13%
- of those breached organizations had no AI access controls [1]
- 97%
- of AI-related security incidents led to compromised data [1]
- 60%
- of organizations did not know whether their AI had been compromised [1]
- 8%
| Placement | Fails closed when context is missing | Leaks through ranking or counts | Survives a prompt injection |
|---|---|---|---|
| Instruction in the system prompt | No | Yes | No |
| Filter applied after top-k ranking | Depends on code | Yes | Yes |
| Metadata filter inside the vector query | Depends on code | No | Yes |
| Row-level security in the database | Yes, default deny | No | Yes |
The 8% figure deserves attention. One common reason an organization cannot say whether its AI was compromised is that it has no retrieval log keyed by user. Without that log, there is no way to answer which chunks a given user received last month.
The table explains the recommendation that follows. Row-level security in the database is the only placement where a missing identity returns nothing by default. PostgreSQL applies a default-deny policy when row security is enabled and no policy matches [5].
Implementation
The example uses PostgreSQL with the pgvector extension, because row-level security puts the permission check under the ranking query, where application code cannot forget it. The same design works in any store that supports server-side filters bound to the caller's identity.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
tenant_id uuid NOT NULL,
source_id text NOT NULL, -- document the chunk came from
acl_groups text[] NOT NULL, -- copied from the source ACL at ingest
policy_ver integer NOT NULL, -- ACL version this copy reflects
body text NOT NULL,
embedding vector(1536) NOT NULL
);
ALTER TABLE chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE chunks FORCE ROW LEVEL SECURITY; -- the table owner is filtered too
-- Tenant isolation must pass for every command. current_setting() raises an
-- error when the API did not set the context, so a missing identity fails closed.
CREATE POLICY tenant_isolation ON chunks AS RESTRICTIVE
USING (tenant_id = current_setting('app.tenant_id')::uuid);
-- Readers see a chunk only if they share a group with its source ACL.
CREATE POLICY group_read ON chunks FOR SELECT TO rag_app
USING (acl_groups && string_to_array(current_setting('app.groups'), ','));
-- Ingestion writes through its own role, still inside the tenant boundary.
CREATE POLICY ingest_write ON chunks FOR INSERT TO rag_ingest
WITH CHECK (true);
-- The query the API runs after setting context. RLS filters before ranking:
-- SELECT id, source_id, body FROM chunks ORDER BY embedding <=> $1 LIMIT 8;The API sets app.tenant_id and app.groups with set_config(..., true) inside each transaction, from the authenticated session. The model never supplies them. The rag_app role has no BYPASSRLS attribute and does not own the table.
Three supporting pieces complete the design:
- A permission sync job that reads ACL changes from each source system and writes them to the revocation queue, with the lag exported as a metric.
- A retrieval log that records user, tenant, policy version and chunk IDs for every query, so the 8% question has an answer.
- A response validator that drops any citation whose source ID was not in the permitted result set.
Test it
Build two tenants with deliberately overlapping text, so similarity alone would return the wrong tenant's chunk. Then prove isolation, revocation and the fail-closed path.
"""Run against a seeded test database. Tenants A and B both hold a 'payroll memo' chunk."""
import psycopg
import pytest
DSN = "postgresql://rag_app@localhost/rag_test"
TENANT_A = "0f6c1d7e-0000-4000-8000-00000000000a"
TENANT_B = "0f6c1d7e-0000-4000-8000-00000000000b"
QUERY = "SELECT source_id FROM chunks ORDER BY embedding <=> %s::vector LIMIT 8"
PAYROLL_VEC = "[" + ",".join(["0.01"] * 1536) + "]" # same vector seeded for both memos
def search(tenant: str, groups: list[str]) -> list[str]:
with psycopg.connect(DSN) as conn, conn.transaction():
conn.execute("SELECT set_config('app.tenant_id', %s, true)", (tenant,))
conn.execute("SELECT set_config('app.groups', %s, true)", (",".join(groups),))
return [row[0] for row in conn.execute(QUERY, (PAYROLL_VEC,)).fetchall()]
def test_tenant_b_never_sees_tenant_a():
results = search(TENANT_B, ["finance"])
assert results, "tenant B should see its own memo"
assert all(src.startswith("b/") for src in results) # seed prefixes source IDs by tenant
def test_other_group_sees_nothing():
assert search(TENANT_A, ["marketing"]) == [] # the memo's ACL is finance only
def test_missing_context_fails_closed():
with psycopg.connect(DSN) as conn:
with pytest.raises(psycopg.Error):
conn.execute(QUERY, (PAYROLL_VEC,)).fetchall()Expected result: three passes. If test_missing_context_fails_closed returns rows instead of raising, the role is bypassing row security or a session default is set somewhere. Fix that before anything else.
Add these checks to the same suite:
- Revoke a user's group in the source system, then query before and after the revocation queue drains. Record the window during which the old grant still worked.
- Ask for a document by exact title from an unpermitted account. Expected: no title, no snippet, and no reply that admits a matching document exists.
- Run the suite on every schema migration and every change to the ingestion job.
Decision
Put authorization in the retrieval infrastructure, not in the prompt and not in a post-filter.
- New builds: store chunks with tenant, ACL, source ID and policy version from day one. Retrofitting ACLs onto an existing index means re-ingesting it.
- Existing builds: add tenant isolation first, then group filters, then the revocation queue. Tenant isolation alone removes the worst case.
- Before launching any workplace assistant, run an oversharing review of the source systems. The assistant will faithfully expose every grant that was wrong.
- Budget: the database work is about a week for a small team. The permission sync per source system is the larger, ongoing cost.
Sources
- [1]IBM Report: 13% of organizations reported breaches of AI models or applications, 97% of which reported lacking proper AI access controls (opens in a new tab)IBM Newsroom, July 2025
- [2]Data, Privacy, and Security for Microsoft Copilot (opens in a new tab)Microsoft Learn, November 2026
- [3]Prevent oversharing in Microsoft 365 Copilot: deployment blueprint (opens in a new tab)Microsoft Learn, November 2026
- [4]LLM08:2025 Vector and Embedding Weaknesses (opens in a new tab)OWASP GenAI Security Project, 2025
- [5]Row Security Policies (opens in a new tab)PostgreSQL Global Development Group, November 2026
Technical guidance, not security certification or legal advice.
