Your logger prints secrets after you redacted them
A redaction hook sees values. The logger prints text. Errors, structs and printf arguments turn into text after the hook has run, so the secret inside them goes out as it came in. We found this in five of the six languag
A redaction hook sees values. The logger prints text. Errors, structs and printf arguments turn into text after the hook has run, so the secret inside them goes out as it came in. We found this in five of the six languages flare-redact supports and fixed it in 1.12.1. Here is the mechanism, the real output, and a test you can run against your own logger.
Short answer: redact what the logger will print, not only the values it is handed. A value the hook does not recognise (an error, a struct, a URL, a %s argument) has to be turned into text the way the logger would, and that text redacted. Then test with the real logger writing to a buffer, never with a fake of its hook.
How we found it
While checking code samples for a round of replies, we logged a database error through our own Go handler:
slog.Error("db down", "err", fmt.Errorf("connect %s: connection refused", dsn))
The password came out in clear. The handler's tests were green, because none of them logged an error. The redactor walks strings, maps and lists. An error is none of those, so the handler passed it on unchanged, and slog's JSON handler called err.Error() when it wrote the line.
So we checked every logging integration the same way: the real logger, a known secret, the printed output. Eight integrations in five languages leaked in at least one path.
The mechanism
Every logger works in two steps:
- You hand it values: a message template, arguments, fields, bound context.
- Later, when it writes the line, it turns some of those values into text:
Error(),String(),toString(),__str__,ToString(), printf's%s.
A redaction hook sits between the two, so it can only redact what is already text when it runs. An error object is not text yet. Neither is a dataclass, a Uri or a struct. If the hook returns unknown objects unchanged, which is the polite thing for a walker to do, the text is created after redaction and nothing looks at it again.
Go slog
dsn := "postgres://app:[email protected]:5432/prod"
slog.Error("db down", "err", fmt.Errorf("connect %s: connection refused", dsn))
slog.Info("config", "db", DB{Host: "db.internal", Password: "S3cret-canary-42"})
With flare-redact 1.12.0:
{"level":"ERROR","msg":"db down","err":"connect postgres://app:[email protected]:5432/prod: connection refused"}
{"level":"INFO","msg":"config","db":{"Host":"db.internal","Password":"S3cret-canary-42"}}
With 1.12.1:
{"level":"ERROR","msg":"db down","err":"connect postgres://app:***@db.internal:5432/prod: connection refused"}
{"level":"INFO","msg":"config","db":{"Host":"db.internal","Password":"***"}}
A key rule in ReplaceAttr, such as if a.Key == "password", would not have helped with the first line: the key is err. The secret is in the value, and the value is not text yet.
pino
pino adds two twists. It builds the message itself from the template and arguments, and passes only the merge object to formatters.log, so a formatter never sees msg. And child() with no options swaps the bindings formatter for one that returns its input, so child bindings skip it too.
log.info('connecting to %s', dsn);
log.error(new Error(`connect ${dsn}: refused`));
log.child({ dsn }).info('pool ready');
With 1.12.0 (stack trimmed):
{"level":30,"msg":"connecting to postgres://app:[email protected]:5432/prod"}
{"level":50,"err":{"type":"Error","message":"connect postgres://app:***@db.internal:5432/prod: refused"},"msg":"connect postgres://app:[email protected]:5432/prod: refused"}
{"level":30,"dsn":"postgres://app:[email protected]:5432/prod","msg":"pool ready"}
Look at the middle line: the same string is masked in err.message and printed raw in msg right next to it. With 1.12.1 all three lines show app:***@db.internal.
Python logging
A logging.Filter sees record.msg and record.args. getMessage() runs later, in the handler, and calls str() on each argument.
log.info("config %s", DB("db.internal", "S3cret-canary-42"))
1.12.0 INFO config DB(host='db.internal', password='S3cret-canary-42')
1.12.1 INFO config DB(host='db.internal', password='***')
This one leaked only with RedactingFilter on its own. install() also wraps the handler's formatter, which redacts the final text, and that caught it. But the filter alone is a common setup, so it had to be right too.
The other five
-
winston: splat arguments and an Error's message and stack, when
winstonRedact()runs beforeformat.splat()orformat.errors(). Those formats read the raw arguments kept underSymbol.for('splat')and the Error's non-enumerable properties. -
console (
wrapConsole()and--import flare-redact/register): an object with its owntoString()printed through%s. -
.NET Microsoft.Extensions.Logging and Serilog: a
Uri, a class with its ownToString(), or a struct passed as a structured value or a scope. -
Java Log4j2: object values in a
MapMessage.
The Rust engine and the Fluent Bit filter only ever see JSON and msgpack values, so nothing is turned into text later. Logback and the Log4j2 pattern converters already redacted the formatted text.
Why our tests missed it
The old pino test called our formatters.log with a record that had a msg field in it. Real pino never puts msg there. The test checked the hook contract as we imagined it, not as the logger implements it, so it passed while the real path leaked. The Go, Python, .NET and Java tests had the same blind spot in a quieter form: none of them logged an error, a struct or an object with its own string form that held a secret.
The fix for the tests was the same everywhere: drive the real logger, write to a buffer, search the buffer for the secret. Every new leak test fails on 1.12.0.
What the fix does
One rule, applied per logger: redact what will be printed.
- When the hook meets a value it does not walk, it turns it into text the way the logger would (
Error(),String(),str(),ToString(),String.valueOf) and redacts that text. In Go, structs, typed slices and maps are redacted as their JSON, decoded withUseNumberso int64 ids stay exact, and aPasswordfield is masked whole by the key rule. - Plain numbers and booleans keep their type, so dashboards and queries keep working.
- Where the logger formats the message itself (pino), the integration hooks in earlier, at
hooks.logMethod, to redact the template and its arguments. For a logger whose bound context holds something sensitive, it also redacts the finished line inhooks.streamWrite. That check runs once per logger, so loggers with clean bindings pay nothing extra. - If redaction itself fails, the field becomes
[REDACTION FAILED]. Printing the original is the one outcome a redactor exists to prevent.
A test you can copy
This works whatever you use for redaction, including your own ReplaceAttr or a regex filter. Pick a canary secret, log it through every path your code uses, and search the printed output. The paths that matter: the message text, format arguments, errors (message, stack, traceback), objects with their own string form, child or bound context, and groups or scopes.
Go
func TestLogsNeverPrintTheCanary(t *testing.T) {
const canary = "S3cret-canary-42"
dsn := "postgres://app:" + canary + "@db.internal:5432/prod"
var buf bytes.Buffer
policy, _ := flareredact.Compile(flareredact.Options{})
log := slog.New(flareredact.NewSlogHandler(slog.NewJSONHandler(&buf, nil), policy))
log.Info("connecting to " + dsn) // the message
log.Error("db down", "err", fmt.Errorf("connect %s: refused", dsn)) // an error
log.Info("config", "db", struct{ DSN string }{dsn}) // a struct
log.With("dsn", dsn).Info("pool ready") // bound context
log.Info("pool", slog.Group("db", "url", dsn)) // a group
if strings.Contains(buf.String(), canary) {
t.Fatalf("secret printed:\n%s", buf.String())
}
}
Node.js with pino
import test from 'node:test';
import assert from 'node:assert/strict';
import pino from 'pino';
import { pinoRedact } from 'flare-redact/pino';
test('logs never print the canary', () => {
const canary = 'S3cret-canary-42';
const dsn = `postgres://app:${canary}@db.internal:5432/prod`;
let out = '';
const log = pino(pinoRedact(), { write: (line) => { out += line; } });
log.info(`connecting to ${dsn}`); // the message
log.info('connecting to %s', dsn); // a printf argument
log.error(new Error(`connect ${dsn}: refused`)); // an error
log.info({ db: { dsn } }, 'config'); // a field
log.child({ dsn }).info('pool ready'); // child bindings
assert.ok(!out.includes(canary), out);
});
Python
import io
import logging
from dataclasses import dataclass
import flare_redact.log as flare_log
@dataclass
class DB:
dsn: str
def test_logs_never_print_the_canary():
canary = "S3cret-canary-42"
dsn = f"postgres://app:{canary}@db.internal:5432/prod"
stream = io.StringIO()
log = logging.getLogger("canary-test")
log.addHandler(logging.StreamHandler(stream))
flare_log.install(log) # your redaction setup goes here
log.warning("connecting to %s", dsn) # a format argument
log.warning("config %s", DB(dsn)) # an object with its own str()
try:
raise ConnectionError(f"connect {dsn}: refused")
except ConnectionError:
log.exception("db down") # the traceback
assert canary not in stream.getvalue(), stream.getvalue()
The Go and Node tests fail on flare-redact 1.12.0 and pass on 1.12.1. The Python test passes on both, because install() already redacted the formatted text in 1.12.0; the Python leak needed RedactingFilter on its own.
Upgrade
npm install [email protected]
pip install -U flare-redact
go get github.com/flare-collection/flare-redact/sdk/[email protected]
The Rust crate was not affected. Java and .NET are not on Maven Central and NuGet yet; until they are, build sdk/java with mvn install and sdk/dotnet with dotnet pack from the 1.12.1 tag.
What 1.12.1 still does not cover. A Python traceback is only redacted by the formatter, so use install() or add RedactingFormatter yourself; a filter never sees the rendered traceback. In pino, bindings added with setBindings() after a logger's first line are not checked again. A Node Buffer is printed as its byte values and is not scanned.
The code and every test are in the repository, and the full list of changes is in the changelog.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.