FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

One misplaced filter, and Python still logs your passwords

A redaction filter only works on the handler, and it has to scrub arguments and tracebacks as well as the message itself.

ShareLinkedInFacebookX

In brief

  • A filter on a parent logger skips records from child loggers; a filter on the handler catches every record.
  • Secrets can sit in args and tracebacks, so fixing msg alone is not enough.
  • From Python 3.12, a filter can return a redacted copy without affecting other handlers.
Table comparing three ways of writing and attaching a secret-masking filter in Python logging, tested against three leak paths: a password in args, a token in a traceback and records from a child logger. A filter that masks only msg and sits on the handler leaks args and the traceback. A full-masking filter on the parent logger leaks records from the child logger. Only a full-masking filter on the handler stops all three; its row is highlighted in orange.
The filter must mask the message after args have been merged (getMessage), mask the traceback too, and be attached to the handler. A filter on a parent logger is not applied to records propagated up from child loggers. Source: Python's logging module documentation, as cited in the article.

In May 2018 Twitter admitted that a bug had caused user passwords to be written to an internal log before they were hashed. In the same period, The Register quoted GitHub as saying that a newly introduced bug had made its “secure” internal logs record passwords in plain text.

In both cases the passwords escaped by the same route: internal logs.

For FDEs the risk sits closer to home. Your code runs in the client’s infrastructure, your logs flow into their systems, and the token you use to call an API is often the client’s own.

OWASP lists access tokens, authentication passwords and database connection strings among the data that should usually not be written directly to logs. One careless log.info call can turn into a security incident with your name on it.

This guide shows how to write a logging.Filter that masks secrets, attach it in the right place and back it with a test. The full version needs Python 3.12 or later. Notes for older versions are in step 3.

Step 1: write the masking function separately from the filter

Start with a pure function that is easy to test. GitHub tokens carry recognizable prefixes: ghp_ for classic personal access tokens, github_pat_ for fine-grained ones, gho_ for OAuth, and ghu_, ghs_ and ghr_ for GitHub Apps. That keeps the regex fairly compact.

# redact.py — trimmed version; extend the regex for your real system
import re

TOKEN_RE = re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]+|\bgithub_pat_[A-Za-z0-9_]+")
KV_RE = re.compile(r"(?i)\b(password|passwd|pwd|token|secret)=([^\s&]+)")

def redact(text: str) -> str:
    text = TOKEN_RE.sub("[REDACTED]", text)
    return KV_RE.sub(r"\1=[REDACTED]", text)

Check it straight away in the REPL: redact("password=hunter2 token ghp_abc123") should return password=[REDACTED] token [REDACTED]. Keeping the key name means whoever reads the log still knows what the line is about.

Step 2: the filter must handle args, not just msg

This is where many people go wrong. A log message is assembled from msg % args, so with log.info("login %s", password) the password lives in args, while msg is just "login %s". A filter that runs its regex over record.msg sees nothing.

The safe approach is to call record.getMessage(), which returns the message after the arguments have been merged in, mask that string and then clear args.

# redact.py (continued)
import copy
import logging

class RedactFilter(logging.Filter):
    def filter(self, record):
        record = copy.copy(record)          # do not modify the original
        record.msg = redact(record.getMessage())
        record.args = None
        if record.exc_info:
            text = logging.Formatter().formatException(record.exc_info)
            record.exc_text = redact(text)
            record.exc_info = None
        return record                        # Python 3.12+: return the new record

The exc_info handling is not decoration. The formatter formats the traceback, appends it after the message and caches the result in exc_text. Mask only msg, and an exception such as ValueError("bad token ghp_...") still prints the full token on the last line of the traceback.

Here the filter formats the traceback itself, masks it and places it in exc_text ready for the formatter to reuse. This version does not yet handle stack_info; add that if your project uses stack_info=True.

Step 3: why return a copy

From Python 3.12 a filter may return a new LogRecord in place of the original. The Python documentation states the purpose plainly: a filter on a handler can modify the record before it is emitted without side effects on other handlers. You can mask logs sent to an external service while keeping the original record for another handler, if you genuinely need it.

On older versions a filter only returns true or false, so you have to modify record in place and drop the copy.copy line. Every handler downstream then sees the masked version. When the aim is to block secrets, that is usually what you want anyway.

Nor do you have to subclass logging.Filter. Any object with a filter method of the same semantics will do, and since 3.2 a plain function can serve as a filter. A subclass simply makes the code easier to read.

Step 4: attach it to the handler, not the parent logger

This is the costliest mistake, because the code looks right and a cursory test still passes.

# main.py
import logging
from redact import RedactFilter

handler = logging.StreamHandler()
handler.addFilter(RedactFilter())      # the right place

root = logging.getLogger()
root.addHandler(handler)
root.setLevel(logging.INFO)

log = logging.getLogger("app.db")
log.info("connect user=%s password=%s", "bob", "hunter2")
log.info("using token %s", "ghp_abc123XYZ")
try:
    raise ValueError("bad token ghp_abc123XYZ")
except ValueError:
    log.exception("call failed")

Run python main.py. The first line should read connect user=bob password=[REDACTED], the second using token [REDACTED], and the last line of the traceback ValueError: bad token [REDACTED].

Now get it wrong on purpose: remove handler.addFilter(...) and use root.addFilter(RedactFilter()) instead. The password appears verbatim. The cause lies in two rules of the logging module.

A filter attached to a logger does not filter records created by child loggers unless you attach it to that child logger itself. With propagation on, records from app.db are passed straight to the parent logger’s handlers, and the parent logger’s level and filters are never consulted.

The handler is the point every record must pass through before it is written, and a handler’s filter is called just before that write. If the project has several handlers (console, file, a log aggregation service), each one needs its own filter.

Step 5: lock it in with a test

A filter without a test will break silently the day someone changes the logging configuration. The test below attaches the filter to a handler that writes to a buffer and asserts that the secrets are gone.

# test_redact.py — run with pytest
import io, logging
from redact import RedactFilter

def test_secret_not_in_output():
    buf = io.StringIO()
    h = logging.StreamHandler(buf)
    h.addFilter(RedactFilter())
    log = logging.getLogger("test.child")
    log.addHandler(h)
    log.setLevel(logging.INFO)
    log.info("pw=%s password=%s", "x", "hunter2")
    try:
        raise RuntimeError("ghp_abc123XYZ")
    except RuntimeError:
        log.exception("boom")
    out = buf.getvalue()
    assert "hunter2" not in out
    assert "ghp_abc123XYZ" not in out

If the project configures logging with dictConfig, watch one parameter: disable_existing_loggers defaults to True. Existing non-root loggers can be disabled, and you will lose logs while assuming the filter dropped them. Set it to False before hunting for a bug in the filter.

Where does key-name regex fall short?

Masking by key name only catches what you anticipated. Apache Airflow’s documentation concedes as much: in a Connection’s JSON extra field, keys that do not contain a sensitive keyword are not masked automatically. A field named api_credential would slip past the regex in step 1.

Airflow compensates by masking by value: you register the secret string itself with mask_secret, and the system masks it wherever it appears. But the documentation also warns that the value must be registered before any log or output is produced, or it has no effect.

The lesson carries over to your own filter: if the app reads secrets from environment variables at startup, add them to the masking list at that moment, before the first log line.

Using this skill on a client site

On the first day with a client, one of the first things to do is read the logs your integration produces in their staging environment, searching for password=, token, the ghp_ prefix or database connection strings. If the client runs Airflow, check the keys in each Connection’s extra, because that is where automatic masking misses.

On a CV, skip the generic “security-minded”. Be specific: added a redaction filter on every handler, with a test that blocks tokens even in tracebacks. In an FDE interview, be ready to explain why the filter has to sit on the handler, using the two propagation rules above.

Twitter and GitHub both found their bugs after the passwords were already in the logs. A test of roughly fifteen lines running in CI would catch the same bug before your code reaches the client.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
6 sources
Read next on the roadmap · Stage 1: FoundationsA client's zip file can overwrite files on your machineChecking each entry before extraction is only the first layer of defense: you also need resource limits and a patched version of Python.