Lesson 01 · 45 minutes
Decide what to log, keep secrets out and protect the log
- Choose the fields of one log record for an AI assistant
- Sanitise text, write a retention rule and test both
- Protect the log with a file mode and a sealed digest that reports a change
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
Orbi, the assistant of Orbit Parcels, has run for a month. Its log is a plain copy of every chat. The security lead asks: "If a customer says that Orbi repeated their card number, what can we prove? What would we regret having stored?" You design the record, make the writer keep secrets out, write the deletion rule, and protect the log.
The idea
The courses "Securing AI agents and MCP" (lesson 10) and "Security fundamentals" (lesson 6) said that a log is the base of detection and must never hold a secret. For an AI assistant the text is the danger: a prompt can hold a card number, and a log of the text is a second copy that lives longer than the chat.
So the record holds the shape of an interaction, not its text. The rest of the course uses these fields:
| Field | What it holds |
|---|---|
id, ts | A record number and the time (UTC, Coordinated Universal Time) |
user | A pseudonym: a hash of the user name with a secret salt |
prompt_sha, prompt_len, excerpt | A hash, the length and the first 60 characters, after sanitising |
resp_len | The length of the response, not the response |
model | The model version that answered |
tools, docs | Tool calls, and ids of retrieved documents (kb- is ours, ext- is untrusted) |
decision | answered or refused |
tokens_in, tokens_out, cost | Token counts and the cost in USD |
confidence | A score from 0 to 1 for the answer |
Three rules decide what is written (a fourth, protect the log, is step 7).
- Sanitise first. Replace emails, card numbers, keys and passwords by a name such as
[card]before anything is cut or stored. A cut can split a key in two halves that no pattern finds. - Never log a secret, a raw user name, a full prompt or response by default, or a request header with a token.
- Delete on a schedule. Every field has a time limit. A record that is part of an incident is held longer, on purpose.
- Customer → Orbi: asks, with a card number in the text
- Orbi → Sanitiser: the raw text, in memory only
- Sanitiser → Log file: sizes, hashes, a masked excerpt
- Retention job → Log file: cuts and deletes old data
- Detectors → Log file: read the records
- Detectors → Analyst: raise an alert
How long to keep data is a decision of the owner and of the law. The principle of storage limitation of the General Data Protection Regulation (GDPR) (Article 5(1)(e)) keeps personal data no longer than its purpose needs. For high-risk systems, the EU AI Act asks for automatic logs (Article 12) kept for a fitting period (Article 19). Take the current wording from the source. The periods here belong to the invented lab.
Worked example
1. Look at one record
head -n 1 prints the first line of a file. Print the first record of week 1.
head -n 1 logs/week1.jsonl{"id": "r100001", "ts": "2026-10-05T01:16:08Z", "user": "u_e92f0422", "prompt_sha": "8362591a4098", "prompt_len": 44, "excerpt": "What is the weight limit for a small parcel?", "resp_len": 626, "model": "orbi-1.2", "tools": ["search_kb"], "docs": ["kb-25"], "decision": "answered", "tokens_in": 461, "tokens_out": 176, "cost": 0.004023, "confidence": 0.743}The record says who (a pseudonym), what (a tool, a model, a length) and how much, not what the customer wrote.
2. Write the safe writer
logrec.py holds the safe writer. A regular expression (re) is a pattern for text; pattern.sub(new, text) replaces every match. In a pattern, \d is a digit, \w is a letter, digit or underscore, \S is any character that is not a space, [...] is one character from a list, {12,15} means 12 to 15 times, \b is the edge of a word, (?:...) groups without keeping the match, (?i) ignores case, and a plus sign that must match itself is written \+. A salt is a secret text added before hashing, so that a list of names cannot rebuild the user names. hashlib.sha256 makes a fingerprint of a text. datetime.strptime reads a time from a text. sanitise runs the four masks, violations lists why a record must not be written, make_record builds a record with no field for the text, write appends a record or refuses it, and retain says what may still be kept of an old record.
logrec.py
"""logrec.py: build one safe log record, sanitise text, write it, apply the retention rules."""
import hashlib
import json
import re
from datetime import datetime
SALT = "orbit-lab-salt"
PRICE_IN, PRICE_OUT = 3.0, 15.0 # invented prices, USD per million tokens
EXCERPT_CHARS = 60
EXCERPT_DAYS, RECORD_DAYS, HOLD_DAYS = 7, 90, 365
MASKS = [
("email", re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")),
("card", re.compile(r"\b\d(?:[ -]?\d){12,15}\b")),
("key", re.compile(r"\b(?:sk|key|tok)[-_][A-Za-z0-9_-]{8,}")),
("password", re.compile(r"(?i)\b(?:password|passwd|secret)\s*[:=]\s*\S+")),
]
def sha(text, n):
return hashlib.sha256(text.encode()).hexdigest()[:n]
def pseudonym(raw_user):
return "u_" + sha(f"{SALT}:user:{raw_user}", 8)
def prompt_hash(text):
return sha(f"{SALT}:prompt:{text}", 12)
def sanitise(text):
for name, pattern in MASKS:
text = pattern.sub(f"[{name}]", text)
return text
FORBIDDEN_FIELDS = {"prompt", "response", "headers", "authorization", "password"}
def violations(record):
"""Why a record must not be written. An empty list means that it may."""
found = [f"field {k}" for k in record if k in FORBIDDEN_FIELDS]
found += [f"{k} holds a secret or a personal item" for k, v in record.items() if isinstance(v, str) and sanitise(v) != v]
return found
def make_record(rid, ts, event):
p = event["prompt"]
tin, tout = event["tokens_in"], event["tokens_out"]
return {"id": rid, "ts": ts, "user": pseudonym(event["user"]), "prompt_sha": prompt_hash(p), "prompt_len": len(p),
"excerpt": sanitise(p)[:EXCERPT_CHARS], "resp_len": len(event["response"]), "model": event["model"],
"tools": event["tools"], "docs": event["docs"], "decision": event["decision"],
"tokens_in": tin, "tokens_out": tout, "cost": round(tin * PRICE_IN / 1e6 + tout * PRICE_OUT / 1e6, 6),
"confidence": event["confidence"]}
def write(path, record):
found = violations(record)
if found:
raise ValueError("not written: " + "; ".join(found))
with open(path, "a") as f:
f.write(json.dumps(record) + "\n")
def age_days(record, now):
return (now - datetime.strptime(record["ts"], "%Y-%m-%dT%H:%M:%SZ")).days
def retain(record, now, held=False):
"""What may still be kept of a record: all, without the excerpt, or None. `held` is an incident hold."""
age = age_days(record, now)
if age > (HOLD_DAYS if held else RECORD_DAYS):
return None
if age > EXCERPT_DAYS and not held:
return {k: v for k, v in record.items() if k != "excerpt"}
return record
def load(path):
with open(path) as f:
return [json.loads(line) for line in f]3. Sanitise a prompt
python3 -c runs the text after it as a short program.
python3 -c "from logrec import sanitise; print(sanitise('Card 4111 1111 1111 1111, mail anna@orbit.example, password: hunter2'))"Card [card], mail [email], [password]4. Test the rules
A test is a small program that checks one fact (assert in Python) and stops with an error if it is false. test_logrec.py holds eight tests: four for the masks, one for the record, one for violations, one for write and one for retain. Open the block and save the file. tempfile.TemporaryDirectory() makes a folder that is deleted at the end of its block. The line @test puts a function into a list that runs at the end of the file.
The finished file: test_logrec.py
test_logrec.py
"""test_logrec.py: tests for logrec.py. Run: python3 test_logrec.py"""
import tempfile
from datetime import datetime, timedelta
from logrec import load, make_record, pseudonym, retain, sanitise, violations, write
NOW = datetime(2026, 11, 1)
tests = []
def test(f):
tests.append(f)
return f
def aged(days):
return {"id": "r1", "ts": (NOW - timedelta(days=days)).strftime("%Y-%m-%dT%H:%M:%SZ"), "excerpt": "hello"}
@test
def masks_an_email():
assert sanitise("mail anna@orbit.example now") == "mail [email] now"
@test
def masks_a_card_with_spaces():
assert sanitise("card 4111 1111 1111 1111 ok") == "card [card] ok"
@test
def masks_a_key_and_a_password():
assert sanitise("key sk-live-9f8e7d6c5b and password: hunter2") == "key [key] and [password]"
@test
def leaves_a_parcel_number():
assert sanitise("Where is parcel OP12345?") == "Where is parcel OP12345?"
@test
def record_has_no_text_fields():
event = {"user": "anna", "prompt": "secret: abc", "response": "ok", "model": "m", "tools": [], "docs": [],
"decision": "answered", "tokens_in": 10, "tokens_out": 5, "confidence": 0.9}
rec = make_record("r1", "2026-10-30T10:00:00Z", event)
assert "prompt" not in rec and "response" not in rec and rec["user"] == pseudonym("anna")
assert rec["excerpt"] == "[password]" and rec["prompt_len"] == 11
@test
def finds_what_must_not_be_logged():
assert violations({"id": "r1", "excerpt": "hello"}) == []
assert violations({"id": "r1", "prompt": "hello"}) == ["field prompt"]
assert violations({"id": "r1", "excerpt": "mail anna@orbit.example"}) == ["excerpt holds a secret or a personal item"]
@test
def write_refuses_a_bad_record():
with tempfile.TemporaryDirectory() as folder:
path = folder + "/log.jsonl"
write(path, {"id": "r1", "excerpt": "hello"})
try:
write(path, {"id": "r2", "prompt": "hello"})
assert False, "the bad record was written"
except ValueError:
pass
assert len(load(path)) == 1
@test
def retention_by_age():
assert retain(aged(3), NOW) == aged(3)
assert "excerpt" not in retain(aged(10), NOW)
assert retain(aged(100), NOW) is None
assert retain(aged(100), NOW, held=True)["excerpt"] == "hello"
for t in tests:
t()
print(f"tests passed: {len(tests)}")python3 test_logrec.pytests passed: 85. Scan a whole week
Count the records of both weeks that break a rule.
python3 -c "
from logrec import load, violations
for week in ('week1', 'week2'):
records = load(f'logs/{week}.jsonl')
print(week, len(records), 'records,', sum(bool(violations(r)) for r in records), 'with a violation')
"week1 908 records, 0 with a violation
week2 1399 records, 0 with a violationThe good writer gives 0. Now scan leaky.jsonl, the log of an older tool, with eight lines.
leaky.jsonl
{"id": "x1", "user": "anna.k@orbit.example", "excerpt": "Where is parcel OP12345?"}
{"id": "x2", "user": "u_70a0e5d6", "prompt": "Where is parcel OP20202?", "response": "It is at the depot."}
{"id": "x3", "user": "u_70a0e5d6", "excerpt": "My card 4111 1111 1111 1111 was charged twice"}
{"id": "x4", "user": "u_fca25bd2", "excerpt": "Do you deliver on Sundays?"}
{"id": "x5", "user": "u_fca25bd2", "excerpt": "call me on +44 7700 900123"}
{"id": "x6", "user": "u_b3116c83", "excerpt": "my login is password: hunter2"}
{"id": "x7", "user": "u_b3116c83", "excerpt": "Authorization failed for me", "headers": {"Authorization": "Bearer sk-live-9f8e7d6c5b4a"}}
{"id": "x8", "user": "u_b3116c83", "excerpt": "Has parcel OP11111 left the depot yet?"}python3 -c "
from logrec import load, violations
for r in load('leaky.jsonl'):
print(r['id'], violations(r))
"x1 ['user holds a secret or a personal item']
x2 ['field prompt', 'field response']
x3 ['excerpt holds a secret or a personal item']
x4 []
x5 []
x6 ['excerpt holds a secret or a personal item']
x7 ['field headers']
x8 []Five lines break a rule. Line x5 holds a phone number, and no mask finds it: a scanner finds only what its masks know.
6. Apply the retention rule
retain(record, now) returns the whole record, the record without its excerpt, or None. The limits are 7, 90 and 365 days (incident hold).
retain_count.py
"""retain_count.py: count what the retention rule keeps and deletes in week 1, on three dates."""
from datetime import datetime
from logrec import load, retain
records = load("logs/week1.jsonl")
for now in (datetime(2026, 10, 15), datetime(2026, 11, 21), datetime(2027, 1, 5)):
kept = [retain(r, now) for r in records]
print(now.date(), "whole", sum(1 for k in kept if k and "excerpt" in k), "no excerpt", sum(1 for k in kept if k and "excerpt" not in k), "deleted", kept.count(None))python3 retain_count.py2026-10-15 whole 563 no excerpt 345 deleted 0
2026-11-21 whole 0 no excerpt 908 deleted 0
2027-01-05 whole 0 no excerpt 741 deleted 167On 15 October part of the week keeps its excerpt, on 21 November none does, and on 5 January the oldest records are gone. The lab files are never cut: you only count.
The rules of lessons 2 and 5 read the excerpt, so they must run within 7 days. Keep what they find, not the excerpt.
7. Control who can change the log, and notice a change
A log has a writer (the service that appends), readers (detectors and analysts) and everybody else. A file mode is three digits for the owner, the group and everybody else, where read is 4, write is 2 and execute is 1 (for a folder: to enter it). chmod 440 (change mode) leaves nobody a write right, and stat -c '%a %n' prints a mode. A digest is the SHA-256 fingerprint of a whole file: one changed byte gives another digest. sha256sum FILE > DIGEST saves it, and sha256sum -c DIGEST (check) compares. sed -i '3s/answered/refused/' edits line 3 in place. cp copies a file, and 2>&1 | tail -1 joins the error messages to the output and shows only its last line.
cp logs/week1.jsonl copy.jsonl
sha256sum copy.jsonl > copy.sha256
chmod 440 copy.jsonl
stat -c '%a %n' copy.jsonl
python3 -c "
from logrec import write
write('copy.jsonl', {'id': 'x', 'excerpt': 'hello'})
" 2>&1 | tail -1
chmod 640 copy.jsonl
sed -i '3s/answered/refused/' copy.jsonl
sha256sum -c copy.sha256
echo "exit code $?"440 copy.jsonl
PermissionError: [Errno 13] Permission denied: 'copy.jsonl'
copy.jsonl: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
exit code 1The writer of step 2 is refused on a file with no write right, and the digest notices the edit. Root ignores the mode: if you are root, the write works and only the digest notices. In production the log has its own owner: chown logwriter:analysts (it needs root, so the lab does not run it), mode 640 on the file and 750 on its folder: all for the owner, read and enter for the group, nothing for others. The service runs as logwriter, and the group analysts can read but not change. A mode does not stop the owner or root, so a closed log (rotated at the end of the day) is sealed with a digest stored where the writer cannot change it, and each line also goes to another system at once ("Security fundamentals", lesson 6). The check says that the file changed, not where: compare with the copy off the machine. Lesson 7's change record can be sealed the same way.
Your turn
Files you need: logrec.py, test_logrec.py, leaky.jsonl and the data of lesson 0 (kr-lab.sh for this lesson, then python3 makelogs.py). The phone number in x5 must be found. Add a mask named phone to MASKS that matches a plus sign, a country code of one to three digits, and then, after the country code, two or three groups of 2 to 6 digits, each group with one space or one hyphen in front of it, such as +44 7700 900123. Put it after card, so that a card number is still a card. The text call +44 7700 900123 now must become call [phone] now.
Then run the scan of leaky.jsonl again. For the retention questions use datetime(2026, 10, 17) and datetime(2027, 1, 7) as now with logs/week1.jsonl. Last, seal a copy of logs/week2.jsonl as in step 7, delete its last line with sed -i '$d', and check the seal.
Check yourself
Why does the record hold the length and the hash of the prompt, and not the prompt?
The text may hold personal data and secrets, and every copy lives as long as the log. The length and the hash still show a repeated prompt and a strange size. The excerpt is the exception, with the shortest life (7 days).
Why does sanitise run before the text is cut to 60 characters?
A cut can leave half of a key, which no mask matches, so the half is stored. Masking first removes the whole item.
A scan of your log finds 0 violations. Does it prove that the log holds no secret?
No. It proves only that no value matches your masks and no forbidden field is present. The phone number passed the first scan.
The log has mode 640 and a stored digest. Why is the digest not enough, and why is the mode not enough?
The mode does not stop the owner or root. The digest shows a change only after it happened, and only if the intruder cannot write it. Use both, with a separate owner and a copy off the machine.
Field notes
- A pseudonym is not anonymous. Whoever has the salt and a list of user names can recompute every hash, and confirm a guess about a short prompt. In production use a keyed hash (
hmac) with the key apart from the log, and treat both values as personal data. - Regular expressions miss what they do not know (other phone formats) and hit what they should not: the
cardmask also masks a 13-digit order number. Add the Luhn check (a sum that real card numbers satisfy). - An incident hold (
held=True) needs an end date, or it keeps everything for ever.