Sub topic 14
Enforcing permissions in search results
This chapter assumes you know how the search index is built and kept in sync with the source of truth, and that you can read a bool query with filters. It also assumes you are familiar with sessions or tokens for authentication. The goal is to make sure a user never sees a search result, a snippet, a count, or a suggestion for something they are not allowed to read.
Why search is a special permission problem
In a normal read path, the application loads a record by ID and checks whether the caller may see it. Search inverts this. The engine returns many documents at once, ranked by relevance, and the application must decide which of them the caller may see.
The search index is also a second copy of your data. Every field you put in it can leak if you do not control access to it. Leaks do not only happen through the document body. They also happen through:
- Highlighted snippets that quote hidden text.
- Facet counts that reveal how many hidden documents match.
- Total hit counts ("1,204 results") that reveal that something exists.
- Autocomplete suggestions built from private titles.
- Pagination: if you drop results after the engine returns them, pages come back short or empty.
Permissions must therefore be applied inside the query, before ranking, counting, and pagination. They should not be applied as a cleanup step afterwards.
Three enforcement strategies
| Strategy | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Query-time filter | Store access metadata on each document and add a filter for the caller's identity | Simple, accurate counts and pages, one query | Index must be updated when permissions change |
| Post-filtering | Run the query, then check each hit against the source of truth | Always uses current permissions | Short pages, wrong counts, slow, may leak through facets |
| Separate indexes | One index per tenant or per permission group | Strong isolation | Many small indexes, expensive to manage |
Most systems use a query-time filter as the main control. Post-filtering is useful as a second check. Separate indexes fit hard tenant boundaries, such as one index per customer in a multi-tenant product.
Query-time filtering with access control lists
An access control list (ACL) is a list of who may read a resource. To filter at query time, copy a compact form of the ACL into each document. Two common shapes are:
- A list of allowed principals, such as user IDs and group IDs.
- A visibility level plus an owner, such as
public,team, orprivate.
Here is a mapping that stores the allowed principals as exact-match keywords, next to the full-text fields. Because these values are identifiers, they must be keyword fields and not analyzed text. Analysis could split or lowercase an ID and break the match.
PUT /documents
{
"mappings": {
"properties": {
"title": { "type": "text" },
"body": { "type": "text" },
"tenant_id": { "type": "keyword" },
"visibility": { "type": "keyword" },
"allowed_ids": { "type": "keyword" }
}
}
}A document that only the user u-17 and the group g-sales may read looks like this:
PUT /documents/_doc/501
{
"title": "Q3 pricing plan",
"body": "Draft discounts for enterprise accounts.",
"tenant_id": "acme",
"visibility": "restricted",
"allowed_ids": ["u-17", "g-sales"]
}At query time, the application looks up the caller's identity and group memberships, then builds the filter. The caller's identity must come from the authenticated session, never from a request parameter the client can change.
GET /documents/_search
{
"query": {
"bool": {
"must": [ { "match": { "body": "pricing" } } ],
"filter": [
{ "term": { "tenant_id": "acme" } },
{
"bool": {
"should": [
{ "term": { "visibility": "public" } },
{ "terms": { "allowed_ids": ["u-17", "g-sales", "g-all-staff"] } }
],
"minimum_should_match": 1
}
}
]
}
},
"size": 10
}The filter has two parts. The tenant filter is mandatory and isolates customers from each other. The inner should clause means "public, or the caller or one of their groups is in the allowed list". Filters do not affect scores, and the engine can cache them, so this adds little cost.
Build the filter on the server
Never let the client send the filter. Put the construction in one function so that every search path uses it. This sketch shows the idea in Python.
def acl_filter(user):
principals = [user["id"], *user["group_ids"]]
return [
{"term": {"tenant_id": user["tenant_id"]}},
{
"bool": {
"should": [
{"term": {"visibility": "public"}},
{"terms": {"allowed_ids": principals}},
],
"minimum_should_match": 1,
}
},
]
def build_search(user, text, size=10):
return {
"query": {
"bool": {
"must": [{"match": {"body": text}}],
"filter": acl_filter(user),
}
},
"size": size,
}
user = {"id": "u-17", "tenant_id": "acme", "group_ids": ["g-sales"]}
print(build_search(user, "pricing")["query"]["bool"]["filter"][0])Keeping this in a single function lowers the risk that a new endpoint, such as an export or an autocomplete route, forgets the filter.
Keeping permissions fresh
The ACL in the index is a copy. When permissions change in the source of truth, the index must change too. This is the same sync problem as for any other field, but the stakes are higher: a stale name is a nuisance, and a stale ACL is a data leak.
Consider these cases:
- A user is removed from a group. If group IDs are stored in each document, every document the group could read needs reindexing. For a large group this is a heavy update.
- A folder is shared or unshared. Documents inherit access from the folder, so every document in it needs an update.
- A user is fired or an account is disabled. Their access must stop quickly.
There are two ways to reduce the cost of these updates.
- Resolve groups at query time. Store only group IDs on documents, and look up the caller's current group list when searching. A membership change then takes effect immediately for every document, with no reindexing. Only changes to the document's own ACL require an index update.
- Index the parent, not the expansion. Store a
folder_idon each document and compute which folders the caller can read at query time. This works well for deep hierarchies but makes the query more complex.
Even with these, treat permission changes as high priority in your sync pipeline. Send them on a faster path than ordinary content edits, and monitor how long they take to reach the index. Because the index is eventually consistent, a revoked user may still see a result for a short time. Decide how long that window may be and measure it.
Defense in depth: verify against the source of truth
Because the index can lag, sensitive systems add a second check. After the engine returns the top hits, the application asks the source of truth, "may this user read these IDs?", and removes any that fail. This is cheap when you check a page of ten IDs in one batch call.
The query-time filter keeps pages full and counts correct in nearly all cases. The post-check catches the rare stale entry. Do not use the post-check alone. If it removes hits, the page is short, and the counts and facets it did not touch still include hidden documents.
When the post-check does remove a hit, log it. Each log entry points to a permission change that took too long to reach the index, and a rising rate is a sign that your sync pipeline needs attention.
Leaks outside the result list
Check each of these separately.
- Snippets. Highlighting quotes text from the body. If a document is filtered out, no snippet is produced. If a document is visible but one field is sensitive, exclude that field from highlighting and from the returned
_source. - Facets and counts. Aggregations run over documents that pass the query. Because the ACL filter is part of the query, the counts only include readable documents. A facet computed on a separate, unfiltered request would leak.
- Autocomplete. Suggestions are built from titles or past queries. If they come from a shared dictionary, a private title can appear to everyone. Apply the same ACL filter to suggestion queries, or build suggestions only from public data.
- Query logs and analytics. Logged queries may contain sensitive terms. Restrict who can read them.
- Error messages. "Document 501 is restricted" confirms that document 501 exists. Return the same response as for a missing document.
Common mistakes
- Putting the user ID in the request body and trusting it.
- Filtering results in application code after fetching, then reporting the engine's total hit count.
- Analyzing ID fields as
text, which makes thetermsfilter miss or match wrongly. - Forgetting a mandatory tenant filter on a new endpoint.
- Using the same index and the same filter code for internal admin search and customer search, so a flag mistake exposes everything.
- Letting permission updates wait in the same slow batch queue as bulk content updates.
Choosing a strategy
- Use a mandatory tenant filter for any multi-tenant product. Consider separate indexes if tenants are large, few, or have strict legal isolation needs.
- Use query-time ACL filters when permissions are per document or per group and results must have correct counts and full pages.
- Add a source-of-truth post-check when a leak is costly and you can afford one batch call per page.
- Prefer query-time group resolution when group membership changes often, so that those changes do not trigger mass reindexing.
Exercise
A user is removed from the group g-sales at 10:00. Documents in the index store the group ID g-sales in allowed_ids, and the application resolves the caller's groups from the source of truth on every search. At 10:01 the user searches. Will they see documents that were readable only through g-sales? What would change if the application instead copied the user's group list into each document?
Show answer
They will not see them. The filter is built from the caller's current groups, which no longer include g-sales, so documents that allow only g-sales fail the filter. This takes effect immediately with no reindexing. If the user's group list were copied into each document, those copies would stay stale until each document was reindexed, so the user could keep seeing the documents during that delay. That is why group membership is better resolved at query time.
Exercise
A team applies the ACL check after the search returns, removing hits the user cannot read. Page size is 10, and the response shows "total: 340". Name two problems this causes.
Show answer
Pages can come back with fewer than 10 results, or even empty, because hidden hits are removed after the engine has already filled the page. The total of 340 also counts documents the user cannot read, which reveals that hidden matches exist and shows a number that does not match what the user can page through. Facet counts calculated by the engine are similarly wrong. The fix is to apply the ACL as a filter inside the query.