Lesson 10 · 55 minutes
Build a secure RAG service and its test suite
- Combine provenance, quarantine, redaction, access control and a safe index in one service
- Write a test suite that fails when a control is removed
- Run the service with the real model and read what it held back
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
Marlowe Outdoor goes live on Monday. Your lead asks for one service file, one test file, and a result: "If someone changes the code on Tuesday and breaks a control, the tests must say so." The pieces exist, one for each lesson. You join them into a service, write a suite that attacks it, and prove that the suite notices when you take a control out.
Recall
Lesson 9: what does `govcheck.py catalogue` give the build, and when does it fail?
An exit code. It is 1 when a page has no row, a row has no page, an owner or a retention period is missing, a level, a source or an owner disagrees with the knowledge base, or a review is overdue. A change that adds a page without an owner then stops the build.
Lesson 8: where does the access filter sit, and why not in the gateway?
In retrieval, before the ranking, because only there the user and the chunks meet. A filter in the gateway sees only the finished answer.
The idea
The finished service is a small class that calls the pieces in the order of the pipeline. Each file comes from one lesson.
| Piece | File | Lesson |
|---|---|---|
| Search, prompt, index | rag.py | 1 |
| Screen: provenance, quarantine, hashes | provenance.py | 3 |
| Access rule | access.py | 4 |
| Safe index: cap per document, stuffing check | safeindex.py | 5 |
| Redaction and a clean log | redact.py | 6 |
| Quality and leakage measure | evaluate.py | 7 |
The service does not call keep_recent (6), archcheck.py (8) or govcheck.py (9): run them as separate jobs in the build. It does not use partition.py (5) either. One shared index with the filter of lesson 4 is simpler. The user argument stands for a sign-in that your gateway must check: the lab does not build one.
The new file securerag.py adds no new control. It decides the order: screen, clean, index; then, for each question, redact the question, filter by user, rank, write the prompt, answer, and log. A test suite is a program that attacks the service and returns pass or fail for each attack. It uses the fake model of lesson 4 that returns its own prompt: the worst case, with no randomness, so the code decides the result.
- Question → Redact: private data out first
- Redact → Access filter: only the user's chunks
- Access filter → Ranking: the safe index
- Ranking → Prompt: sources below the rules
- Prompt → Reply: the answer and its sources
Worked example
1. Approve the tickets
The tickets of lesson 6 are a source now, so a person must approve them like the pages of lesson 3. You are that person: you have read the ten tickets. The command adds their hashes to approvals.json.
python3 provenance.py approve tickets.json approvals.json all22 chunks approved2. Write the service
Save securerag.py. rebuild screens the chunks, keeps the verdicts that are not accept in held, redacts the accepted ones, and builds the safe index. delete removes a chunk from the source list and rebuilds (lesson 8). retrieve returns the ids for one user and one question, with the filter before the ranking and with k capped at MAX_K, so that a caller cannot ask for a prompt of any size. ask redacts the question first, logs it, and returns only the answer and its sources: no score. A user who may read nothing for this question gets I do not know. and the model is not called.
securerag.py
"""securerag.py: the finished service. Provenance and quarantine, redaction, access control before ranking,
a safer index, sources below the rules, a log without private data, and no scores in the reply."""
import json
from access import allowed_ids
from llm import chat
from provenance import screen
from rag import build_prompt, load
from redact import redact, safe_log
from safeindex import SafeIndex
NO_ANSWER = "I do not know."
MAX_K = 5 # a caller may ask for fewer chunks, never for more
class Service:
def __init__(self, chunks, approvals, model=chat):
self.source, self.approvals, self.model, self.log = list(chunks), approvals, model, []
self.rebuild()
def rebuild(self):
"""Screen, clean and index the chunks that exist now. Deleting a chunk calls this too."""
verdicts = screen(self.source, self.approvals)
self.held = {cid: why for cid, (verdict, why) in verdicts.items() if verdict != "accept"}
clean = [dict(c, text=redact(c["text"])[0]) for c in self.source if verdicts[c["id"]][0] == "accept"]
self.index = SafeIndex(clean)
for cid in self.index.rejected:
self.held[cid] = "looks stuffed"
def delete(self, cid):
self.source = [c for c in self.source if c["id"] != cid]
self.rebuild()
def retrieve(self, user, question, k=3):
"""The ids that may go into the prompt: the user's own chunks, ranked after the filter."""
allow = allowed_ids(user, list(self.index.chunks.values()))
return [cid for _, cid in self.index.search(question, min(k, MAX_K), allow)]
def ask(self, user, question, k=3):
"""The reply is the answer and its sources. It holds no score."""
question = redact(question)[0]
ids = self.retrieve(user, question, k)
safe_log(self.log, user, f"{question} -> {ids}")
if not ids:
return {"answer": NO_ANSWER, "sources": []}
messages = build_prompt(question, [self.index.chunks[cid] for cid in ids])
return {"answer": self.model(messages, temperature=0.7, seed=0, max_tokens=80).strip(), "sources": ids}
INBOX = ["kb.json", "tickets.json", "poison.json", "poison2.json", "promo.json"] # every file that the sources delivered
def build():
return Service([c for path in INBOX for c in load(path)], json.load(open("approvals.json")))
if __name__ == "__main__":
service = build()
print("held back:", service.held)
for user, question in [("gus", "When is delivery free?"), ("gus", "How much does a store assistant earn?"),
("fay", "How much does a store assistant earn?")]:
print(user, question, "->", service.ask(user, question))3. Write the test suite
Save test_securerag.py. Each function named test_... is one attack or property, and returns true when the service holds. The last block finds them all (globals() lists every name in the file), runs them, and ends with the exit code. dict(a, **b) is a copy of a with the entries of b added. A test that crashes because a control is gone counts as a failure: try and except catch the error, so that the run goes on and prints FAIL. JUNK is the three bad files of lessons 2 and 5.
test_securerag.py
"""test_securerag.py: the test suite of the finished service. Run: python3 test_securerag.py
It uses a fake model that returns its own prompt, so every result is decided by code and is the same on every machine."""
import json
import sys
from evaluate import MAX_LEAKS, MIN_PRECISION, run
from provenance import chunk_hash
from rag import load
from securerag import MAX_K, NO_ANSWER, Service
APPROVALS = json.load(open("approvals.json"))
KB = load("kb.json") + load("tickets.json")
JUNK = load("poison.json") + load("poison2.json") + load("promo.json")
calls = []
def echo(messages, **options):
calls.append(messages)
return messages[0]["content"]
def service(chunks=KB, approvals=APPROVALS):
calls.clear()
return Service(chunks, approvals, model=echo)
def test_junk_is_held():
held = service(KB + JUNK).held
return all(c["id"] in held for c in JUNK)
def test_no_provenance_is_held():
no_level = {k: v for k, v in KB[0].items() if k != "level"}
bad = [dict(KB[0], id="x-1", owner=""), dict(no_level, id="x-2"), dict(KB[0], id="x-3", level="internal"),
dict(KB[0], id="x-4", source="pastebin")]
held = service(KB + bad).held
return (held["x-1"], held["x-2"], held["x-3"], held["x-4"]) == ("no owner", "no level", "bad level", "unknown source")
def test_edited_chunk_is_held():
edited = [dict(KB[0], text=KB[0]["text"].replace("30 days", "90 days"))] + KB[1:]
return service(edited).held["pub-returns"] == "changed since review"
def test_relabelled_chunk_is_held():
relabelled = [dict(c, level="public") if c["id"] == "fin-salary" else c for c in KB]
return service(relabelled).held["fin-salary"] == "changed since review"
def test_stuffed_chunk_is_held_even_when_approved():
approved = dict(APPROVALS, **{c["id"]: chunk_hash(c) for c in load("promo.json")})
return all(service(KB + load("promo.json"), approved).held[c["id"]] == "looks stuffed" for c in load("promo.json"))
def test_no_leak_and_good_precision():
s = service()
precision, leaks = run(lambda user, q, k: s.retrieve(user, q, k), json.load(open("questions.json")),
{c["id"]: c["level"] for c in KB})
return leaks <= MAX_LEAKS and precision >= MIN_PRECISION
def test_unknown_user_gets_nothing():
s = service()
return s.retrieve("mallory", "When is delivery free?") == [] and s.ask("mallory", "When is delivery free?")["answer"] == NO_ANSWER and not calls
def test_forbidden_text_never_reaches_the_prompt():
s = service()
reply = s.ask("gus", "How much does a store assistant earn?")
return "31,000" not in reply["answer"] and not any("31,000" in m["content"] for msgs in calls for m in msgs)
def test_private_data_is_not_indexed():
text = json.dumps(service().index.chunks)
return "4111" not in text and "@example" not in text and "[CARD]" in text
def test_question_and_log_are_clean():
s = service()
s.ask("sam", "My card 4111 1111 1111 1111 was declined. Who is jo@example.com?")
return "4111" not in s.log[0] and "jo@" not in s.log[0] and "4111" not in json.dumps(calls)
def test_reply_has_no_score():
return set(service().ask("fay", "What was the revenue in Q3?")) == {"answer", "sources"}
def test_card_like_order_number_stays():
return "1234 5678 9012 3456" in service().index.chunks["tkt-4403"]["text"]
def test_one_chunk_per_document():
parts = [{"id": f"pub-guide#{n}", "level": "public", "source": "shop-wiki", "owner": "web-team", "date": "2026-11-20",
"text": f"Delivery guide, part {n}: delivery is free for large orders and takes three days."} for n in (1, 2, 3)]
approved = dict(APPROVALS, **{c["id"]: chunk_hash(c) for c in parts})
ids = service(KB + parts, approved).retrieve("gus", "When is delivery free?", 5)
return sum(cid.startswith("pub-guide#") for cid in ids) == 1
def test_k_has_a_ceiling():
return len(service().retrieve("fay", "What are the days and prices of delivery and returns?", 13)) == MAX_K
def test_deleted_chunk_leaves_the_index():
s = service()
s.delete("pub-hours")
return "pub-hours" not in s.index.chunks and "pub-hours" not in s.retrieve("gus", "When is the shop open on Saturday?")
if __name__ == "__main__":
tests = [(name, fn) for name, fn in sorted(globals().items()) if name.startswith("test_")]
passed = 0
for name, fn in tests:
try:
ok = fn()
except Exception as error: # a control that is gone can make a test crash: that is a failure too
ok = False
name += f" ({type(error).__name__})"
passed += ok
print("PASS" if ok else "FAIL", name)
print(f"{passed} of {len(tests)} tests pass")
sys.exit(0 if passed == len(tests) else 1)4. Run the suite
python3 test_securerag.py
echo "exit code $?"PASS test_card_like_order_number_stays
PASS test_deleted_chunk_leaves_the_index
PASS test_edited_chunk_is_held
PASS test_forbidden_text_never_reaches_the_prompt
PASS test_junk_is_held
PASS test_k_has_a_ceiling
PASS test_no_leak_and_good_precision
PASS test_no_provenance_is_held
PASS test_one_chunk_per_document
PASS test_private_data_is_not_indexed
PASS test_question_and_log_are_clean
PASS test_relabelled_chunk_is_held
PASS test_reply_has_no_score
PASS test_stuffed_chunk_is_held_even_when_approved
PASS test_unknown_user_gets_nothing
15 of 15 tests pass
exit code 05. Take a control out and see the suite fail
A suite that never fails proves nothing. Remove the access filter from retrieve. sed -i.bak edits the file in place and keeps the old one as securerag.py.bak. Run the suite, then put the file back. grep -E keeps the lines that match a pattern, and | in the pattern means "or": here the lines with FAIL or of.
sed -i.bak 's/, allow)/)/' securerag.py
python3 test_securerag.py | grep -E "FAIL|of"
mv securerag.py.bak securerag.pyFAIL test_forbidden_text_never_reaches_the_prompt
FAIL test_no_leak_and_good_precision
FAIL test_unknown_user_gets_nothing
12 of 15 tests passOne removed filter fails three tests, which look at it from three sides: the prompt, the labelled set and the unknown user. Try the same with two other controls, the cap of one chunk for each document and the Luhn check. Each one fails one test.
sed -i.bak 's/if doc not in seen:/if True:/' safeindex.py
python3 test_securerag.py | grep -E "FAIL|of"
mv safeindex.py.bak safeindex.py
sed -i.bak 's/if luhn(/if True or luhn(/' redact.py
python3 test_securerag.py | grep -E "FAIL|of"
mv redact.py.bak redact.pyEach run prints one FAIL line and 14 of 15 tests pass.
6. Run the service with the real model
The service builds from every file in INBOX, the good ones and the bad ones. python3 securerag.py prints what it held back, and three real answers. The model call takes several seconds each.
python3 securerag.pyheld back: {'pub-returns-update': 'reads like an instruction', 'pub-shipping-update': 'not reviewed', 'pub-promo#1': 'not reviewed', 'pub-promo#2': 'not reviewed', 'pub-promo#3': 'not reviewed'}
gus When is delivery free? -> {'answer': 'Delivery is free for orders of 80 EUR or more.', 'sources': ['pub-shipping', 'pub-returns']}
gus How much does a store assistant earn? -> {'answer': 'I do not know.', 'sources': []}
fay How much does a store assistant earn? -> {'answer': 'A store assistant earns between 31,000 to 36,000 EUR per year.', 'sources': ['fin-salary']}Five bad chunks were held for a person to review. The visitor gets the right policy and no finance data. The finance user gets the salary. The answers of the real model can differ in wording on your machine.
Your turn
Needs: approvals.json with the tickets (step 1) and promo.json (lesson 5). A reader who starts here runs bash catchup.sh from the set-up lesson (00) first, and then step 1.
Add a rate limit to the gateway, as in lesson 8 of "Securing LLM applications", in its simplest form. A Service answers at most 3 questions for each user in its lifetime. The fourth and later questions of a user get the reply {"answer": "Too many questions.", "sources": []}, and the model is not called. Count only the questions that reach the model. Keep a dictionary of counts in the object. Then add a test test_rate_limit to the suite: five times the question "When is delivery free?" from gus with the fake model. Run the whole suite.
Check yourself
Why does the suite use a fake model that returns its prompt?
The real model gives different text on every machine, so a test on its answer is flaky. The fake model is the worst case, since it repeats everything it receives. If forbidden text is not in the prompt, no model can repeat it. The test decides by code, and it runs in a fraction of a second.
One removed control failed three tests. Is that duplication?
No. The three tests look at the same control from three sides: what reaches the prompt, what the labelled set measures, and what an unknown user gets. A control that is broken in a way that one test misses is likely to show in another. This is the same idea as defence in depth, applied to tests.
The suite passes 15 of 15. What can still go wrong?
New kinds of attack that no test covers, a wrong fact that an approved page carries, a model that writes a false answer from right sources, a name or an address that redaction cannot find, and a mistake in sign-in that gives a user the wrong role. A suite is a floor. It shows that known failures did not return.
Field notes
- Run the suite,
evaluate.pyandgovcheck.pyin the build, and run the access table and the leak test again on a schedule against the live index. Data changes between builds. - The service answers from sources, and the model can still be wrong. OWASP lists this as LLM09:2025 Misinformation. Return the sources with every answer, so that a reader can check, and tell users when no source was found.
- Log what you need to investigate (user, ids of the sources, sizes, time) and nothing more. The log of lesson 6 is clean because the data was removed before it was written.
- Alert on the signals of this course: a growing queue, a chunk that ranks first for many questions, a rise in redactions, and a failed sign-in or an unknown user. Each one points to a lesson.
- A poisoned chunk can make the model write a link or an image address that carries data out when the chat window loads it. The approval keeps the chunk out, and the reply should reach the user as plain text. Lesson 5 of "Securing LLM applications" shows how to handle such output.
- Keep the file
INBOXout of production: in the real service, the sources feed the index through the screen, and the bad files of the labs stay in the test folder.