A retrieval-augmented assistant is often the first feature in a company that searches across everyone's documents at once. The old product had one permission check per page load. The new one embeds every document into a single index and answers questions from whatever comes back as most similar. If that index ignores who is asking, the assistant becomes a polite way to read files the user was never allowed to open.
The tempting fix is a sentence in the system prompt: "Only use documents the user is allowed to see." That sentence cannot work, because by the time the model reads it, the forbidden text is already in the context window. This article walks through where the permission check belongs, how to implement it so it fails closed, and how to test that it holds.
The check belongs before the model, not inside it
A language model is not an enforcement point. It has no reliable way to know which passages the current user may see, and any text placed in its context can be paraphrased, summarized or quoted in an answer. A prompt-level instruction is advice. An access-control decision has to be code that runs on the retrieval path and removes unauthorized chunks before prompt assembly.
There are three places such a filter can live, and they fail differently:
- Pre-filter in the vector query. The search is restricted to chunks whose access metadata matches the caller. Unauthorized chunks are never scored or returned.
- Post-filter after retrieval. You fetch the top k by similarity, then drop what the user cannot see. This is simple, but it has a quality problem: if the top 10 are mostly restricted, you are left with two usable chunks, or none, even though plenty of permitted and relevant text exists.
- Separate indexes per tenant or per group. Isolation is strongest, and cost and operational overhead are highest.
A sound default is a pre-filter for the normal case, plus a post-filter as a second, independent check. The pre-filter gives good recall. The post-filter is a safety net that catches stale metadata and bugs in the first layer, and it should log loudly when it removes anything, since that means the first layer let something through.
OWASP lists this class of problem as "Vector and Embedding Weaknesses" and recommends fine-grained, permission-aware vector stores and strict partitioning of datasets (see Further reading).
Store access metadata on every chunk
Filtering needs something to filter on. When you chunk a document, copy the access information onto each chunk, not just onto the parent document record:
@dataclass
class Chunk:
chunk_id: str
doc_id: str
text: str
tenant_id: str # hard boundary, never crosses
allowed_groups: list[str] # groups that may read this doc
acl_version: int # version of the doc's ACL when indexedThe reason for allowed_groups rather than a list of user ids is churn. Group membership changes constantly, and re-indexing every chunk because someone changed teams is expensive. Resolve the user's groups at query time from your identity system, and match against stable group ids stored in the index.
The acl_version field supports the staleness check described below. Make tenant_id mandatory in the schema, so an indexing job that forgets it fails at write time instead of silently creating a world-readable chunk.
Build the filter from the server-side identity, and deny by default
The filter must be derived from the authenticated session, never from anything the client or the model can influence. This matters most in agent setups where the model calls a search_docs tool: do not give that tool a user_id or filter parameter that the model fills in. The model might be prompt-injected, and even a well-behaved model can hallucinate an argument. The tool's code should read identity from the request context instead.
def search_docs(query: str, ctx: RequestContext, k: int = 8) -> list[Chunk]:
principal = ctx.principal # set by auth middleware, not by the model
if principal is None:
raise PermissionError("no authenticated principal")
groups = identity.resolve_groups(principal.user_id) # fresh, short TTL cache
flt = {
"tenant_id": principal.tenant_id, # mandatory equality
"allowed_groups": {"any_of": groups},
}
# Over-fetch so the post-filter has headroom without hurting recall.
candidates = index.query(embed(query), top_k=k * 3, filter=flt)
visible = []
for c in candidates:
if authz.can_read(principal, c.doc_id, expected_acl=c.acl_version):
visible.append(c)
else:
log.warning("post-filter dropped chunk", chunk=c.chunk_id,
user=principal.user_id) # should be ~never
return visible[:k]Three details carry most of the weight here.
Deny by default. If the group list is empty, the filter must match nothing, not everything. Many query builders treat an empty "any of" list as "no constraint", which turns a failed identity lookup into a full-corpus search. Add an explicit guard: when groups is empty and the document is not public, return no results. The OWASP authorization guidance makes the same point, that access should be denied by default and permission validated on every request.
The authoritative check is the source system. authz.can_read asks the system of record, such as the document store or the permission service, whether this principal can read this document right now. The index metadata is a cache of that answer, and caches go stale. That is what acl_version is for: if the source's current version differs from the version recorded at indexing time, treat the chunk as unreadable until it is re-indexed.
Over-fetching trades cost for recall. Asking for k * 3 candidates costs a little more per query, but it keeps the post-filter from starving the prompt. The multiplier is a tuning knob; measure how often the post-filter drops anything and how often you end up with fewer than k results.
What this approach does not cover
Be honest about the limits, because each one is a place a leak can still occur:
- Caches. If you cache answers (see semantic caching), key the cache on the permission scope, not just the query. Otherwise user A's answer, built from A's documents, can be served to user B who asks a similar question.
- Derived content. Summaries, titles, and "related questions" generated from restricted documents inherit the restriction. Store them with the same ACL as their source.
- Revocation lag. When a document's permissions tighten, there is a window until the index catches up. The source-of-truth check closes it for reads, but only if you actually run it on every request. If that is too slow at your scale, accept a short, explicit staleness window and write it down as a decision, rather than discovering it in an incident.
- Logging and traces. Prompts logged for debugging contain retrieved text. Give the logs the same access scope as the data they carry.
- Inference from absence. A response such as "I found nothing about the Q3 layoff plan" can confirm that something exists. For sensitive collections, return the same generic "no results" message whether the cause is permissions or no match.
Test it with a cross-user matrix
Permission bugs hide because ordinary evals use one test user with broad access. You need tests where two users with different rights ask the same question and the results are compared.
Set up a small fixture corpus with deliberately overlapping topics:
| doc | tenant | groups | |---|---|---| | pricing-public | acme | everyone | | pricing-internal | acme | finance | | pricing-other-tenant | globex | everyone |
Then assert on the retrieved chunks, not on the generated text, since retrieval is where the decision is made:
def test_finance_sees_internal_pricing():
ids = {c.doc_id for c in search_docs("pricing", ctx_for("alice", groups=["finance"]))}
assert "pricing-internal" in ids
def test_engineer_does_not_see_internal_pricing():
ids = {c.doc_id for c in search_docs("pricing", ctx_for("bob", groups=["eng"]))}
assert "pricing-internal" not in ids
assert "pricing-public" in ids # still gets useful results
def test_other_tenant_never_appears():
ids = {c.doc_id for c in search_docs("pricing", ctx_for("bob", groups=["everyone"]))}
assert "pricing-other-tenant" not in ids
def test_empty_groups_fails_closed():
ids = {c.doc_id for c in search_docs("pricing", ctx_for("eve", groups=[]))}
assert ids <= {"pricing-public"} # public only, never everything
def test_revoked_acl_is_not_returned():
revoke("pricing-internal", group="finance") # index not yet updated
ids = {c.doc_id for c in search_docs("pricing", ctx_for("alice", groups=["finance"]))}
assert "pricing-internal" not in idsThe last test is the one teams skip, and it is the one that proves the source-of-truth check does something. Add one more at the end-to-end level: ask the full assistant a question whose answer exists only in a document the user cannot read, and assert the response does not contain a distinctive marker string planted in that document. Planting a unique canary string in each restricted fixture makes leaks trivially greppable in test output and in production monitoring.
Checklist
- Enforce access in code on the retrieval path; treat prompt instructions as irrelevant to security.
- Copy tenant and group metadata onto every chunk; make
tenant_idrequired at write time. - Derive the filter from the authenticated session; never let the model supply identity or filter arguments.
- Pre-filter for recall, post-filter as an independent safety net, and alert when the post-filter fires.
- Fail closed: empty group lists and failed identity lookups return nothing private.
- Verify against the source system, using an ACL version to detect stale index metadata.
- Scope caches, derived summaries, logs and traces to the same permissions as their sources.
- Keep a cross-user test matrix with overlapping topics, revocation cases and planted canary strings.
Further reading
- OWASP GenAI Security Project, "LLM08:2025 Vector and Embedding Weaknesses": https://genai.owasp.org/llmrisk/llm082025-vector-and-embedding-weaknesses/
- OWASP Cheat Sheet Series, "Authorization Cheat Sheet": https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html
Comments (0)
No comments yet — be the first.
Sign in to leave a comment.