Retrieval that respects permissions
Enterprise search is easy until two people ask the same question and should get different answers. How to build permission-aware retrieval that holds up across many tenants.
The first version of enterprise search usually takes an afternoon. Pull documents from a few connectors, chunk them, embed them, put them in a vector index, retrieve the top twenty for a question, hand them to the model. The answers are good. The demo is good.
Then someone in the room asks the obvious question: "So if I search for salary bands, what do I see?" And the honest answer is: everything the connector service account can see. Which, for a connector set up by an administrator, is nearly everything.
Every enterprise retrieval system eventually runs into the same wall. Two people ask the same question and should get different answers, because they're allowed to read different things. The model can't fix that. The prompt can't fix that. It has to be true of the data before the model ever sees it.
This is how to make it true, across many tenants and a lot of users, including deployments that run fully on-prem with no internet access at all.
The rule
There's exactly one rule, and everything else is implementation:
A chunk reaches the model only if the asking user can read the source document right now, in the source system.
"Right now" and "in the source system" are the hard parts. The index is a copy. Copies go stale. Permissions in a large organisation change constantly — people move teams, folders get re-shared, a contractor's access gets cut on their last day. The rule is about the source of truth, not the copy of it, and the whole design is about keeping the gap between the two small, measured, and closed at the moment it matters.
Two pipelines, one index
It helps to think of permission-aware retrieval as two separate pipelines that meet in the index. Ingest runs in the background and writes content and access together. Query runs per request and refuses to look at anything it can't justify.
Content and access are written together at ingest; the query path filters inside the search, then re-checks the handful of chunks it will actually cite.
Ingest: capture the ACL with the content
Every connector has to return two things for each document: the content, and who can read it. Not "the document is in the HR site", which is a hint, but the actual access control list — users, groups, and any organisation-wide grants — as the source system sees it.
Flatten that into principal tokens: short strings like u:4821, g:finance-team,
t:all. Every chunk of a document carries the document's tokens. Deny entries, where a source
supports them, become negative tokens that the query path treats as overriding.
from dataclasses import dataclass
@dataclass(frozen=True)
class Acl:
allow: frozenset[str]
deny: frozenset[str]
version: str # etag / change token from the source
synced_at: float
def to_tokens(entries, tenant_id: str) -> Acl:
allow, deny = set(), set()
for e in entries:
token = f"{e.kind}:{e.id}" # u:4821, g:finance-team
if e.kind == "everyone":
token = f"t:{tenant_id}" # never a global wildcard
(deny if e.effect == "deny" else allow).add(token)
return Acl(frozenset(allow), frozenset(deny),
version=entries.version, synced_at=entries.fetched_at)The highlighted lines guard against an easy, dangerous bug. Some sources express "everyone in the organisation" as a special principal. The lazy mapping is a global wildcard token. In a shared index that wildcard means everyone in every tenant. Scope it to the tenant, always, and add a test that fails the build if any connector emits an unscoped wildcard.
The version and timestamp matter later. They let you answer "how old is the permission I'm trusting?" for every single chunk.
Query: expand the principal, filter inside the search
At query time, resolve who's asking into the same token vocabulary: their user token, every group they're in (including nested groups, resolved transitively), and the tenant token. That set gets cached for a few minutes per user, because resolving nested group membership against a directory on every keystroke is how you take down an identity provider.
Then the important part: the token set goes into the search as a filter, not after it.
-- hybrid search over one tenant's chunks, filtered by access
SELECT id, doc_id, text,
0.7 * (1 - (embedding <=> $1)) + 0.3 * ts_rank(tsv, query) AS score
FROM chunks, plainto_tsquery('simple', $2) AS query
WHERE tenant_id = $3
AND acl_allow && $4::text[] -- any of the user's tokens
AND NOT (acl_deny && $4::text[]) -- no deny token matches
AND (labels && $5::text[]) IS NOT TRUE
ORDER BY score DESC
LIMIT 50;This is a simplified version — at scale you'd use a dedicated vector index with filtered approximate search rather than a single SQL statement — but the shape is the same. The filter is part of the retrieval, so the top fifty are the top fifty readable chunks.
Why post-filtering fails quietly
The alternative — retrieve the top twenty, then throw away what the user can't read — is tempting because it's simple and it works in every demo. It fails in a way that's hard to notice.
With post-filtering, a user who can read a small slice of the corpus gets almost nothing back. With pre-filtering, every retrieved chunk is usable.
In a big organisation, any one person can read a small fraction of the total corpus. Retrieve twenty chunks from the whole thing and most of them belong to other departments. Filter afterwards and you're left with one or two, or none. The model then does one of two things: answers from a single weak chunk, or says it couldn't find anything. Users conclude the assistant is bad at search. Nobody files a security incident, because nothing leaked. The failure looks like a quality problem, so it gets treated like one, and people start tuning embeddings and chunk sizes to fix a filtering problem.
You can paper over it by retrieving more — two hundred, then filter — but the fraction a user can read varies wildly. A senior official might see a third of the corpus; a new joiner might see two percent. There's no fixed over-fetch factor that works for both, and the expensive users are the ones with the least access.
One index or many
The other big decision is physical layout, and it's the one teams go back and forth on most.
| Index per tenant | Shared index + tenant filter | |
|---|---|---|
| Isolation | physical; a bug can't cross tenants | logical; one missing filter leaks |
| On-prem / air-gapped | natural fit, ships with the tenant | awkward, has to be split anyway |
| Ops cost | many small indexes to tune and back up | one big index, one set of knobs |
| Small tenants | wasteful, cold caches | efficient |
| Re-embedding | per tenant, staggered | one large job |
| Security review | easy to explain | needs a long conversation |
For a small number of large, security-sensitive tenants, I'd pick one index per tenant, and the deciding factor isn't performance. If some tenants run on-prem or fully air-gapped, they need their own index anyway, on their own hardware. Running the cloud tenants the same way means one code path, one set of tests, and a security story that fits on a slide: your documents are in your index; nothing else is. Inside each tenant the token filter still applies, because departments within one organisation should be separated as strictly as organisations are from each other.
For thousands of small tenants, I'd make the other choice. For a handful of large, security-sensitive ones, physical separation is worth the operational cost.
Group expansion is where it gets subtle
Most access in large organisations is granted to groups, not people. Groups contain groups. Some groups are dynamic — "everyone whose department is Finance" — and are computed by the directory on the fly. Getting expansion wrong in either direction is bad: too narrow and people can't find their own team's documents; too wide and you've leaked.
What works:
- Resolve at query time, not ingest time. Documents carry group tokens, not the expanded list of users. Expanding at ingest means every membership change rewrites every chunk that group can read. Expanding at query means one cached lookup per user.
- Cap nesting depth and alert on cycles. Directories in the wild contain group cycles and nesting twelve levels deep. Cap depth, log what you cut, and show it to tenant admins.
- Treat unresolved groups as no access. If the directory times out, the user gets fewer results, not more. Search degrades; it never widens.
- Mirror dynamic groups as static ones. Where the directory supports it, snapshot dynamic group membership on a schedule. Where it doesn't, exclude those grants and tell the admin which sources are affected.
export async function principals(user: User): Promise<string[]> {
const cached = await cache.get(`p:${user.id}`);
if (cached) return cached;
const tokens = new Set([`u:${user.id}`, `t:${user.tenantId}`]);
try {
for (const g of await directory.transitiveGroups(user, { maxDepth: 8 })) tokens.add(`g:${g.id}`);
} catch (err) {
// Fail closed: if the directory is down, search with user + tenant only.
log.warn("group expansion failed; narrowing", { user: user.id, err });
metrics.increment("principals.narrowed");
}
const list = [...tokens];
await cache.set(`p:${user.id}`, list, { ttlSeconds: 300 });
return list;
}The staleness window
All of the above is correct with respect to the indexed copy of the permissions. The rule says right now, in the source. The gap between those two is the staleness window, and it's the thing a good security reviewer will ask about first.
Nightly sync leaves a window of hours. Change events shrink it to minutes. A live check on cited documents closes it at the moment of answering.
The obvious first version syncs ACLs nightly with the content. Someone removed from a group at ten in the morning could, in principle, still retrieve that group's documents until two the next morning. It may never be exploited, but "in principle" is not an answer you want to give.
A sturdier design has three layers:
- Change events where the source supports them. Group membership changes and re-shares arrive within a minute or so and update tokens without touching content.
- A periodic reconcile that walks every document's ACL version and catches anything the events missed. Sources lose events. All of them, eventually.
- A live check at answer time on the handful of chunks the model will actually cite. Before the answer is shown, ask the source system directly whether this user can open these eight documents. It's a small number of cheap calls, and it turns "the copy says yes" into "the source says yes".
The live check is the piece I'd insist on if I could only keep one. It doesn't help recall — it can only remove things — but it means the staleness window can never reach the user. In an air-gapped deployment, where the source systems are on the same network, it's also fast.
Evaluating it
Permission bugs don't show up in normal relevance metrics. A system that leaks can score beautifully. So keep two evaluation sets per tenant, and let them measure different things.
Relevance, the usual one: questions with known supporting documents, scored on whether the answer is grounded in them. This is where the pre-filter versus post-filter gap shows up first.
Access, the one that matters here: a set of synthetic users with carefully constructed permissions, and questions whose correct answer is different for each of them — including "you can't see anything about this". Every release runs the access set, and a single chunk reaching a user who shouldn't see it fails the build. Not a regression in a dashboard. A failed build.
The synthetic users are the tedious part. Model a handful of archetypes per tenant: a new joiner with almost nothing, a manager with their team's folders, someone in two departments, a contractor with an expired grant, an administrator who can technically see everything but whose searches should still be scoped. Each archetype has a set of questions that would only be answerable with documents they're not supposed to have.
What I'd do differently
Make ACLs a connector contract from the first line of code. It's tempting to write connectors that return content first and permissions "later". Later always comes with surprises: sources whose APIs expose permissions differently from their UI, sharing links that grant access to anyone with the URL, inherited permissions that only resolve if you walk up the folder tree. Every connector should refuse to index a document it can't get an ACL for.
Build the access evaluation set before the relevance one. Relevance is what demos well, so it gets attention first. Access is what decides whether you're allowed to deploy at all.
Show the user what was filtered. Not the content — the fact. "Some documents matched but you don't have access to them" with a way to request access turns a confusing empty result into a useful one, and cuts a whole class of "search is broken" tickets.
None of this is novel. Search engines inside enterprises have dealt with document-level security for decades. What's new is that the consumer of the results is a model that will happily summarise whatever it's handed. That raises the cost of getting it wrong, and it makes the old, boring answer — filter inside the search, re-check before you show it — more important, not less.