Sub topic 3
Hashing and Pseudonymizing Identifiers and Prompts
Assume you know basic Python, have called an LLM API, and understand application log levels and regular expressions. This chapter focuses on limiting what enters persistent logs.
Hashing and pseudonymizing identifiers and prompts
A hash is a one-way digest of input. It lets you compare values without storing the original text. A plain hash is weak for predictable prompts because an attacker can hash guesses. Use a keyed hash, such as HMAC, when you need a stable pseudonym.
import hashlib
import hmac
def pseudonym(value: str, secret: bytes) -> str:
return hmac.new(secret, value.encode(), hashlib.sha256).hexdigest()[:16]
print(pseudonym("user-42", b"service-secret"))Keep the HMAC key outside the logs. Log a random request ID for correlation. Use a pseudonym only when you need to group events by the same user, prompt, or tenant.
Truncating and sampling logged content
Redaction should happen before truncation. Truncate by character or byte count so an unusually large response cannot fill the logging system. Sample ordinary successful calls, but retain errors and latency outliers. Sampling reduces exposure and storage cost, but it must not hide important failures.
Logging streamed responses safely
Do not log each streamed chunk. A chunk can contain half of an email address or secret, so redacting chunks separately can fail. Yield chunks unchanged to the caller, collect them privately, and redact once when the stream ends.
def stream_logged(chunks, log_fn, redact):
parts = []
try:
for chunk in chunks:
parts.append(chunk)
yield chunk
finally:
text = "".join(parts)
log_fn({
"event": "llm_stream_done",
"response_chars": len(text),
"response": redact(text)[:2000],
})The finally block also records a consumer that stops early.
Opt-in, time-limited content logging for debugging
Metadata should be the default: model, status, token counts, latency, and pseudonymous IDs. Enable content logging only for a specific request or support case. Require an expiry time, restrict the operator who can enable it, and record an audit event. Never let model output choose this setting.
Access control, encryption, and retention
Store logs in an encrypted system with separate permissions from application operators. Limit access to the smallest team that needs it. Encrypt data in transit and at rest. Set an automatic deletion period based on the debugging need. Keep keys in a secret manager, not in source code or log fields.
Testing that redaction works and keeps working
Test known emails, credentials, multiline values, long inputs, and model text containing fake log records. Add a regression test for every discovered leak pattern.
def test_redaction(redact):
out = redact("[email protected] sk-abcdefghijklmnop1234")
assert "[email protected]" not in out
assert "sk-abcdefghijklmnop1234" not in outExercise
Why is HMAC safer than an ordinary hash for pseudonymizing a predictable prompt?
Show answer
HMAC requires a secret key, so an observer cannot efficiently test guesses without that key.