Sub topic 2
Finding and Removing Secrets Across Git History
Assume you know basic Git commands, commit hashes, branches, and how to run commands in a shell. You also need permission to rewrite and force-push the repository.
Find the secret and its commits
A secret remains exposed in an old commit even after you delete it in a later commit. Search all reachable references with git log:
git log --all --oneline -S'AKIAEXAMPLEKEY12345'The -S option finds commits where the number of occurrences of the exact string changed. It can reveal the commit that added the secret and later commits that removed it. Search broadly because the secret might exist on another branch or tag.
For larger repositories, git filter-repo can create an analysis report:
git filter-repo --analyze
less .git/filter-repo/analysis/path-all-sizes.txtThe report helps identify suspicious paths and large historical files.
Remove a whole file from all history
If the file contains only secrets, remove its path from every commit:
git filter-repo --invert-paths --path config/secrets.env--invert-paths means “keep everything except this path.” Use the exact historical path. If the file moved, specify each old path with another --path option.
Replace secret strings across history
When a file also contains useful content, replace only the sensitive text. Store the rules outside the repository:
literal:AKIAEXAMPLEKEY12345==>REDACTED
regex:password\s*=\s*\S+==>password = REDACTEDRun the replacement:
git filter-repo --replace-text ../expressions.txtEach rule matches a literal string or regular expression and writes the replacement into every historical file version.
Clean commit messages
--replace-text does not rewrite commit messages. Apply the same expressions file separately:
git filter-repo --replace-message ../expressions.txtThe rewritten commits receive new hashes because their contents or metadata changed.
Exercise
Which option should you use when a configuration file contains both safe settings and a leaked token?
Show answer
Use --replace-text to replace the token while preserving the safe settings.