Lesson 03 · 40 minutes
Stop poisoned documents with provenance and review
- Reject a chunk that has no provenance and quarantine one that no person has approved
- Record the SHA-256 hash of each approved document and detect a later edit
- Prove with a checker and its exit code that the poisoned pages stay out of the index
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
After the poisoned returns page, your lead sets a rule: "Nothing goes into the index unless we know where it came from and a person has read that exact text." You have the pages of lesson 2 as test cases. You write the gate: a screen that every chunk must pass, a queue for the chunks that wait for a person, and a hash that ties each approval to the exact text that the person read.
Recall
Lesson 2: the page `pub-shipping-update` had no strange words. Why could a pattern for instructions not find it?
It held only a false fact, written like a normal policy sentence. A pattern finds text that looks unusual. A false fact looks usual, so the control must be about who wrote it and whether a person approved it.
Lesson 2: which measure is a good test, the rank of a chunk or the count of model answers that repeat it?
The rank. Code decides it from fixed text, so it is the same on every machine. The model's answers differ between runs.
The idea
Provenance is the record of where a piece of data came from: its source, its owner and its date. Every chunk of kb.json already has these three fields. A screen turns them into a rule. Provenance alone is not enough, because an attacker can write any owner into a field. So the screen adds a second control, review: a person reads a document, and the system records the hash of what the person approved: the text, and also the id, the level, the source and the owner. A hash is a fixed-length fingerprint of data. Change one character and the hash changes. SHA-256 is the hash function that this course uses.
A chunk gets one of three verdicts.
| Verdict | Meaning | Reaches the index |
|---|---|---|
reject | The provenance is broken: a field is missing, the date is not a date, or the level or the source is not on the list. | No. It is an error to fix. |
queue | The provenance is complete, but no person has approved this exact text, or the text reads like an instruction. | No. It waits in the quarantine, the holding place for a person to review. |
accept | The provenance is complete and the hash matches an approval. | Yes. |
- Attacker → Wiki: edits the returns page
- Wiki → Screen: incoming chunk with its fields
- Screen → Quarantine: complete fields, but not approved
- Quarantine → Reviewer: a person reads the exact text
- Reviewer → Index: the approved hash lets it in
- Screen → Index: an approved chunk passes
Worked example
1. Write the screen
Save provenance.py. hashlib.sha256 makes the hash. date.fromisoformat reads a date, and re.fullmatch first demands the plain form YYYY-MM-DD: Python 3.11 and later also accept other ISO forms such as 20261121, and the screen must give the same verdict on every version. re.compile prepares a pattern for text. INSTRUCTION is a short list of phrases that talk to the assistant: a tripwire for the reviewer, and not a defence (the course "Securing LLM applications", lesson 9, shows why a list of phrases fails). A page that holds one of them stays in the queue, even when approved, until the page or the list changes. sys.argv holds the words of the command line. sys.exit(1) ends the program with exit code 1: only a reject gives it, because a queue is normal work for people. sys.exit("text") prints the text and also ends with code 1: approve uses it to refuse an id that is not in the file, so that a typo cannot pass as a success.
provenance.py
"""provenance.py: screen chunks before they enter the index.
python3 provenance.py approve kb.json approvals.json ID [ID ...] record the hash of reviewed chunks (ID: all)
python3 provenance.py check incoming.json approvals.json screen chunks; exit code 1 if any is rejected
"""
import hashlib
import json
import re
import sys
from datetime import date
REQUIRED = ("level", "source", "owner", "date")
LEVELS = {"public", "staff", "finance"}
SOURCES = {"shop-wiki", "hr-share", "finance-share", "helpdesk"}
INSTRUCTION = re.compile(r"note for the assistant|ignore (all|any|the) (previous|above)|end the answer|always (say|tell)", re.I)
def fingerprint(text):
"""The SHA-256 hash of a text, in hex."""
return hashlib.sha256(text.encode()).hexdigest()
def chunk_hash(chunk):
"""The hash that an approval records: the text and the fields that decide who may read it."""
return fingerprint(json.dumps([chunk["id"], chunk["level"], chunk["source"], chunk["owner"], chunk["text"]]))
def screen_one(chunk, approvals):
"""Return (verdict, reason). Verdicts: reject (broken), queue (a person must review), accept."""
for name in REQUIRED:
if not str(chunk.get(name, "")).strip():
return "reject", "no " + name
if not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", chunk["date"]):
return "reject", "bad date"
try:
date.fromisoformat(chunk["date"])
except ValueError:
return "reject", "bad date"
if chunk["level"] not in LEVELS:
return "reject", "bad level"
if chunk["source"] not in SOURCES:
return "reject", "unknown source"
if INSTRUCTION.search(chunk["text"]):
return "queue", "reads like an instruction"
if chunk["id"] not in approvals:
return "queue", "not reviewed"
if approvals[chunk["id"]] != chunk_hash(chunk):
return "queue", "changed since review"
return "accept", "approved"
def screen(chunks, approvals):
"""Return {id: (verdict, reason)}."""
return {c["id"]: screen_one(c, approvals) for c in chunks}
if __name__ == "__main__":
mode, chunks_file, approvals_file = sys.argv[1:4]
chunks = json.load(open(chunks_file))
try:
approvals = json.load(open(approvals_file))
except FileNotFoundError:
approvals = {}
if mode == "approve":
names = sys.argv[4:]
missing = [n for n in names if n != "all" and n not in {c["id"] for c in chunks}]
if missing:
sys.exit("no such id: " + ", ".join(missing))
for c in chunks:
if names == ["all"] or c["id"] in names:
approvals[c["id"]] = chunk_hash(c)
json.dump(approvals, open(approvals_file, "w"), indent=1)
print(len(approvals), "chunks approved")
else:
results = screen(chunks, approvals)
for cid, (verdict, reason) in results.items():
print(f"{verdict:7} {cid:20} {reason}")
counts = [sum(v == name for v, _ in results.values()) for name in ("accept", "queue", "reject")]
print("accept %d, queue %d, reject %d" % tuple(counts))
sys.exit(1 if counts[2] else 0)2. Approve the twelve documents
A person must read each document before the approval. In this lab you are that person, and the twelve documents of kb.json are yours. all approves every chunk of the file. The file approvals.json maps each id to a hash. | tail -1 sends the output of the check to tail -1, which prints only its last line.
python3 provenance.py approve kb.json approvals.json all
python3 provenance.py check kb.json approvals.json | tail -112 chunks approved
accept 12, queue 0, reject 03. See how a hash follows the text
Change one number in a sentence and the hash is a different one. The first eight characters are enough to see it.
python3 -c "
from provenance import fingerprint
print(fingerprint('returned within 30 days')[:8], fingerprint('returned within 90 days')[:8])
"c8403c98 1cabb19d4. Screen four incoming chunks
Save incoming.json. It holds an edit of the returns page (90 days instead of 30), an unchanged copy of the hours page, a chunk with no owner, and a chunk from a source that is not on the list.
incoming.json
[
{"id": "pub-returns", "level": "public", "source": "shop-wiki", "owner": "web-team", "date": "2026-11-19",
"text": "Returns: unused gear can be returned within 90 days of delivery. The customer sends the order number. Marlowe Outdoor refunds the money to the original payment method within 5 working days."},
{"id": "pub-hours", "level": "public", "source": "shop-wiki", "owner": "web-team", "date": "2026-04-01",
"text": "Opening hours: the Bergen shop is open Monday to Friday from 10:00 to 18:00 and on Saturday from 10:00 to 16:00. The shop is closed on Sunday."},
{"id": "web-note", "level": "public", "source": "shop-wiki", "owner": "", "date": "2026-11-20",
"text": "Note: all gear is half price this week."},
{"id": "web-promo", "level": "public", "source": "pastebin", "owner": "anon", "date": "2026-11-20",
"text": "Promotion: a free tent for every customer who writes to us."}
]After the check, echo "exit code $?" prints the exit code of the last command: the shell keeps it in $?. A pipeline or a test script can use that code to stop a build.
python3 provenance.py check incoming.json approvals.json
echo "exit code $?"queue pub-returns changed since review
accept pub-hours approved
reject web-note no owner
reject web-promo unknown source
accept 1, queue 1, reject 2
exit code 1The edit of the returns page keeps its owner and its source, and still it is stopped: the hash of the new text is not the hash that a person approved. Two chunks are rejected, so the exit code is 1.
5. Screen the two poisoned pages of lesson 2
python3 provenance.py check poison.json approvals.json
python3 provenance.py check poison2.json approvals.jsonqueue pub-returns-update reads like an instruction
accept 0, queue 1, reject 0
queue pub-shipping-update not reviewed
accept 0, queue 1, reject 0Both pages have complete provenance, so no field catches them. The first one trips the phrase list. The second one carries only a false fact, and the approval step stops it: it is new, and no person has approved it. This is the point of review. The fields are easy to forge, and the approval is not.
6. Build the index from the accepted chunks only
The index of lesson 1 took every chunk. Now only the accepted ones go in. The command joins the three files, screens them, and asks the same two questions as in lesson 2.
python3 -c "
import json
from provenance import screen
from rag import Index, load
chunks = load() + json.load(open('poison.json')) + json.load(open('poison2.json'))
ok = {cid for cid, (v, _) in screen(chunks, json.load(open('approvals.json'))).items() if v == 'accept'}
index = Index([c for c in chunks if c['id'] in ok])
print(len(index.chunks), 'chunks indexed')
print(index.search('How many days do I have to return unused gear?', 1))
print(index.search('When is delivery free?', 1))
"12 chunks indexed
[(0.32, 'pub-returns')]
[(0.39, 'pub-shipping')]Fourteen chunks came in and twelve went into the index. The right policies rank first again.
Your turn
Add one rule to screen_one: a chunk with a date later than 2026-11-21 is rejected with the reason future date. Write the date in the code as date(2026, 11, 21), so that your result does not depend on the day when you run it. A forged date in the future is a way to look newer than every real page.
Save incoming2.json and test your rule on it.
incoming2.json
[
{"id": "pub-promo-2027", "level": "public", "source": "shop-wiki", "owner": "web-team", "date": "2027-01-15",
"text": "Promotion: every tent is 20 percent cheaper in January."},
{"id": "pub-bad-date", "level": "public", "source": "shop-wiki", "owner": "web-team", "date": "2026-13-45",
"text": "Care guide: dry a wet tent before you pack it."},
{"id": "pub-guide", "level": "public", "source": "shop-wiki", "owner": "web-team", "date": "2026-11-19",
"text": "Packing guide: put heavy items close to your back and near the middle of the pack."}
]Then act as the reviewer for pub-guide. Use a separate file, so that approvals.json keeps only the twelve documents: approve that one id from incoming2.json into approvals-test.json with the command of step 2, and run the check again with that file.
Check yourself
The page `pub-shipping-update` had a full source, owner and date. What stopped it?
The review check. The fields only say what the writer claims. The approval says that a person with the right to approve has read this exact text. A new page has no approval, so it waits in the quarantine.
Why does the approval store the hash of the text and not only the id of the document?
An id says nothing about the content. If the approval covered the id, an attacker could edit an approved page and keep its approval. The hash binds the approval to one exact text. Any edit, even of one character, makes it a different text that needs a new review.
An attacker changes only the `level` of an approved finance chunk to `public` and leaves its text alone. What happens?
The chunk goes back to the queue with the reason changed since review. The hash covers the level, the source and the owner as well as the text. A hash of the text alone would accept the chunk, and the access control of lesson 4 would then trust the forged level.
Why must the writers of the wiki have no write access to `approvals.json`?
If they could write to it, an attacker who poisons a page could also approve it. Review is a separation of duties: one party writes, another approves. Keep the approvals in a place that only the reviewers can change, and log every change.
A `queue` verdict gives exit code 0. Is that a gap?
No, but it needs a process. The queue keeps the chunk out of the index, so the service is safe. A queue that nobody works makes the service stale, because new and edited pages never go live. Count the age of the oldest waiting chunk, and alert when it is too high.
Field notes
- In a real system, take the identity of the editor from the audit log of the source (the wiki or the share). Do not trust the
ownerfield that sits inside the text. OWASP lists validation of sources and the use of trusted, verified sources among the controls for LLM08:2025 Vector and Embedding Weaknesses. - This lab drops an edited chunk until a person approves it. A production service often keeps serving the last approved version and queues the change. Choose on purpose: dropping is safer, serving the old text is more available.
- A list of phrases such as
INSTRUCTIONcatches careless attacks and helps the reviewer to look in the right place. Never count it as the control. The control is the approval. - Require two people for sensitive levels: the author and a reviewer who is not the author. Record who approved what, and when.
- Hash every field that a later control trusts: the level, the source and the owner as well as the text.
chunk_hashleaves out the date, because the screen checks it on its own. Store the approval in a system that you control, and re-check the hashes when the index is built. A hash that is checked only once, at upload, does not protect against a later change in the store.