# How Do You Enforce Access Control in RAG?

> Check who is asking before the search ranks anything, label every chunk with its permissions, and keep the model out of the decision. Explained for your AI interview.

**In short:** Work out who is asking on your own server, then apply their permissions as a filter inside the search query, on every request. Label each chunk with who may read it, and keep the model out of the decision about who sees what.

AI and LLM interview question Q140, Retrieval-augmented generation (RAG). Advanced, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-do-you-enforce-access-control-in-rag

## Say it in 30 seconds

Access control in RAG means the search only returns chunks the person asking may read. I take the user's identity from the server's login, never from the question. I turn it into a filter and apply it inside the search query, on every request, before anything is ranked. Each chunk carries a permission label from when it was indexed. And the model never decides who sees what, because text the model reads can steer it.

## Say it in 2 minutes

RAG searches your own documents first, then gives the best matches to a language model, which writes the answer from them. The risk sits in the search. If it ranks a file the user may not read, the model can quote that file, however harmless the answer looks.

So I enforce access in code, not in the prompt. The server takes the identity from the login system, along with the user's teams. That becomes a filter, and the filter goes into the search query itself, so the ranking never sees hidden chunks. Every chunk keeps a permission label from indexing time, so a confidential paragraph inside a public file keeps its own label.

Order matters. If the search reads everything and the app hides results afterwards, the user can get fewer results than they should. Counts and speed can also reveal that hidden files exist. OWASP's 2026 guidance on this risk says to scope the search inside the index query, and to validate it on the server.

Last, I fail closed, meaning I show nothing, when the identity is missing, never return raw match scores to the browser, update the labels when permissions change, delete the stored vectors (the number lists for each chunk) with their source, and treat vector backups as sensitive as the documents. Access control belongs to the system, and the model stays out of it.

## What is access control in RAG, in plain words?

RAG means your app searches your own documents first, then hands the best matches to a language model, which writes the answer from them. Access control is the rule that decides which matches a particular person may see.

Picture a records clerk at a hospital. A nurse asks for a patient file. The clerk checks the nurse's badge before opening the cabinet, and only then pulls the file. RAG needs that same order: check who is asking, then search.

Take an insurer, say with around 40,000 claim files and two regional claims teams. An adjuster on the north team should never see a medical note from a claim that belongs to another team, even when that note matches their question best. A search that ignores the team would return it happily.

- **Chunk:** A small piece of a document, stored and searched on its own.
- **Permission label:** A tag on each chunk that says which people or groups may read it.
- **Identity:** Who the logged-in user is, and which teams or groups they belong to.
- **Filter:** A condition the search must obey, such as only chunks labelled for the north team.
- **Index:** The searchable store where the chunks sit, each with its label.

## Where does the permission check have to go?

Inside the search, before anything is ranked, on every query. The search should only ever see the chunks the user may read. If the search reads everything and the app hides results afterwards, the leak has already happened before the hiding step.

> "similarity search frequently runs across the full index before access control is applied at the application layer" (OWASP, LLM09:2026)
>
> "Enforce tenant scoping inside the index query, not as a post-retrieval filter, and validate it server-side." (OWASP, LLM09:2026)

*Diagram, Filter before ranking, or after: The top path applies the permission filter inside the search, so only allowed chunks are ranked and the answer is full. The bottom path ranks everything first and hides results later, so the answer can run short, and the search has already read files the user must not see.*
1. The filter is applied inside the search, before ranking.
2. Only allowed chunks are ranked, so the answer is full.
3. Every chunk is ranked first, including files the user cannot see.
4. Hiding afterwards can leave too few results, and the search has read them.

OWASP's 2026 list gives this risk its own entry, LLM09, Vector and Embedding Weaknesses. It also says RAG is the most familiar case of it. The fix is to scope the search itself, so the question about access never comes second.

## How do you store permissions and apply them?

1. **Get the identity from the login:** Your login system says who is asking and which teams they belong to. The question text never sets this.
2. **Label every chunk when it is indexed:** Each chunk keeps its own label. A confidential paragraph inside a public file gets its own label, not the file's.
3. **Build the filter in code:** Turn the user's teams into the filter on your server, and add it to every search. No teams means no results.
4. **Search with the filter inside the query:** The index applies the filter during the search, the way OWASP asks (inside the index query), so hidden chunks are not returned. Check that your engine filters during the search, not after it.
5. **Re-index when permissions change:** When a file's permissions change, update the labels on its chunks. If you push your own chunks, re-index the affected ones, because Microsoft's guide says custom or push ingestion requires re-indexing the affected documents. Delete a file's chunks when the file is deleted.

> "Your application must authenticate users, obtain trusted principal and grant values, apply filters to every query, and prevent bypasses." (Microsoft, Azure AI Search guide)
>
> "Unresolved group memberships don't grant access." (Microsoft, Azure AI Search guide)

*Diagram, Labels travel with each chunk: One claim file is split into chunks when it is indexed. Each chunk keeps its own label, so the medical paragraph stays with the medical team even though it sits in a north file.*
1. The claim file is split into chunks at indexing.
2. The medical paragraph gets its own, stricter label.
3. The roof chunk goes in with the north team label.
4. The medical chunk goes in with the medical team label.

Here is the logic in a small program. It uses made-up claims and a stand-in search, with no network, and it runs the same question for the north team in both orders.

```python
# A simplified claims search: six chunks, each with the team allowed to read it.
CHUNKS = [
    {"id": 1, "team": "north", "text": "water damage kitchen claim paid in full"},
    {"id": 2, "team": "north", "text": "water damage roof claim under review"},
    {"id": 3, "team": "south", "text": "water damage flat medical notes claim"},
    {"id": 4, "team": "south", "text": "fire damage shop claim paid in part"},
    {"id": 5, "team": "north", "text": "water damage garage appeal claim open"},
    {"id": 6, "team": "south", "text": "water damage shop fraud check claim"},
]

def score(question, chunk):
    return len(set(question.split()) & set(chunk["text"].split()))

def search_filter_first(question, team, k=2):
    # The permission filter runs inside the search: only this team's chunks are ranked.
    allowed = [c for c in CHUNKS if c["team"] == team]
    ranked = sorted(allowed, key=lambda c: -score(question, c))
    return [c["id"] for c in ranked[:k]]

def search_filter_last(question, team, k=2):
    # Wrong order: rank everything first, then hide what the user may not see.
    ranked = sorted(CHUNKS, key=lambda c: -score(question, c))
    return [c["id"] for c in ranked[:k] if c["team"] == team]

question = "water damage medical claim"
print("filter first, north:", search_filter_first(question, "north"))
print("filter last, north: ", search_filter_last(question, "north"))
print("filter first, south:", search_filter_first(question, "south"))
```

Output:

```text
filter first, north: [1, 2]
filter last, north:  [1]
filter first, south: [3, 6]
```

> **Tip:** Asked how you would build it? Say the order out loud: identity from the login, a label on each chunk, the filter inside the query, and no results when the identity is missing.

## What does a weak design still leak?

Even with a filter in place, four leaks come up again and again. Name them in the interview, and say what you would change.

- **Counts and speed:** OWASP warns that an attacker can infer the existence, topic, and approximate volume of other customers' or teams' documents from result counts, score distributions, and timing, without ever seeing the documents.
- **Raw scores:** Returning the match score each chunk got (its similarity score) lets someone test whether a document is in the index. OWASP's advice is to keep those scores on the server.
- **Backups and copies:** Stored embeddings (the number lists that stand for each chunk's meaning) can be inverted to recover source text, so a vector backup needs the same care as the documents it came from.
- **A scope from the browser:** If the browser sends the team name, anyone can change it. OWASP is blunt: a client-supplied scope is a suggestion, not a control.

### How would you stop a sales rep seeing legal's notes?

A sales rep asks the bot about a supplier contract's price. The best matching chunk is a note from the legal team, marked for legal only.

- **Without layers: The note reaches the model.** The search ranks it first, and the prompt only asks the model to keep legal notes private. The model may still quote it.
- **With layers: The note never leaves the index.** The rep's teams become a filter built in code. The legal note is filtered out inside the query, and the model answers from the sales sheet.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Identity comes from the server's login, never from the question.
- [ ] A permission label on every chunk, set when it is indexed.
- [ ] The filter sits inside the search query, applied on every request.
- [ ] Fail closed: no identity, no chunks.
- [ ] Re-index on permission changes, and delete with the source.
- [ ] Watch for leaks through counts, scores and backups.

**Common traps**

- Trap: "Tell the model to only use documents the user may see." Better: The model is not a guard. Put the filter in code, inside the search query.
- Trap: "Filtering after the search works the same way." Better: It does not. Hidden files still get ranked, and the results can run out.
- Trap: "The vector database handles security for us." Better: Microsoft's guide says the security filter is just a string with no authentication behind it. Your server must check the login and build the filter.

## Can you spot the safe search call?

**Spot the safe call:** Which search call builds the team check from the logged-in user and applies it inside the search?

A. results = index.search(q, top=5); keep if r.team == request.json["team"]
B. results = index.search(q, filter=team_filter(user), top=5)  # user from the login
C. results = index.search(q, top=5); keep if r.team == user.team
D. results = index.search(q, filter=prompt_says_team, top=5)

**Answer:** B. Option 2 builds the filter from the logged-in user and applies it inside the query. Option 1 trusts the browser's team name. Options 3 and 4 hide results after ranking, or let the prompt choose the filter.

**Quick check:** A staff bot for an insurer keeps showing one team's notes to another. What is the first fix?

A. Add a line to the system prompt that forbids sharing other teams' notes.
B. Apply the user's team as a filter inside the search query, built from the login.
C. Switch to a larger model that follows rules better.
D. Lower the temperature so answers stay on topic.

**Answer:** B. The model is not the guard. A filter built on the server from the login stops the chunks before the model sees them. Prompts, model size and temperature do not change what the search returns.

## Can you answer these from memory?

**Flash cards**

- **Where does the permission check go?** Inside the search query, before ranking, on every request.
- **Where does the user's identity come from?** Your server's login system, never the question text.
- **What is a permission label?** A tag on each chunk saying who may read it, set when it is indexed.
- **Why not filter after the search?** Hidden files still get ranked, and the results can run out.
- **What if the identity is missing?** Fail closed: show nothing, or only public chunks.
- **Can the model enforce access?** No. Code enforces it, because text the model reads can steer it.

## Likely follow-up questions

- Q375 Design permission-aware search over an internal wiki. (full answer coming)
- Q354 What are the multi-tenant concerns? (full answer coming)
- Q148 What are vector and embedding security weaknesses? https://designervenkat.online/interview/ai/what-are-vector-and-embedding-security-weaknesses
- Q201 What is prompt injection? https://designervenkat.online/interview/ai/what-is-prompt-injection
- Q133 What are common RAG failure modes? https://designervenkat.online/interview/ai/common-rag-failure-modes

## Learn it in depth

- [RAG & Dynamic Filters](https://designervenkat.online/learn/ai-engineering/rag-and-dynamic-filters)
- [Unauthorized access](https://designervenkat.online/learn/ai-guardrails/unauthorized-access)
