Skip to main content

Hushfang

Hushfang, value-based redaction for Python logs

PyPI version

Hushfang lets the code that loads a credential teach the logger what to hide. Register a Pydantic secret while its type and purpose are known. When an SDK repeats it in a retry message or traceback, Hushfang can mask the recognized value and leave the request ID and failure reason intact. The library depends only on Pydantic.

Design principles for logging secrets · Hushbench

Installation

Hushfang requires Python 3.11 or later. To add it to a uv project, run

uv add hushfang

To install it with pip in your active environment, run

python -m pip install hushfang

Why a secret registry?

Settings register the SecretStr with SecretRegistry before the SDK receives a plain string. RedactingFormatter uses that same registry to mask the SDK's retry diagnostic before the handler writes it.

Runtime value registries also exist in Airflow, GitHub Actions and logmask. Hushfang brings typed Pydantic registration, explicit reveal boundaries and type-specific matching into an application-owned registry. Hushbench compares their actual output. Runtime registry design and prior art · Runtime comparison

The idea grew out of validating application settings. When a service reads a field declared as SecretStr, it knows exactly which value is private. Printing the wrapper shows a mask. An SDK making an authenticated request, however, needs the actual value. Once it calls a retry logger with an ordinary string, the field name and the Pydantic type are gone.

Suppose the token is cedar/47+mint. A client URL-encodes it and logs a rejection. Here is the same retry before and after redaction.

SDK diagnostic:   request=r-17 attempt=2 rejected cedar%2F47%2Bmint
Protected output: request=r-17 attempt=2 rejected ***

An operator can recognize r-17 as a request ID, but what makes the last string private? Only the settings loader saw it arrive as an API key. A SecretRegistry is the in-memory collection of known secret values and the forms they can take. The settings loader adds to it, and the log handler consults it.

  1. Register at the source. Pass one wrapped value to registry.register(secret), or pass validated settings to registry.register_model(settings). Registration prepares matching data in process memory. For a text token this includes its literal value and common encodings. A SecretMnemonic can also match a run of recovery words. The declared type tells Hushfang which forms to look for.
  2. Match at the handler. Give the same registry to RedactingFormatter. After Python interpolates the arguments and formats any traceback, the formatter replaces matching spans in the resulting text with ***. The client gets the credential it needs, and the operator keeps the request ID and retry count.

For a retry event you control, a request ID, attempt number and status code are usually enough. The registry also covers recognized values that an SDK includes in its own diagnostic. Designing a retry event

Run the example

import logging
from urllib.parse import quote

from pydantic import BaseModel, SecretStr

from hushfang import RedactingFormatter, SecretRegistry


class Settings(BaseModel):
    api_key: SecretStr


settings = Settings(api_key="cedar/47+mint")
registry = SecretRegistry()
registry.register_model(settings)

handler = logging.StreamHandler()
handler.setFormatter(RedactingFormatter(registry, "%(message)s"))
logger = logging.getLogger("example.sdk")
logger.propagate = False
logger.addHandler(handler)


def sdk_retry(request_id: str, attempt: int, token: str) -> None:
    # Simulate a client that includes the URL-encoded value in a retry message.
    logger.warning("request=%s attempt=%d rejected %s", request_id, attempt, quote(token, safe=""))


sdk_retry("r-17", 2, settings.api_key.get_secret_value())
# request=r-17 attempt=2 rejected ***

Inspect this behavior in the detailed Hushbench report or compare Airflow, GitHub Actions and Python masking libraries side by side.

For two more runnable cases, see loading credentials from TOML and signing with a generated key.

You can also run the demo from a repository checkout.

uv sync --locked
uv run --no-sync python demo.py

Who owns the registry?

Create a registry for the application or worker and share that instance with its text handlers. Register a replacement credential before the first request that uses it. Keep the old value registered while queued records can still mention it. Calling clear() removes all registrations from that instance. Treat the registry as sensitive for its entire lifetime because it holds values and reversible encodings.

The registry can recognize only what its matching rules cover. For example, an unregistered token can pass through, while registering the short value prod in the default mode also masks those letters in production. A separate error reporter that sends an exception directly needs its own redaction step. Design principles and the secret lifecycle

Coverage

Secret types, validation, disclosure and exceptions · Cryptographic test vectors

  • Register individual SecretStr and SecretBytes instances, or walk stored fields on an already validated model. The walk includes excluded fields, extras, nested models and standard containers. It handles cycles and skips computed properties.
  • Matching covers complete literals, Python and JSON escapes, standard and URL-safe padded Base64, hexadecimal, and common URL encodings. For a URL with credentials, the registry also covers its password and Basic credentials encoded as UTF-8 or Latin-1 when representable. A validated Secret[HttpUrl] can be registered directly.
  • Overlapping matches are merged. Registering a short value can also mask ordinary text containing it. With the default policy, fragments of a truncated credential may survive. Select SecretRegistry(token_mode="delimited") for clients that log token fragments.
  • Pass mask_extra={"password"} to the formatter to replace that top-level log-record field even if its value is unknown. The same rule applies to nested mapping keys in messages, arguments and extras.
  • Install the formatter on each text handler that needs masking. Direct writes, separate telemetry exporters, validation failures before registration and logs emitted before registration are outside its coverage. A formatting failure emits a fixed diagnostic so the logging error path cannot echo the bad arguments.

Test and compare

With Task and uv installed, run task to list commands, task bench for the full comparison or task bench:password for the four password cases. Open hushbench-report/results.html after the full run.

Hushbench is the benchmark workspace member. It compares Hushfang, Python's standard formatter, logmask and loggingredactor on the same synthetic records. Reports show exact output, exposed canaries, altered public controls, dropped records and formatting cost. Expand a case in the HTML report to see the original event alongside each adapter's output.

uv sync --locked --all-packages
uv run --no-sync hushbench --output hushbench-report
uv run --no-sync ruff check .
uv run --no-sync ruff format --check .
uv run --no-sync ty check

CI runs the library tests and benchmark on Python 3.11, 3.12, 3.13, 3.14 and 3.15. The combined artifact contains an offline HTML index with a report for each interpreter. Results by scenario · Corpus and metrics · CI runs and downloads

The CI artifact includes a second report from 1,630 public cryptographic test events on each Python version. Sources and reproduction

How does Hushfang compare?

On 134 shared text-registration cases, Hushfang produced 129 exact lines with its default policy and 133 with the delimited policy. The remaining delimited case involved an unregistered password inside serialized JSON. Airflow preserved all 18 public controls, and logmask was faster on the one-secret timing test. The corpus includes 78 wallet cases. Run task bench:runtimes to compare the seven configurations on the same events and inspect their output. Comparative report and methodology

How much latency does Hushfang add?

On an Apple M1 Max with CPython 3.14, one registered value added a median 3.0 µs to a clean text record and 3.6 µs to a record with one match. With one million registered values those medians were 14.0 µs and 14.6 µs. Hushfang 0.1.0 took 1.47 s and 1.41 s on the same million-value workload. Registering that batch in 0.2.0 took 12.43 s and peak worker memory was 1.50 GiB.

The test formatted a 66-byte record without I/O, using the default exact policy. Long tracebacks, binary records and more varied credential lengths need their own measurements. Run task bench:latency to reproduce the sweep. All sizes, p95 and memory

Development roadmap

The next experiments measure rotation and memory costs, test credentials across queue boundaries, and follow structured events into structlog and telemetry exporters. Each milestone has a paired public control and a destination-level acceptance test. Research and roadmap

Packaging

The library and benchmark share a uv lockfile. Installing Hushfang alone brings in Pydantic. The release rehearsal builds the library's wheel and source distribution and tests each in a clean environment. Packaging and release workflow

An unsuccessful model validation can include the original input before a secret wrapper exists. On Pydantic 2.14.4, hide_input_in_errors=True hides input when printing the exception. Structured outputs still include it unless the caller passes include_input=False. The accompanying fork changes that default for structured errors and preserves explicit overrides. Experimental patch and regression tests | Pydantic issue 7461

Metadata

Release files for hushfang 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for hushfang 0.2.0
File Size Uploaded Provenance Actions
hushfang-0.2.0.tar.gz 20.7 kB Without provenance Details for hushfang-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for hushfang 0.2.0
File Interpreter ABI Platform Actions
hushfang-0.2.0-py3-none-any.whl Python 3 none any Details for hushfang-0.2.0-py3-none-any.whl

Total release size: 43.6 kB

Release files / hushfang-0.2.0.tar.gz

Download URL hushfang-0.2.0.tar.gz
Size 20.7 kB
Tags Source
SHA-256 checksum
How to use checksums
094aa0e9f5e451a5edc1fbf8b070844d86a66600ef3b1ba43c0ae6d91ccfb088
BLAKE2b-256 checksum
How to use checksums
98de1dc8b8b623c6422dbd8712bf41fe824ea48364b5b3f1994af29b17c59cb4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.13 {"installer":{"name":"uv","version":"0.13.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / hushfang-0.2.0-py3-none-any.whl

Download URL hushfang-0.2.0-py3-none-any.whl
Size 22.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
07aba9e35a0b8e910b5667fdf3b72e17224422c666480415f70ecb1a9a6b5708
BLAKE2b-256 checksum
How to use checksums
359324f73696c5d79cc78de59c17929e77942213bc09f6b089faaf4a30139b49
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.13 {"installer":{"name":"uv","version":"0.13.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for hushfang 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page