A debug log leaked Bearer tokens. How do you log safely?
Question
During an outage, an engineer enabled request logging to trace failed checkouts. Centralized logs and crash reports now contain Authorization: Bearer tok_test_99, Cookie: sid=sess_42, ?token=reset_abc, and a request path containing \r\nINFO login ok.
- Why is a regex denylist across raw log strings a fragile fix?
- Write
safe_log_event(req)using a strict field allowlist, secret stripping, and CR/LF neutralization.
def log_request(req): # req has method, path, query, headers, status, user_id, request_id return f"{req['method']} {req['path']}?{req['query']} {req['headers']}"
Show hints (3)
- "ALLOWLIST OVER DENYLIST"
If you dump whole
headersorquerystrings and only regex-maskBearer, what happens whenX-Api-KeyorSet-Cookieshows up? - "KEEP CORRELATION IDS"
Engineers still need to trace failures. Which non-secret fields (
request_id,user_id,method,path,status) make debugging possible? - "STOP FORGED LINES"
Replace
\rand\nand emit structured JSON so untrusted text cannot inject a fake second log entry.
Show checked explanation
A regex denylist breaks whenever a new secret header, query parameter, or crash field appears. Emit structured JSON from a strict allowlist (request_id, method, path, status, user_id), and strip Authorization, Cookie, Set-Cookie, and query strings at middleware boundaries. Neutralize \r and \n to block log injection.
import json SAFE_FIELDS = ("request_id", "method", "path", "status", "user_id") def clean(val): return (val.replace("\r", " ").replace("\n", " ") if isinstance(val, str) else val) def safe_log_event(req): event = {k: clean(req[k]) for k in SAFE_FIELDS if k in req} return json.dumps(event, sort_keys=True) req = {"request_id": "req_7", "method": "GET", "path": "/reset\r\nFAKE", "query": "token=reset_abc", "status": 401, "user_id": "user_101", "headers": {"Authorization": "Bearer tok_test_99", "Cookie": "sid=sess_42"}} print(safe_log_event(req))
{"method": "GET", "path": "/reset FAKE", "request_id": "req_7", "status": 401, "user_id": "user_101"}Code run on CPython 3.12.10 against synthetic requests carrying Bearer tokens, Cookie and Set-Cookie headers, query tokens, and CRLF payloads; official OWASP and NIST links checked. Checked by an editor other than the author.
Walkthrough
Centralized logs and crash trackers are shared across teams and kept for months. Once tok_test_99 or sess_42 lands there, anyone with log read access (or a leaked log bucket) can replay live sessions.
Prefer an allowlist over a regex denylist. Dumping whole request objects and scrubbing known patterns fails silently whenever someone adds X-Api-Key, Set-Cookie, ?code=, or a nested payment field. An allowlist (SAFE_FIELDS) logs only explicit non-secret keys, so new sensitive fields are dropped by default.
| input | denylist risk | allowlist design |
|---|---|---|
Authorization, Cookie, Set-Cookie | Misses custom auth headers or response headers | Stripped at middleware edge; omitted from log schema |
Query string (?token=reset_abc) | Regex misses new secret parameter names | Log route path only; drop raw query string |
| User and request tracing | Overbroad masks hide useful context | Log opaque request_id, user_id, and token_id |
Untrusted text with \r\n | Forges fake lines in plain-text logs | Replace \r/\n and serialize as single-line JSON |
Use structured IDs instead of partial masking. Masking tok_test_99 to tok_***99 still leaks token shape and fragments. Logging opaque IDs (request_id, user_id, token_id, status) gives full incident traceability with zero secret material.
Strip secrets at the middleware boundary and in crash reports. Configure HTTP middleware, reverse proxies, and error trackers to scrub Authorization, Cookie, Set-Cookie, query strings, and request bodies before events leave the process. Replacing \r and \n plus emitting single-line JSON stops untrusted input from forging INFO login ok lines.
Common mistakes
- Dumping full
req.headersorreq.urland masking onlypasswordandBearer. Custom headers likeX-Api-Keyor?code=still leak. - Scrubbing incoming
Cookieheaders while forgetting outgoingSet-Cookieheaders or reverse-proxy access logs. - Cleaning application logs while leaving crash reporters capturing raw request bodies and local variables in stack frames.
- Writing untrusted strings straight into plain-text log lines without neutralizing
\rand\n, allowing forged log entries.
Follow-up questions
- "Support says they cannot debug auth errors without seeing the token. What do you log instead?" Log opaque
request_id,user_id, non-secrettoken_id(orkid), HTTP status, and an explicit failure code such asexpiredorbad_sig. Never log the raw token or a long prefix. - "You find live Bearer tokens in centralized logs from the last two hours. What do you do first?" First, stop the leak by disabling or fixing the log emitter and revoke or rotate the exposed tokens right away. Second, purge those entries from the log store and retention copies.
- "If you emit JSON logs, do you still need to strip
\rand\n?" JSON escapes\rand\n, which already keeps the raw log to one line. Still normalize control characters so downstream dashboards or CLI viewers that decode JSON do not display deceptive multi-line messages.
What a strong answer covers
Replaces raw dumps and brittle regex denylists with a structured field allowlist. Strips Authorization, Cookie, Set-Cookie, and query secrets at middleware edges and in crash reports, logs opaque IDs, and blocks CRLF injection.
Open in interactive practice deck →