Keep untrusted text from forging log lines
Keep untrusted text from forging log lines. Python fixtures run ten hostile values through a JSON logger and one mutation that breaks it.
A login fails, and the app writes a line: login_failed user=<name>. The name came from the request. If an attacker sends a name that contains a line break followed by INFO login_ok user=admin, the log now holds two lines, and the second looks like a real success. Anyone reading or searching the log later can be misled.
The OWASP Logging Cheat Sheet warns against log injection and recommends sanitizing CR, LF and delimiter characters and encoding for the output format. JSON is the design chosen for this fixture, not a guarantee that every downstream reader handles logs safely. The sheet also lists data that should usually not be logged directly, among them passwords, access tokens, and session identification values, which it suggests replacing with a hashed value when session events must be tracked. It also tells you to test that logging mechanisms are not susceptible to injection.
This guide tests a small JSON logger against hostile input. It was prepared with AI assistance and reviewed on 18 November 2026. It uses in-memory strings, not a logging framework.
Show the forgery first
The text logger writes event key=value .... With the user value bob, a newline and INFO login_ok user=admin, a reader that splits on line feeds sees two lines, and the second one is the forged event. The test asserts exactly that.
The JSON logger
Each event becomes one JSON object on one line. Strings are escaped by the encoder, so a newline in a value becomes the two characters backslash and n. Values are clipped to 200 characters, and keys named password, token or authorization are replaced with a marker. A session_id is replaced with the first 12 hex characters of its SHA-256 hash.
def log_json(out, event, ensure_ascii=True, **fields):
rec = {'event': event}
for k, v in fields.items():
if k in SECRET_KEYS:
rec[k] = '[redacted]'
elif k == 'session_id':
rec[k] = hashlib.sha256(str(v).encode()).hexdigest()[:12]
else:
rec[k] = clip(v)
out.write(json.dumps(rec, ensure_ascii=ensure_ascii,
separators=(',', ':')) + '\n')
Ten hostile values, two kinds of reader
The fixture logs ten values: LF, CRLF, a bare CR, U+2028, U+0085, a vertical tab, a form feed, a 5,000-character string, a quote-and-brace string meant to close the JSON early, and a value with a null character. It reads the output two ways. One reader splits on \n only. The other uses Python's splitlines, which also breaks on CR, U+2028, U+0085 and others.
For each value, both readers see exactly one line. The line parses as JSON, has exactly the keys event and user, and holds the original value, shortened to 200 characters plus a marker for the long one. The quote-and-brace payload stays inside its string and adds no fields.
A mutation that breaks it
A test should fail when the protection is removed. With ensure_ascii=False, the encoder writes U+2028 raw. The test shows the LF-only reader still sees one line and the splitlines reader sees two. Whether a given log tool splits on that character varies, which is the point: the default escaping removes the question.
Secrets and their limits
A login event with a password, token, authorization header and session ID is written. None of the raw values appear in the output. The three keyed fields show the marker, and the session ID shows a 12-character hash. The last check shows a limit and does not fix it: a password typed into a free-text message field is written as is. Key-based masking cannot see a secret inside prose, so keep such values out of logged text.
The logger assumes application-controlled event names and field keys. Its clipping applies to ordinary field values, not the event name or total record size. Masking recognizes only the three exact, lower-case keys above: a Password key is not masked, and neither are secrets in nested values. The fixture explicitly shows the case-sensitive gap as well as the free-text gap. This is not a general secret detector or a resource-exhaustion defense.
All of this passes on Python 3.10.12.
What this does not cover
It does not test a real logging framework, file rotation, or how a log viewer renders values, where escaping for HTML is a different problem. It does not cover log tampering after the write, secure transport, or retention, which the cheat sheet discusses separately. A 12-character hash prefix is enough to correlate events in this sketch, but it is a design choice and not a statement about collision risk.
Sources
- OWASP Logging Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html