Lesson 06 · 40 minutes
Keep private data out of prompts, logs and stores
- Redact emails, card-like numbers and staff identifiers before indexing and before logging
- Test a redaction function against a fixed file and measure false matches
- Apply a retention rule that removes old chunks
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
The support team exports its helpdesk tickets and asks to add them to the assistant, "so that staff can look up how we solved things". The tickets hold customer emails, card numbers that customers typed, and staff identifiers. The data policy of the company says: "Staff may read tickets. They may not read card numbers, and nothing like that goes to the prompt, the index or the log." You clean the data on the way in, you test the cleaning against a fixed file, and you add a limit to how long a ticket stays.
Recall
Lesson 5: why does the public index file not hold the words that only finance documents use?
It is built only from the chunks of its own level. The filter of lesson 4 may fail one day, but the data is absent, so the visitor's index cannot return it.
Lesson 3: why is the hash of a chunk stored, and not only its id?
The hash ties the approval to one exact text. An edit, even of one character, gives another hash and the chunk goes back to the queue.
The idea
Sensitive Information Disclosure is LLM02 in the OWASP Top 10 for LLM Applications (2025 edition). Lesson 4 of "Securing LLM applications" showed leaks in answers. Here the weak point is earlier: private data that enters the store (the index), the prompt and the log. Data that is not there cannot leak or be stolen from a backup or an index file (lesson 5).
Redaction replaces private data with a fixed marker, such as [EMAIL]. It runs at the first point where the text enters your system, and again on every text that you log. It uses patterns, descriptions of the shape of a text. A pattern can fail in two ways: it misses private data (a miss), or it hits text that is not private (a false match). So you test both.
The Luhn check is a small sum that the digits of every payment card pass. Start at the right-hand digit and move left. Double every second digit; if a doubled digit is above 9, subtract 9 from it. Add all the digits. A card number gives a sum that ends in 0. Most random 16-digit numbers fail it, so it removes most false matches.
| Kind | Shape | Marker | Risk of a false match |
|---|---|---|---|
letters, @, a domain | [EMAIL] | low | |
| Card number | 13 to 19 digits that pass the Luhn check | [CARD] | high without the check: order numbers have 16 digits too |
| Staff id | EMP- and five digits | [EMPID] | low |
Retention is a rule for how long data may stay. A ticket that is deleted after 90 days cannot leak on day 91.
- Raw ticket → Redact: before it is indexed
- Redact → Index: only clean text is stored
- Index → Prompt: only clean text is read
- Prompt → Log: logged after redaction too
Redaction removes data with a fixed shape and nothing else. Keep that in mind when you read the results.
Worked example
1. Save the tickets
Save tickets.json: ten invented helpdesk tickets of level staff, from the source helpdesk. The card numbers are well-known test numbers and belong to nobody.
tickets.json
[
{"id": "tkt-4401", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-11-18",
"text": "Ticket 4401: Ana Lind (ana.lind@example.com) asked why the refund for a tent has not arrived. The refund was sent on 12 November."},
{"id": "tkt-4402", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-11-15",
"text": "Ticket 4402: the customer paid with card 4111 1111 1111 1111 and wants to change the delivery address."},
{"id": "tkt-4403", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-11-02",
"text": "Ticket 4403: order reference 1234 5678 9012 3456 shipped on 1 November. The customer asked for the tracking page."},
{"id": "tkt-4404", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-10-21",
"text": "Ticket 4404: staff member EMP-20417 approved a goodwill refund. Write to hr@marlowe.example for the form."},
{"id": "tkt-4405", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-10-05",
"text": "Ticket 4405: two contacts, bo.berg@example.org and bo.work@example.org, share one account. Merge the accounts."},
{"id": "tkt-4406", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-09-30",
"text": "Ticket 4406: card 5500-0000-0000-0004 was declined twice. Ask the customer to use another payment method."},
{"id": "tkt-4407", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-09-12",
"text": "Ticket 4407: EMP-30911 and EMP-20417 handled the repair of a backpack. This note has no customer data."},
{"id": "tkt-4408", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-08-20",
"text": "Ticket 4408: the tent pole set arrived bent. A replacement was sent. This note has no private data."},
{"id": "tkt-4409", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-07-14",
"text": "Ticket 4409: the customer jan.holt@example.net asked for the warranty terms of a backpack."},
{"id": "tkt-4410", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-06-01",
"text": "Ticket 4410: EMP-2041 is not a valid staff id. The form field takes five digits."}
]2. See the leak without redaction
Index the tickets with the knowledge base, and ask the best chunk for a card question. load('tickets.json') reads a file of chunks, as load() reads kb.json.
python3 -c "
from rag import *
index = Index(load() + load('tickets.json'))
hits = index.search('Which card did the customer pay with?', 1)
print(index.chunks[hits[0][1]]['text'])
"Ticket 4402: the customer paid with card 4111 1111 1111 1111 and wants to change the delivery address.Every staff user can read the card number, and the prompt and the index hold it too.
3. Write the redaction
Save redact.py. Some parts of it are new.
- In a pattern,
\bis the edge of a word,\dis a digit,{13,19}means 13 to 19 times, and(?:...)is a group that is not remembered. re.subreplaces matches, andsubnalso returns how many it replaced.- The function
luhnfollows the rule of the idea section.enumerategives each digit with its positioni, counted from the right here because ofreversed, soi % 2is true for every second digit. The functioncardruns on each long number and keeps it when it fails the check. keep_recentis the retention rule, andsafe_logis the only way that this course writes to a log.
redact.py
"""redact.py: take private data out of a text before it is indexed, put into a prompt or logged."""
import re
from datetime import date, timedelta
EMAIL = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
CARD = re.compile(r"\b\d(?:[ -]?\d){12,18}\b") # 13 to 19 digits, with spaces or dashes between
EMPID = re.compile(r"\bEMP-\d{5}\b")
def luhn(digits):
"""True when the digits pass the Luhn check that every payment card number passes."""
total = 0
for i, d in enumerate(int(c) for c in reversed(digits)):
d = d * 2 if i % 2 else d
total += d - 9 if d > 9 else d
return total % 10 == 0
def redact(text):
"""Return (clean text, {kind: count}). A long number is a card only if it passes the Luhn check."""
counts = {"email": 0, "card": 0, "empid": 0}
def card(m):
if luhn(re.sub(r"\D", "", m.group())):
counts["card"] += 1
return "[CARD]"
return m.group()
text = CARD.sub(card, text)
text, counts["email"] = EMAIL.subn("[EMAIL]", text)
text, counts["empid"] = EMPID.subn("[EMPID]", text)
return text, counts
def keep_recent(chunks, today, days):
"""Retention: keep the chunks that are at most `days` days old on the date `today` (a string, YYYY-MM-DD)."""
cutoff = date.fromisoformat(today) - timedelta(days=days)
return [c for c in chunks if date.fromisoformat(c["date"]) >= cutoff]
def safe_log(log, user, text):
"""Add one line to a log, after the private data is taken out of the text."""
log.append(f"{user}: {redact(text)[0]}")4. Test it on the fixed file
Save test_redact.py. Each test returns true or false, and the exit code is 1 when one fails. The tests run on tickets.json, so the results are the same on every machine. They cover the counts, the clean text, the order reference of ticket 4403, a second redaction, the log and the retention. The last block needs no list of tests: globals() is the dictionary of every name in the file, so the block finds each function whose name starts with test_ and runs it. To add a test, write one more function; nothing else changes.
test_redact.py
"""test_redact.py: tests of redact.py on the fixed file tickets.json. python3 test_redact.py"""
import json
import sys
from redact import keep_recent, redact, safe_log
tickets = json.load(open("tickets.json"))
def total(kind):
return sum(redact(t["text"])[1][kind] for t in tickets)
def test_counts():
return (total("email"), total("card"), total("empid")) == (5, 2, 3)
def test_clean_text_has_no_private_data():
text = " ".join(redact(t["text"])[0] for t in tickets)
return "@" not in text and "4111" not in text and "5500" not in text and "EMP-20417" not in text and "EMP-30911" not in text
def test_long_number_that_is_not_a_card_stays():
return "1234 5678 9012 3456" in redact(tickets[2]["text"])[0]
def test_redacting_twice_changes_nothing():
return all(redact(redact(t["text"])[0])[0] == redact(t["text"])[0] for t in tickets)
def test_log_is_clean():
log = []
safe_log(log, "sam", "My card 4111 1111 1111 1111 failed. Write to jo@example.com")
return log == ["sam: My card [CARD] failed. Write to [EMAIL]"]
def test_retention():
return [t["id"] for t in keep_recent(tickets, "2026-11-21", 30)] == ["tkt-4401", "tkt-4402", "tkt-4403"]
tests = [(name, fn) for name, fn in sorted(globals().items()) if name.startswith("test_")]
passed = 0
for name, fn in tests:
ok = fn()
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)python3 test_redact.pyPASS test_clean_text_has_no_private_data
PASS test_counts
PASS test_log_is_clean
PASS test_long_number_that_is_not_a_card_stays
PASS test_redacting_twice_changes_nothing
PASS test_retention
6 of 6 tests passThe ticket 4410 holds EMP-2041, with four digits. It is not a staff id, and the pattern leaves it alone. That is a pass, not a miss: it shows that the pattern does not over-match.
5. Redact before you index
The ingestion step takes each chunk, redacts its text, and only then builds the index. Count the private values in the stored chunks, with and without redaction.
python3 -c "
import json
from rag import *
from redact import redact
raw = load() + load('tickets.json')
clean = [dict(c, text=redact(c['text'])[0]) for c in raw]
for name, chunks in (('raw', raw), ('clean', clean)):
stored = json.dumps(Index(chunks).chunks)
print(name, 'card 4111:', stored.count('4111'), ' emails:', stored.count('@example'), ' EMP-20417:', stored.count('EMP-20417'))
"raw card 4111: 1 emails: 4 EMP-20417: 2
clean card 4111: 0 emails: 0 EMP-20417: 0The clean index holds the markers, and the staff can still find a ticket about a declined card, without the number. The prompt is built from the index, so it is clean too.
6. Apply retention
keep_recent keeps the chunks that are at most 90 days old on the date that you give. Give the date as an argument, and not as today(), so that a test gives the same answer every day.
python3 -c "
from rag import load
from redact import keep_recent
t = load('tickets.json')
print(len(keep_recent(t, '2026-11-21', 90)), 'of', len(t), 'tickets kept')
"7 of 10 tickets keptYour turn
The helpdesk sends a second export, tickets2.json. It holds phone numbers. Save it, and add a fourth pattern to redact.py: a plus sign, a country code of two digits, then eight more digits, replaced by [PHONE]. A space may stand between any two characters after the plus sign. Add the count to the dictionary of counts. Run the new pattern over the file. Ticket 5003 has a number without a plus sign: note what your pattern does with it, and write one sentence on how you would find such numbers. The page does not check the notes.
tickets2.json
[
{"id": "tkt-5001", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-11-19",
"text": "Ticket 5001: the customer asked us to call +47 912 34 567 about a late parcel."},
{"id": "tkt-5002", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-11-17",
"text": "Ticket 5002: use the number +4791234567 for the delivery driver. The customer has no email."},
{"id": "tkt-5003", "level": "staff", "source": "helpdesk", "owner": "support", "date": "2026-11-10",
"text": "Ticket 5003: the shop line is 55 55 55 55 and the customer will call back."}
]Check yourself
Why does the card pattern need the Luhn check?
Many numbers have 16 digits: order references, tracking numbers, parcel codes. Without the check, the pattern turns those into [CARD] and the data loses meaning. The check keeps only the numbers that can be real card numbers. It still lets a real number with a typo pass as "not a card", so treat redaction as a reduction of risk, not a proof.
Redaction removed the email, but "Ana Lind" is still in the ticket. What does it tell you?
A pattern finds text with a fixed shape. A name has none. Names, addresses and free-text details need other tools or a rule that such text never enters the store. Say so in your design, and do not claim that the index holds no personal data.
Why redact the question before you log it, when the user typed it?
Users paste cards and emails into questions. A log is stored longer than a chat, it is read by more people, and it is copied to other systems. The log is a store, so it needs the same rule as the index.
Why is a retention rule a security control?
Old data has risk and little value. Every day that a ticket stays, it can leak from a backup, an index file or a stolen laptop. A ticket that is deleted cannot leak. Deleting the source is not enough: lesson 8 shows that the index must follow.
Field notes
- Redact at the first point of entry, and keep the original in a store with strict access, if you must keep it at all. Redaction later, after the text has spread to the index, the cache and the logs, leaves copies.
- Test redaction like code. Keep a fixed file with every shape that you know, and add the text of every miss you find. A test that checks only that the pattern matches proves nothing about false matches, so include numbers that must stay.
- For free text that holds names and addresses, a pattern is not enough. Detection tools exist, but they also miss. The safer design keeps such sources out of the knowledge base, or limits them to the people who need them.
- Retention periods come from the law and from the business, and they differ by data type and country. In the EU, the GDPR sets principles for storage limitation and the right to erasure (Article 17). Take the current text from the official source, and ask your privacy lead for the period of each source.
- A Luhn check misses a mistyped real card number, and the number stays in clear text. For logs, many teams mask every run of 13 to 19 digits and accept the false matches, because a mistyped card is still private. Keep the Luhn check where a false match costs data, as in the index.
- Do not log the prompt in full. Log the user, the ids of the sources, the sizes and the time. If you must keep prompts for debugging, redact them, store them for a short time and restrict access.