Sub topic 8
Replacing secret strings across history
This chapter covers rewriting file contents with git filter-repo --replace-text. It assumes you have already rotated the leaked credential, found the commits that contain it (previous chapters), and are working in a fresh clone. You should be comfortable with basic Git commands and with the idea that a commit hash depends on the content it points to.
When to replace text instead of removing a file
Removing a path with --invert-paths is the right tool when the whole file is the problem, such as a secrets.env that should never have been committed. Many leaks are not like that. A real source file, such as a settings module, a deploy script, or a test fixture, may contain one hardcoded key. Deleting that file from history would also delete code you want to keep.
--replace-text handles this case. It visits every version of every file in history and substitutes matching text. The file stays in every commit, and only the secret changes.
| Situation | Better choice |
|---|---|
| A file that is entirely sensitive (`.env`, a private key file) | `--invert-paths --path <file>` |
| A key hardcoded inside a file you want to keep | `--replace-text` |
| The same key appears in many files | `--replace-text` |
| The secret is in a commit message | `--replace-message` (next chapter) |
How --replace-text works
You give the tool an expressions file. For each blob (the stored content of one version of one file) in history, git filter-repo applies every rule in that file and writes a new blob if anything changed. Commits that point to a changed blob get a new tree and therefore a new hash. Every descendant commit also gets a new hash, because each commit hash includes its parent's hash.
Two consequences follow:
- The current files at the tip of each branch are rewritten too. If a secret is still in
HEAD, it is replaced there as well, so the working tree will contain the placeholder after the run. - Commits that never contained the secret keep their content, but they get new hashes if they are descendants of a rewritten commit. Only commits before the first change keep their original hashes.
The expressions file
The expressions file is plain text with one rule per line. A rule has the form pattern==>replacement. A prefix on the pattern selects how it is matched:
literal:matches the exact text. This is the default if no prefix is given.regex:matches a Python regular expression.
If you omit ==> and the replacement, the tool substitutes the default text ***REMOVED***.
Here is the file from the earlier chapter, with one literal rule and one regex rule:
literal:AKIAEXAMPLEKEY12345==>REDACTED
regex:password\s*=\s*\S+==>password = REDACTEDThe first rule replaces one known key with REDACTED. The second replaces any assignment such as password = hunter2 or password=hunter2 with password = REDACTED. The whole match is replaced, so the replacement must contain any part you want to keep, here the password = prefix.
Choosing literal or regex
Prefer literal: whenever you know the exact string. A literal rule cannot match anything you did not intend. Use regex: when the value varies, for example several keys from the same provider or a password assigned in many files.
Regex rules need care:
- A pattern that is too broad will damage code. A rule like
regex:\S+==>Xwould destroy every file. - A pattern that is too narrow will miss variants, such as a key wrapped in quotes or split over lines.
- Escape special characters in secrets if you use regex. A literal rule avoids this problem, since characters like
+,.and$are common in tokens.
Replacement text should be harmless and obvious. A marker like REDACTED tells later readers that something was removed on purpose. Do not use a value that looks like a working credential.
A complete runnable example
This script builds a small repository where a key was committed and then "removed" in a second commit. It then clones the repository and cleans the clone. It assumes git and git-filter-repo are installed and that your Git supports git init -b.
set -e
mkdir demo-origin && cd demo-origin
git init -q -b main
git config user.name "Demo"
git config user.email "[email protected]"
printf 'region = eu-west-1\naws_key = AKIAEXAMPLEKEY12345\n' > settings.ini
git add settings.ini
git commit -qm "Add settings"
printf 'region = eu-west-1\naws_key = from-env\n' > settings.ini
git commit -qam "Remove key from settings"
cd ..
printf 'literal:AKIAEXAMPLEKEY12345==>REDACTED\n' > expressions.txt
git clone -q --no-local demo-origin demo-clean
cd demo-clean
echo "--- before ---"
git log --all --oneline -S'AKIAEXAMPLEKEY12345'
git filter-repo --replace-text ../expressions.txt
echo "--- after ---"
git log --all --oneline -S'AKIAEXAMPLEKEY12345'
git show "$(git rev-list --max-parents=0 HEAD)":settings.iniBefore the rewrite, the -S search lists the two commits where the number of occurrences changed: the one that added the key and the one that removed it. After the rewrite, the search prints nothing, and the first commit's settings.ini shows aws_key = REDACTED. The second commit now changes REDACTED to from-env, and both commits have new hashes.
The expressions file sits next to the clone, not inside it. --no-local makes Git copy objects into a pack instead of hard-linking them. This gives git filter-repo the clean state it expects.
Applying the rule to a real repository
On a real repository, the steps from earlier chapters apply unchanged: a fresh clone, then --replace-text.
git clone [email protected]:org/repo.git repo-clean
cd repo-clean
git filter-repo --replace-text ../expressions.txtThe tool runs through every commit, prints progress, repacks the repository, and removes the origin remote. The remote is removed on purpose, so you cannot push rewritten history by accident. You restore it later when you are ready to push.
Common errors and gotchas
The tool refuses to run. git filter-repo checks that the repository looks like a fresh clone. If it says the clone is not fresh, start over with a new clone. Avoid --force for this job. The check exists because a rewrite destroys the original objects, and in a working repository those may be your only copy.
The secret is still found afterwards. Possible causes:
- The secret appears in a form your rule does not match, such as with different quoting, in a different case, or Base64-encoded.
- The secret was in a file path or a commit message.
--replace-textchanges file contents only. File names need--invert-pathsor path renaming, and messages need--replace-message. - You searched an old clone or a different copy of the repository.
- The secret appears in a tag message or a ref name, which this option does not rewrite either.
Regex matches too much. Test the pattern on the current files first with git grep -nE 'your-pattern' (note that git grep -E uses POSIX extended syntax, which differs slightly from Python). Then check the result after the rewrite with git diff against the original clone's main. Large unexpected differences mean the rule is too broad.
Binary files and encodings. The rules operate on bytes. A secret stored in a compressed archive, an image, or a UTF-16 file will not match a plain text rule. Search for those files by path with the analysis report, and remove them with --invert-paths.
Rewritten hashes break references. Issues, pull request comments, release notes, and other documents that link to old commit hashes now point to commits that no longer exist in the rewritten history. git filter-repo writes a commit-map file under .git/filter-repo/ that maps old hashes to new ones, which you can use to repair references that matter.
What comes next
After the rewrite, the work is not finished. You still need to clean commit messages if they contain the secret, verify that no ref contains it, restore the remote and force-push, and deal with forks and cached copies. The following chapters cover each of these.
Exercise
A repository has a Python file deploy.py that contained the line TOKEN = "ghp_EXAMPLE123" in 40 commits, and the token is also in one commit message. You want to keep deploy.py in history. Which command removes the token from the file contents, which line in the expressions file would you write, and what will still contain the token afterwards?
Show answer
Run git filter-repo --replace-text ../expressions.txt in a fresh clone, with the file stored outside the repository and containing the line literal:ghp_EXAMPLE123==>REDACTED. The file contents are cleaned in all 40 commits and at the tip. The commit message still contains the token, because --replace-text does not touch messages. You need --replace-message for that, and you must also have rotated the token first, since old clones still hold it.
Exercise
Why do commits that never contained the secret still get new hashes after --replace-text?
Show answer
A commit's hash includes its parent's hash. Once any ancestor is rewritten and gets a new hash, every descendant must be recreated with the new parent, so it also gets a new hash even though its own file contents did not change.