Sub topic 8
Redacting PII and secrets from logged text
This chapter assumes you can read Python and basic regular expressions, and that you have already decided which fields your logging policy allows. Redaction applies to the content fields that policy lets through: the prompt, the response, and any headers or error text you keep.
What redaction does and does not do
Redaction replaces sensitive substrings with typed placeholders such as [EMAIL] before the text reaches a log. Typed placeholders matter. A log line that says [EMAIL] still tells you an email was present, which helps debugging, but it does not expose the address.
Pattern-based redaction is a safety net, not a guarantee. It finds data that has a recognizable shape: emails, key prefixes, card numbers. It cannot find a person's name, a street address written in prose, or a secret with no fixed format. Treat redaction as a second layer behind the rule "do not log content unless you must."
Where redaction sits in the pipeline
Order of operations matters more than any single pattern. The diagram shows the order used in this chapter.
Two ordering rules follow from this:
- Redact, then truncate. If you cut text to 2,000 characters first, the cut can split a key in half. A half key no longer matches your pattern, so it passes through unredacted. The wrapper from the previous chapter does it correctly:
redact(prompt)[:2000]. - Run specific patterns before general ones. A bearer token contains characters that a loose pattern might partly match. Replacing the most specific shapes first keeps placeholders accurate.
A basic redactor
This is the minimal version. It handles two shapes and is easy to read.
import re
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
API_KEY = re.compile(r"\b(?:sk|key|token)[-_][A-Za-z0-9_-]{16,}\b")
def redact(text: str) -> str:
text = EMAIL.sub("[EMAIL]", text)
text = API_KEY.sub("[SECRET]", text)
return text
print(redact("Mail [email protected], key sk-abcdefghijklmnop1234"))
# Mail [EMAIL], key [SECRET]The key pattern requires a known prefix (sk, key, token), a separator, and at least 16 characters. The length floor avoids matching ordinary words such as key-value. The prefix list is the weak point: a provider with a different prefix is not covered until you add it.
Extending the redactor with more shapes
Real traffic contains more than emails and keys. The version below uses a list of (pattern, replacement) pairs, so you can add shapes without editing the function. A replacement can be a string or a function. The card entry uses a function so it can run a validator before deciding.
import re
def _luhn_ok(digits: str) -> bool:
total = 0
for i, ch in enumerate(reversed(digits)):
n = int(ch)
if i % 2 == 1:
n *= 2
if n > 9:
n -= 9
total += n
return total % 10 == 0
def _card_sub(match: re.Match) -> str:
digits = re.sub(r"\D", "", match.group())
if 13 <= len(digits) <= 19 and _luhn_ok(digits):
return "[CARD]"
return match.group()
PATTERNS = [
(re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", re.S), "[SECRET]"),
(re.compile(r"\bBearer\s+[A-Za-z0-9._~+/=-]{16,}"), "[SECRET]"),
(re.compile(r"\bAKIA[0-9A-Z]{16}\b"), "[SECRET]"),
(re.compile(r"\b(?:sk|key|token)[-_][A-Za-z0-9_-]{16,}\b"), "[SECRET]"),
(re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"), "[EMAIL]"),
(re.compile(r"\b\d(?:[ -]?\d){12,18}\b"), _card_sub),
(re.compile(r"\+\d{1,3}[\s.-]?\d(?:[\s.-]?\d){6,11}"), "[PHONE]"),
]
def redact(text: str) -> str:
for pattern, replacement in PATTERNS:
text = pattern.sub(replacement, text)
return text
sample = (
"Mail [email protected], card 4111 1111 1111 1111, "
"key sk-abcdefghijklmnop1234, call +44 20 7946 0958"
)
print(redact(sample))
# Mail [EMAIL], card [CARD], key [SECRET], call [PHONE]Several design choices are worth noting:
- Validators cut false positives. A 16-digit order number is not a card number. The Luhn checksum rejects most random digit strings, so only plausible cards are replaced. If the check fails, the function returns the original text unchanged.
- Secrets come first. Private key blocks, bearer tokens, and cloud key IDs are replaced before the digit and email patterns see the text.
- The phone pattern requires a leading
+. Matching every run of digits would redact timestamps, IDs, and token counts. The trade-off is that a local number like020 7946 0958is not caught. Decide which side of that trade you prefer, and write the decision down.
Redacting structured data by key name
Pattern matching works on free text. Headers, request bodies, and tool-call arguments are structured, and for those a key-name rule is stronger than a text pattern. A value under authorization is a secret regardless of its shape.
SENSITIVE_KEYS = {"authorization", "x-api-key", "api_key", "password", "cookie"}
def redact_obj(obj):
if isinstance(obj, dict):
return {
k: "[SECRET]" if k.lower() in SENSITIVE_KEYS else redact_obj(v)
for k, v in obj.items()
}
if isinstance(obj, list):
return [redact_obj(v) for v in obj]
if isinstance(obj, str):
return redact(obj)
return obj
headers = {"Authorization": "Bearer abcdefghijklmnop1234", "Accept": "application/json"}
print(redact_obj(headers))
# {'Authorization': '[SECRET]', 'Accept': 'application/json'}Use both techniques together. The key-name rule catches secrets with no recognizable shape. The text patterns catch secrets that appear inside free-form strings, such as a prompt where a user pasted a config file.
Where the redactor is called
Call redact at the point where content enters the log record, not later in a log formatter or at the sink. In the wrapper from the logging-policy chapters, that means the lines that build record["prompt"] and record["response"]. If redaction happens only in a shared formatter, a developer who writes a quick logger.info(prompt) elsewhere bypasses it.
Redact error messages too. Exception text from HTTP libraries sometimes includes the request URL or headers. The wrapper above logs only type(exc).__name__ for this reason. If you need the message, pass str(exc) through redact first.
Known failure modes
| Failure | Example | Mitigation |
|---|---|---|
| Unknown secret format | A vendor key with prefix `acme_live_` | Add the prefix when you adopt the vendor. Scan logs for new shapes. |
| Names and addresses in prose | "Send it to Maria at 12 Elm Street" | Do not log content, or use an NER-based tool and still test it. |
| Split by truncation | Key cut at character 2,000 | Redact before truncating. |
| Obfuscated text | `ana [at] example [dot] com` | Accept the gap, or add a pattern for common forms. |
| False positives | A 16-digit ID that passes Luhn | Accept some over-redaction. Over-redaction is the safer error. |
| Slow patterns | Nested quantifiers on long text | Keep patterns simple and bound the input length first. |
Slow patterns deserve a note. A regex with nested repetition can take exponential time on crafted input, and model output can be crafted by an attacker. The patterns in this chapter use bounded or single-level repetition. If you add your own, test them on a long string of near-matches.
Test the redactor
Each leak you find in production should become a test case. The first test checks the basic guarantee.
def test_redact_removes_email_and_key():
out = redact("[email protected] sk-abcdefghijklmnop1234")
assert "[email protected]" not in out
assert "sk-abcdefghijklmnop1234" not in out
assert "[EMAIL]" in out and "[SECRET]" in out
def test_redact_keeps_non_card_digits():
assert redact("order 1234567890123456") == "order 1234567890123456"The second test guards against over-redaction. 1234567890123456 fails the Luhn check, so it stays. Without that test, a later edit that removes the validator would pass silently.
Exercise
A teammate truncates the response to 2,000 characters and then calls redact on the result. A key such as sk-abcdefghijklmnop1234 straddles character 2,000, so the log keeps only sk-abcdefghijkl. Why does this leak, and what is the fix?
Show answer
The truncated fragment is shorter than the 16 characters after the prefix that the pattern requires, so the regex no longer matches and the partial key is logged as-is. The fix is to redact the full text first and truncate afterward: redact(response)[:2000]. Placeholders are short, so truncating after redaction cannot expose a partial secret.
Exercise
Your redactor replaces any run of 13 to 19 digits with [CARD]. Support staff complain that order IDs and timestamps are being hidden in logs. What change keeps card protection but reduces the false positives?
Show answer
Add a validator. Strip the separators from the match and run a Luhn checksum, and replace the text only if it passes. Return the original text otherwise, as cardsub does. Most order IDs and timestamps fail the checksum and stay readable.