Expand description
Finding secrets in a string and replacing them with a marker that says what was there.
This is the matching half of the redact-secrets hook (crate::hooks); it is a pure
function over text, so it can be tested without a loop, a config or a store.
§Hand-written, high precision first
There is no regex engine here, on purpose: every dependency is a thing to audit, and the shapes below are all “a literal prefix, then a run of characters from a small set”. Each one is cheap to scan for and cheap to reason about. The trade is made explicit:
- A pattern with a distinctive prefix (
sk-,ghp_,AKIA, a PEM header) fires on the prefix and a minimum length. A near-miss — one character short, a word that merely contains the prefix — is left alone, because a false positive mangles a file the user asked to read. - The assignment pattern (
password = …) has no distinctive prefix, so it is the one that can over-match:token = refresh_access_token_nowlooks like a secret to a scanner that has no idea what a variable is. It is kept becauseAPI_TOKEN=…in an.envis the commonest way a real secret reaches a prompt;allowis the escape hatch.
§Properties that are tested
- Idempotent. Redacting redacted text changes nothing. A marker never contains a run the scanner would take for a secret, and the text before and after a marker is judged the same way both times.
- A marker is not a secret. Text that is already
[redacted:…]is skipped whole. - Ordinary text is byte-identical: prose, logs, code that merely mentions a password.
- Matches never overlap, and the earliest pattern in the text wins: in
API_KEY=sk-…the label isapi_key, not a second marker nested in the first.
Only the secret is replaced where a pattern has context worth keeping: Bearer stays,
the user in https://user:pass@host stays, the name in password=… stays. The reader
— the model — can still see what kind of thing was there.
Structs§
- Redacted
- What a redaction pass did.
Functions§
- redact
- Replace every secret in
input. A match that lies entirely inside one of theallowstrings (compared literally) is left as it is.