Metadata filters & permission-aware retrieval

In one sentence

Attach metadata (tenant, ACL groups, date, type) to every chunk and enforce it as a hard filter inside the search, built in code, so the LLM never sees a document the user couldn't open.

Analogy: A records clerk who only opens the drawers your badge unlocks, versus one who pulls every file and asks you politely not to read the confidential ones.

ACLs travel with the chunks; the filter comes from the verified session, never from the prompt, and a final re-check guards the window.

How it works

  • The same filter mechanism serves relevance ("only 2024 policies") and authorization (the user's groups).
  • Build the authorization filter from the authenticated identity, never from the prompt or LLM tool arguments.
  • Pre-filter inside the ANN search; post-filtering leaves a user who can read 1% with ~1 of 100 hits.
  • Benchmark recall with realistic filters: very selective ones can degrade HNSW.
  • ACLs change: sync them via webhooks plus periodic reconciliation, or revoked access lingers until your next sync.

Check yourself

Answer to mark it learned; your answers aren't scored.

At 9:00 a manager removes a contractor from a Drive folder. At 15:00 the contractor's RAG assistant still quotes that folder. Chunks carry allowed_groups, and ACLs are re-synced by a nightly batch. Best fix?

Go deeper

Full explanation

Every chunk carries metadata copied from its source at ingestion: tenant_id, allowed_groups, doc_type, updated_at, region. At query time you pass a filter with the vector or keyword search, so only eligible chunks get scored.

One mechanism, two jobs:

  • Relevance filters: "only 2024 policies", "only product X manuals", often extracted from the query by Query transformation (rewrite, HyDE).
  • Authorization filters: the user's groups must overlap the chunk's allowed_groups. This is security, so the filter is built in code from the authenticated identity: never from the prompt, never from LLM tool arguments, and never by asking the model to ignore what it shouldn't see. Once forbidden text reaches the window, Prompt injection (direct & indirect) can get it out.

Pre-filter vs post-filter. Pre-filtering restricts the ANN search to allowed vectors and returns k results. Post-filtering searches first and drops forbidden hits: a user who can read 1% of the corpus keeps ~1 of 100. Use an engine with native filtered search (Qdrant payload indexes, pgvector iterative scans, Pinecone metadata filters) and benchmark recall with realistic filters, since very selective ones can degrade HNSW.

ACLs change. Sync them from the source systems (SharePoint, Google Drive, Confluence) via webhooks plus a periodic full reconciliation, and re-check permissions on the final chunks when staleness matters.

Code ACL pre-filter in Qdrant, plus a canary leak test
pythonACL pre-filter in Qdrant, plus a canary leak test
from qdrant_client import QdrantClient, models

client = QdrantClient(url="http://localhost:6333")

def acl_conditions(user) -> list[models.FieldCondition]:
    # From the verified session -- never from the prompt or LLM tool arguments
    return [
        models.FieldCondition(key="tenant_id",
                              match=models.MatchValue(value=user.tenant_id)),
        models.FieldCondition(key="allowed_groups",  # any shared group grants access
                              match=models.MatchAny(any=user.groups)),
    ]

def retrieve(user, query: str, k: int = 20, extra=()) -> list:
    hits = client.query_points(
        collection_name="chunks",
        query=embed(query),
        # Pre-filter: ANN only visits allowed points, so we still get k results.
        # Relevance filters (date, doc_type) are AND-ed with the ACL, never instead.
        query_filter=models.Filter(must=[*acl_conditions(user), *extra]),
        limit=k,
    ).points
    # Defense in depth: re-check against the source of truth before the prompt
    return [h for h in hits if acl_service.can_read(user, h.payload["doc_id"])]

def test_canary_never_reaches_prompt():
    # A doc only "hr-restricted" can read, queried verbatim by an outsider
    index_doc("CANARY-7f3a: Q3 reorg plan", tenant_id="t1",
              allowed_groups=["hr-restricted"])
    outsider = User(tenant_id="t1", groups=["engineering"])
    prompt = build_prompt(outsider, "What is the Q3 reorg plan?")
    assert "CANARY-7f3a" not in prompt
Real example

An internal assistant indexes ~3M Confluence and Drive chunks with allowed_groups. An engineer asks about "reorg plans". With post-filtering, the top 20 are all HR-only pages; every hit is dropped and the bot replies "no information", after the HR page titles already landed in a debug log. With pre-filtering on allowed_groups, the search returns 20 chunks the engineer can read, such as the public org-change FAQ. When a document owner unshares a folder, a webhook rewrites its chunks' allowed_groups within minutes instead of waiting for the nightly re-index.

Trade-offs +3 · −3

+ You gain

  • Deterministic access control: forbidden text never enters the window, so no prompt can leak it.
  • Relevance filters improve precision and speed by shrinking the candidate set.
  • A shared index with a mandatory tenant filter serves thousands of small tenants cheaply.

− You pay

  • ACL sync is real engineering: connectors, group expansion, webhooks, staleness windows.
  • Very selective filters can slow ANN or hurt its recall; post-filtering can return fewer than k.
  • Shared index: one missing filter is a cross-tenant leak. Per-tenant indexes: isolation, but many small indexes to run.

Use it when

Any RAG over data with mixed visibility: multi-tenant SaaS, enterprise search over Drive, SharePoint or Confluence, HR, legal and customer data. Relevance filters whenever queries carry structure such as dates, products or regions.

Avoid it when

A fully public corpus with a single audience, like a public docs site or help center: authorization filtering adds sync cost for nothing. Relevance filters still apply.

Numbers to know 3
  • Post-filter math: a user who can read a fraction p of the corpus keeps ~p·k of k hits; 1% of 100 ≈ 1.
  • Revocation delay = your ACL sync interval: a nightly batch can keep serving revoked access for up to ~24 h.
  • pgvector 0.8+ adds iterative index scans so filtered HNSW queries keep returning enough rows.
Common pitfalls 4
  • Enforcing access in the system prompt ("don't reveal HR docs"): the text is already in the window.
  • Taking the tenant or user from a client-controlled field or from LLM tool arguments instead of the verified session.
  • Storing user ids on chunks: every membership change forces a re-index. Store group ids and resolve the user's groups at query time.
  • Forgetting side channels: titles in citations, a semantic cache shared across users, logs and eval traces.
Interview questions 3

Answer out loud first, then reveal.

How do you guarantee RAG never shows a user a document they can't access?Show answer

I treat it as authorization, not prompting. Every chunk carries tenant and group ACLs synced from the source system. The retriever builds the filter in code from the authenticated session, never from user input or LLM arguments, and applies it inside the search, so forbidden text never enters the prompt. I re-check permissions on the final chunks, scope caches and logs per user, and keep a canary test in CI: a doc only one group can read, queried verbatim by an outsider, must never appear in the prompt.

Per-tenant index or one shared index with a tenant filter?Show answer

It depends on tenant count and isolation requirements. Per-tenant indexes or namespaces give hard isolation, trivial deletion when a customer leaves, and no noisy neighbors, but thousands of small indexes are costly to run and some engines cap them. A shared index with a mandatory tenant filter is cheaper and scales to many small tenants, but one missing filter is a cross-tenant leak. My default: a shared index partitioned by tenant, the filter injected by a wrapper the app can't bypass, and dedicated indexes for large or regulated tenants.

Pre-filter or post-filter?Show answer

Pre-filter by default: the engine only considers allowed vectors, so I get k results. Post-filter breaks when a user sees a small slice: search 100, drop 99, answer from one chunk or none. The catch is ANN performance under very selective filters, since HNSW traversal can get stuck in disallowed regions. So I pick an engine with native filtered search, benchmark recall@k under real filters, and fall back to exact search when the allowed set is small enough.