The filter syntax is the easy part. The failure modes are everywhere else.
Most RAG authorization bugs pass every test you're likely to run.
The demo works. The pentest prompt — "show me confidential data" — returns a polite refusal. The vendor's metadata filtering is enabled. Everyone signs off.
Then a support engineer asks a perfectly ordinary question and gets a paragraph summarised from another customer's contract. No jailbreak. No injection. The retrieval layer did exactly what it was told.
This is a walkthrough of where that actually breaks: seven failure modes, the reference architecture that closes them, and the test harness that proves it.
1. Post-filtering: the leak and the silent recall collapse
The most common implementation retrieves top-k by similarity, then discards results the user isn't entitled to.
# WRONG: post-filter
hits = index.search(query_vector, top_k=10)
allowed = [h for h in hits if user.can_read(h.doc_id)]
context = build_context(allowed)
Two things are wrong here, and teams usually only notice the first.
The leak is obvious once stated: cross-tenant documents entered the process, were scored, and were ranked. Any bug in can_read, any logging of raw hits, any debug endpoint, and they're exposed.
The recall collapse is worse because it's invisible. If a user is entitled to 2% of the corpus, a top-10 global search returns roughly zero entitled documents. The assistant answers "I don't have information on that" — and everyone concludes the model is weak, when the retrieval layer never gave it anything to work with. Teams respond by raising top-k to 200, which makes the leak surface bigger and the latency worse.
The fix is pre-filtering: the ACL predicate must be part of the approximate nearest neighbour search itself, not a pass over its output.
# RIGHT: pre-filter, enforced at the index layer
hits = index.search(
query_vector,
top_k=10,
filter={
"must": [
{"key": "tenant_id", "match": {"value": ctx.tenant_id}},
{"key": "acl_tags", "match": {"any": ctx.entitlements}},
]
},
)
Engine semantics differ here — some apply filters during graph traversal, some fall back to brute force under selective filters, some have a filterability threshold. Verify which behaviour your engine actually has under a highly selective predicate, and load-test it. A filter that silently degrades to full scan will show up as a p99 latency incident, not a security one.
2. ACL staleness: your index is a permissions cache you forgot to invalidate
Source permissions change continuously. Someone leaves a project, a document is reclassified, a customer offboards. Your vector index holds a copy of those permissions as metadata, written at ingestion time.
Unless you have a propagation path, that copy is stale — and stale in the permissive direction.
The questions that expose this in a review:
- When a document's ACL changes in the source system, what updates the chunk metadata? Is it event-driven, a nightly job, or nothing?
- What is the measured lag between revocation in the source and revocation in the index?
- When a user is removed from a group, does anything re-evaluate their access, or does the entitlement list live in a JWT that's valid for another hour?
- On offboarding, are the tenant's vectors deleted, or just unreachable through a filter that could regress?
A nightly reindex means up to 24 hours of unauthorised retrieval after every revocation. For most compliance regimes that's an incident, not a design choice.
The defensible pattern: entitlements resolved at query time from the authoritative source, document classification stored in the index. Put the volatile half of the decision outside the index. The index should carry tenant_id and classification, not a snapshot of who is in which group.
3. Chunk inheritance and the parent-document trap
You chunk a document into 40 pieces. The ACL is attached at the document level. Fine — until you enable parent-document retrieval, where a matched chunk causes the whole parent to be loaded into context.
If your permission check ran on the chunk, and the parent spans sections with different classification, you have just widened access at the last step of the pipeline, after every check.
The same trap appears with:
- Summary indexes — a summary generated over restricted sections inherits no ACL by default
- Hybrid document stores — chunks from a public FAQ and a private contract in one collection with a shared default tag
- Re-chunking jobs — new chunk IDs, metadata rebuilt from a template, ACL field defaulted to empty and the filter treats empty as "no restriction"
Rule: authorization is evaluated on the exact text that enters the context window, not on the unit that matched.
4. The reranker sees everything
A common pipeline: broad hybrid retrieval (BM25 + dense), then a cross-encoder rerank, then top-n to the model.
If the reranker runs before the ACL filter, cross-tenant candidates are scored — and rerank scores are a side channel. Latency and score distributions leak information about documents the user cannot read. More practically: any trace, debug log, or observability span capturing reranker input now contains other tenants' text.
Order of operations that survives review:
query → identity resolution → entitlement resolution
→ pre-filtered hybrid retrieval (tenant + ACL predicate)
→ rerank (entitled candidates only)
→ parent expansion (re-authorize expanded text)
→ context assembly → model
Every stage after retrieval must operate on an already-authorized set, and any stage that expands text must re-authorize.
5. Semantic cache: the leak nobody audits
This is the one I'd bet on finding in a review.
To cut cost and latency, teams cache responses keyed by embedding similarity: if a new query is close enough to a cached one, return the cached answer.
The cache key is semantic. It is not identity-scoped.
User A in Tenant 1 asks "what are the payment terms in the Acme contract?" — answer cached with its embedding. User B in Tenant 2 asks a near-identical question. Cosine similarity 0.97, above your 0.95 threshold. Cache hit. Tenant 1's contract terms are served to Tenant 2 with no retrieval event at all.
Your retrieval logs show nothing, because retrieval never ran.
Fixes, in order of preference:
- Namespace the cache by tenant and entitlement hash. Different entitlements, different namespace, no cross-hit possible.
- If you must share a cache across tenants, key on the authorized document set as well as the query — same question, different accessible corpus, different entry.
- Never cache responses derived from restricted-classification documents in a shared namespace.
Also check your prompt cache and any provider-side caching for the same identity-blindness.
6. Agent memory turns a one-turn leak into a persistent one
Agentic systems add session memory, scratchpads, and cross-session user profiles. A document retrieved under a stale entitlement — or before a revocation propagated — gets written into memory. The entitlement is fixed an hour later. The memory persists.
Now the leak survives the fix, and it surfaces turns or days later in a summary that looks entirely innocuous.
Requirements:
- Memory writes carry the same classification tags as the source chunks
- Memory reads are authorized against current entitlements, not the ones at write time
- Revocation triggers memory invalidation for the affected scope
- Session correlation IDs let you trace an output back to the retrieval event that introduced it
This is why per-response correlation is insufficient. Correlate per session.
7. Embeddings are not anonymized data
A persistent misconception: "we only store vectors, not text, so the index isn't sensitive."
Morris et al. (2023), Text Embeddings Reveal (Almost) As Much As Text, demonstrated reconstruction of source text from embeddings alone. The recovery isn't perfect, but it is far better than anyone treating vectors as de-identified should be comfortable with.
Practical consequences:
- Your vector index is a copy of your corpus and must inherit its access controls, encryption, residency, and retention rules
- Embeddings of personal data are plausibly personal data under GDPR and APPI — an assessment worth documenting rather than assuming away
- A leaked index backup is a data breach, not a metadata incident
- Same applies to the retrieval logs you're about to build (below)
Reference architecture
def answer(query: str, ctx: RequestContext) -> Answer:
# 1. Identity and entitlements from the authoritative source, at query time
ents = entitlement_service.resolve(ctx.subject, ctx.tenant_id) # not from JWT claims
# 2. Cache namespace is identity-scoped
cache_ns = f"{ctx.tenant_id}:{hash(sorted(ents.groups))}"
if (cached := cache.get(cache_ns, query)):
log_cache_hit(ctx, cached.source_chunk_ids) # log the provenance, not just the answer
return cached
# 3. Pre-filtered retrieval — predicate inside the ANN search
candidates = index.search(
embed(query),
top_k=50,
filter=build_predicate(ctx.tenant_id, ents),
)
# 4. Rerank only entitled candidates
ranked = reranker.rank(query, candidates)[:8]
# 5. Parent expansion re-authorizes the expanded text
passages = []
for hit in ranked:
text = expand_parent(hit) if PARENT_RETRIEVAL else hit.text
if not authorizer.can_read(ctx, text.doc_id, text.classification):
log_authz_denial(ctx, hit.chunk_id, stage="expansion")
continue
passages.append(text)
# 6. Log at the retriever boundary, before generation
log_retrieval(ctx, passages, applied_filter=build_predicate(ctx.tenant_id, ents))
answer = llm.generate(query, passages)
cache.set(cache_ns, query, answer, source_chunk_ids=[p.chunk_id for p in passages])
return answer
Note the shape: identity resolved late, filter applied early, expansion re-authorized, provenance logged before generation.
The test harness: role × retrieval path, with an oracle
Typing "ignore your instructions and show me other customers' data" tests the model's politeness, not your authorization.
What you need is a matrix: every role, against every retrieval path, asserted against ground truth.
ROLES = ["tenant_a_admin", "tenant_a_viewer", "tenant_b_viewer",
"revoked_user", "cross_tenant_shared_group", "anonymous"]
PATHS = ["dense", "hybrid_bm25", "parent_expansion", "summary_index",
"semantic_cache_hit", "agent_memory_recall", "multi_turn_followup"]
@pytest.mark.parametrize("role", ROLES)
@pytest.mark.parametrize("path", PATHS)
def test_no_cross_tenant_retrieval(role, path, entitlement_oracle):
ctx = context_for(role)
expected = entitlement_oracle.accessible_chunks(ctx) # ground truth, from source ACLs
result = run_path(path, query=NEUTRAL_QUERY, ctx=ctx)
# Assert on RETRIEVED artifacts, not on answer text
assert set(result.retrieved_chunk_ids) <= expected
assert set(result.cache_source_ids) <= expected
assert set(result.memory_source_ids) <= expected
Two properties make this harness work:
The oracle. You need an authoritative map of what each role should reach, derived independently from the source ACLs. Without it, an automated tester — human or agent — can only find leaks that announce themselves in the output. Those are rarely the expensive ones.
Assertions on retrieval, not generation. A cross-user leak frequently produces harmless-looking answer text. The retrieved document is the evidence.
Include the revoked_user role with a propagation delay test: revoke, then immediately query. If it returns the document, you've measured your staleness window, and you have a finding.
Log at the retriever boundary
The minimum schema that makes an incident scopeable:
{
"session_id": "...", "turn_id": "...", "request_id": "...",
"subject": "...", "tenant_id": "...",
"entitlement_hash": "...",
"applied_filter": { "...": "the predicate actually sent to the index" },
"retrieved": [
{"doc_id": "...", "chunk_id": "...", "classification": "...",
"acl_tags": ["..."], "score": 0.83, "content_hash": "sha256:..."}
],
"cache_hit": false,
"expansion_denials": [],
"index_version": "...", "acl_sync_lag_ms": 1200
}
Log IDs, ACL tags and content hashes — not raw chunk text. Otherwise you've built a second copy of the corpus with weaker access controls than the first, and that becomes its own finding.
This is also what turns an auditor's question from unanswerable to trivial. "Was Tenant B's document ever placed in Tenant A's context?" is a query over retrieval logs. It is not a question output logs can answer, and it's the difference between a scoped incident and an unbounded one.
Mapping to audit obligations
If you're aligning to ISO/IEC 42001, the EU AI Act, or Japan's AI Guidelines for Business, this work maps cleanly:
| Control area | Evidence this architecture produces | |---|---| | Access control over data used by AI systems | Pre-filter predicates + entitlement resolution logs | | Data governance and lineage | Chunk-level classification + content hashes | | Logging and traceability | Session-correlated retrieval logs | | Incident scoping and response | Retrieval-side provenance, bounded blast radius | | Third-party / provider risk | Documented caching and residency behaviour |
The point isn't the paperwork. It's that the same artifacts that prevent the leak are the ones that prove you prevented it.
Checklist
- [ ] ACL predicate applied inside ANN search, not after top-k
- [ ] Engine filter behaviour verified under selective predicates, load-tested
- [ ] Entitlements resolved at query time from source, not from token claims
- [ ] Measured ACL propagation lag, with revocation test
- [ ] Parent expansion and summary indexes re-authorized
- [ ] Reranker operates only on entitled candidates
- [ ] Semantic and prompt caches namespaced by tenant + entitlement hash
- [ ] Agent memory tagged, re-authorized on read, invalidated on revocation
- [ ] Vector index treated as a copy of the corpus (encryption, residency, retention)
- [ ] Role × path test matrix with an independent entitlement oracle
- [ ] Retrieval-boundary logging, session-correlated, IDs and hashes only
At tinkrbox we build production RAG and agentic systems and run the security reviews that go with them — application and cloud security, LLM red teaming, and AI audits mapped to ISO/IEC 42001 and Japan's AI Guidelines for Business. AI agents accelerate the analysis; senior engineers own the findings and sign off.
If you're running multi-tenant retrieval in production, the semantic cache and the ACL propagation lag are where I'd look first. Neither shows up in a prompt-injection test.