Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 04 · 45 minutes

Enforce access control in retrieval

After this lesson you can
  • Filter chunks by the role of the user before they are ranked and before the prompt is built
  • Show that a filter after generation still leaks, with a fake model and with recorded answers
  • Test the filter with a table of user, question and allowed documents
Lab files of this lesson (22)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

In lesson 1 you asked the service for the salary bands, and it answered, because it does not know who asks. Marlowe Outdoor has three kinds of user: gus (a visitor, public documents only), sam (staff) and fay (finance). The privacy officer of the company asks for the fix, and a proof: "A visitor must never see a finance figure, not in the sources and not in the answer." You add the access check, put it in the right place, and test it with a table.

Recall

Lesson 3: which verdict keeps a chunk out of the index, `queue` or `reject`? And which one gives exit code 1?

Both keep the chunk out of the index. Only reject gives exit code 1, because a rejected chunk is broken. A queued chunk waits for a person, and that is normal work.

Lesson 1: what does `allow=None` mean in `Index.search`?

No restriction: every chunk is searched. This lesson gives allow a real value, a set of ids that the user may read.

The idea

Access control decides who may read what. A model cannot do it for you. It reads everything that it is given and can repeat all of it (lesson 3 of "Securing LLM applications" measured this for a secret in a prompt). So the check must run in code, before the text reaches the model.

There are three places where a filter can sit.

Place of the filterWhat the model readsResult
After generationAll chunks, finance includedLeaks. The answer holds the text, and hiding the sources does not remove it.
After ranking, before the promptOnly chunks that the user may read, but the ranking ran on all of themSafe for the text, but the slots can be taken by chunks that the filter removes, so a good answer may be missing.
Before rankingOnly chunks that the user may readSafe, and the best chunks of the user fill the slots.

OWASP names the permission-aware store as the control for cross-user leaks in LLM08:2025 Vector and Embedding Weaknesses, and it also covers LLM02 Sensitive Information Disclosure.

The filter before ranking
VisitorYour serviceProviderVisitor gusAccess filterIndexPromptModel1234VisitorYour serviceProviderVisitor gusAccess filterIndexPromptModel1234
  1. Visitor gus → Access filter: asks for the salary bands
  2. Access filter → Index: only the 4 public chunks are ranked
  3. Index → Prompt: the best allowed chunks
  4. Prompt → Model: no finance text is in the prompt

The rule is deny by default. A user who is not in the table reads nothing.

Worked example

1. Write the access rule

Save access.py. LEVEL gives each level a number, and a user may read a chunk when the level of the chunk is not higher than the level of the user. USERS.get(user) returns None for an unknown user, and LEVEL.get(None, -1) then gives -1, which is below every level. The result is a set (a collection of ids with no order and no repeats).

access.py

"""access.py: who may read which chunk."""
LEVEL = {"public": 0, "staff": 1, "finance": 2}
USERS = {"gus": "public", "sam": "staff", "fay": "finance"}     # user -> the highest level that the user may read


def allowed_ids(user, chunks):
    """The ids of the chunks that `user` may read. An unknown user may read nothing."""
    top = LEVEL.get(USERS.get(user), -1)
    return {c["id"] for c in chunks if LEVEL[c["level"]] <= top}
python3 -c "
from access import allowed_ids
from rag import load
kb = load()
for user in ['gus', 'sam', 'fay', 'mallory']:
    print(user, len(allowed_ids(user, kb)))
"
gus 4
sam 8
fay 12
mallory 0
Chunks of twelve that each user may read
fay12sam8gus4mallory0fay12sam8gus4mallory0

2. Put the filter in the wrong place, then in the right place

Save leak04.py. The model is a fake called echo: it returns the system message that it received. This is the worst case, a model that repeats everything, and it needs no real model, so every machine prints the same lines. late retrieves and generates for everybody, then hides the sources that the user may not see. early passes the allowed ids to the search.

The filter after generation
VisitorYour serviceProviderVisitor gusIndexPromptLate filterModel12345VisitorYour serviceProviderVisitor gusIndexPromptLate filterModel12345
  1. Visitor gus → Index: asks for the salary bands
  2. Index → Prompt: the best chunks, unfiltered, salary first
  3. Prompt → Model: the salary is in the prompt
  4. Model → Late filter: the answer holds 31,000
  5. Late filter → Visitor gus: only the sources are hidden

leak04.py

"""leak04.py: the filter in the wrong place, and in the right place. The model is a fake that returns its prompt,
the worst case: it repeats everything that it was given."""
from access import allowed_ids
from rag import Index, answer, load

kb = load()
index = Index(kb)
QUESTION = "How much does a store assistant earn?"


def echo(messages, **options):
    return messages[0]["content"]


def late(user, question):
    """The mistake: retrieve and generate for everybody, then hide the sources that the user may not see."""
    reply, ids = answer(index, question, model=echo)
    ok = allowed_ids(user, kb)
    return reply, [cid for cid in ids if cid in ok]


def early(user, question):
    """The fix: the user's own chunks are the only ones that are ranked."""
    return answer(index, question, allow=allowed_ids(user, kb), model=echo)


for name, pipeline in (("filter after generation", late), ("filter before ranking", early)):
    reply, sources = pipeline("gus", QUESTION)
    print(f"{name}: sources shown {sources}, finance figure in the answer: {'31,000' in reply}")
python3 leak04.py
filter after generation: sources shown [], finance figure in the answer: True
filter before ranking: sources shown [], finance figure in the answer: False

Both pipelines show no sources to the visitor, so a test that looks only at the sources passes them both. The first one still sends the salary to the model, and the answer carries it. The second never lets the chunk near the model.

3. Ask the real model

The same mistake with the real model. The pipeline runs the unfiltered answer and shows the sources that gus may see.

python3 -c "
from access import allowed_ids
from rag import *
kb = load()
reply, ids = answer(Index(kb), 'How much does a store assistant earn?')
print(reply, [c for c in ids if c in allowed_ids('gus', kb)])
"
A store assistant earns between 31,000 to 36,000 EUR per year. []

The visitor gets the figure and an empty list of sources.

4. Try to repair it with a filter on the answer

A tempting idea is to keep the pipeline and block answers that contain a forbidden figure. Save recorded-04.json. It holds five answers that a real model wrote for the salary question, asked in three different wordings. They are fixed text.

recorded-04.json

[
  "A store assistant earns between 31,000 to 36,000 EUR per year.",
  "A store assistant earns between 31,000 and 36,000 EUR per year.",
  "A store assistant earns thirty-one thousand to thirty-six thousand euros per year.",
  "Thirty-one thousand Euros.",
  "A store assistant typically earns around 31,000 to 32,000 EUR per year."
]

Save late_filter.py. re.findall returns every match of a pattern. Here it takes the figures out of the forbidden chunk, and blocked stops an answer that contains one of them.

late_filter.py

"""late_filter.py: a filter on the TEXT of the answer, run on answers that a real model wrote (recorded-04.json).
The five answers are replies to the same salary question, asked in three different ways."""
import json
import re

from rag import load

secret = next(c for c in load() if c["id"] == "fin-salary")["text"]
FIGURES = set(re.findall(r"\d[\d,]*\d", secret))                # 31,000 36,000 40,000 47,000


def blocked(answer):
    """The late filter: block an answer that contains a figure from the forbidden chunk."""
    return any(figure in answer for figure in FIGURES)


answers = json.load(open("recorded-04.json"))
for a in answers:
    print("blocked" if blocked(a) else "PASSED ", a)
print("answers that got through:", sum(not blocked(a) for a in answers), "of", len(answers))
python3 late_filter.py
blocked A store assistant earns between 31,000 to 36,000 EUR per year.
blocked A store assistant earns between 31,000 and 36,000 EUR per year.
PASSED  A store assistant earns thirty-one thousand to thirty-six thousand euros per year.
PASSED  Thirty-one thousand Euros.
blocked A store assistant typically earns around 31,000 to 32,000 EUR per year.
answers that got through: 2 of 5

The model wrote the figure in words, and the filter did not know the words. A filter on the output must guess every form of the secret. The filter before ranking has nothing to guess: the text was never in the prompt.

5. Test with a table

A row of the table is (user, question, ids). The ids are the only chunks that the search may return for that user and question. The test passes a row when the returned set is equal to the expected one, so it catches a leak and a chunk that was lost. Save test_access.py. With the word nofilter it runs the service of lesson 1 for comparison.

test_access.py

"""test_access.py: the access table. Each row is (user, question, the ids that the search may return).

    python3 test_access.py            the service with the filter
    python3 test_access.py nofilter   the service of lesson 1, for comparison
"""
import sys

from access import allowed_ids
from rag import Index, load

TABLE = [
    ("gus", "How much does a store assistant earn?", set()),
    ("gus", "What does Norrland Textiles charge for a jacket shell?", set()),
    ("gus", "When is delivery free?", {"pub-shipping", "pub-returns"}),
    ("sam", "How do I connect to the VPN?", {"stf-vpn"}),
    ("sam", "What does a team lead earn?", set()),
    ("fay", "How much does a store assistant earn?", {"fin-salary"}),
    ("fay", "What was the revenue in Q3?", {"fin-q3"}),
    ("mallory", "When is delivery free?", set()),
]

kb = load()
index = Index(kb)
failed = 0
for user, question, want in TABLE:
    allow = None if sys.argv[1:] == ["nofilter"] else allowed_ids(user, kb)
    got = {cid for _, cid in index.search(question, 3, allow)}
    failed += got != want
    print("ok  " if got == want else "FAIL", f"{user:8}{question[:42]:44}{sorted(got)}")
print(f"{len(TABLE) - failed} of {len(TABLE)} rows pass")
sys.exit(1 if failed else 0)
python3 test_access.py nofilter
echo "exit code $?"
python3 test_access.py | tail -1
FAIL gus     How much does a store assistant earn?       ['fin-salary']
FAIL gus     What does Norrland Textiles charge for a j  ['fin-supplier']
ok   gus     When is delivery free?                      ['pub-returns', 'pub-shipping']
ok   sam     How do I connect to the VPN?                ['stf-vpn']
FAIL sam     What does a team lead earn?                 ['fin-payroll', 'fin-salary']
ok   fay     How much does a store assistant earn?       ['fin-salary']
ok   fay     What was the revenue in Q3?                 ['fin-q3']
FAIL mallory When is delivery free?                      ['pub-returns', 'pub-shipping']
4 of 8 rows pass
exit code 1
8 of 8 rows pass

Your turn

The board of Marlowe Outdoor wants a fourth level, board, above finance, and a user bea who may read it. Save board.json, a single note for that level, and add the level and the user to access.py. Use kb.json and board.json together as the knowledge base. Then add two rows to the table of test_access.py for bea and fay, and make the full table pass.

board.json

[
  {"id": "brd-offer", "level": "board", "source": "finance-share", "owner": "finance", "date": "2026-11-10",
   "text": "Board note: the board is considering an offer for the shop of Norrland Textiles in the spring. The price is not agreed. Tell nobody outside the board."}
]

Use the question "What is the board considering in the spring?" for the checks below. The first check is about the table as printed in step 5, before you change it.

Check yourself

Why did the "filter after generation" pipeline pass a test that looks only at the sources?

The test looked at the wrong output. The leak was in the answer text, not in the list of sources. A test for access control must look at what the model received and at the whole reply, and it must try the forbidden question.

Why is a filter on the text of the answer weaker than a filter on the chunks?

The answer filter must recognise every form of the secret: digits, words, a rounding, a translation. The model can write any of them, and two of the five recorded answers passed. The chunk filter does not recognise anything: the forbidden text never enters the prompt.

What is the difference between filtering after ranking and before ranking?

After ranking, the best three chunks may include forbidden ones. The filter removes them and the user may get one or none. Before ranking, the three best allowed chunks fill the slots. Both keep the forbidden text out of the prompt, and the second also keeps the answers good. It also hides how the forbidden chunks rank, which lesson 5 uses.

The user `mallory` is not in `USERS`. What does `allowed_ids` return, and why is that the right choice?

An empty set. A user that the system does not know has no rights. If an unknown user got the public level by default, a typing error or a failed sign-in would give access. Deny by default fails safe.

Field notes

  • The user must come from the sign-in session on the server, and never from the request body or from the question text. A service that reads "I am fay" from the question has the same flaw as the model that follows an injected instruction.
  • Levels are the simplest model. Real systems also need groups and per-document lists. The filter stays the same: a set of ids or a metadata filter that the store applies before the similarity search.
  • Put the test table in your build. Add a row for every access bug that you ever find, and write the forbidden rows first. A table that has only "allowed" rows cannot fail on a leak.
  • A shared index with a filter relies on one if. For the highest levels, lesson 5 shows how a separate index for each level removes even that risk.
  • Check the whole reply, not only the sources: the answer, the log and any cache. A cached answer for a finance question can be served to a visitor who asks the same question.