• Removing Passwords from Git History

    Why This Matters

    Any code version control system exists to preserve every project change across its entire history, and, we have to admit, every version control system does this perfectly. So you can be sure: if a password, token, or key ever flashed through your code, it will not disappear the moment you remove it from the current code. An attacker may be able to access it when everyone has already forgotten that important information ever existed in some old commit.

    The bad news is that there is no magic pill that will simply fix everything and require no extra actions or headaches afterward. The good news is that a solution does exist, although it will change every commit starting from the moment the important information is “seized” from storage. That means you will get an entirely different code branch, with entirely different commit hashes.

    git filter-branch --tree-filter 'git ls-files -z "*" |xargs -0 perl -p -i -e "s#(PASSWORD1|PASSWORD2|PASSWORD3)#NOT_A_PASSWORD_ACTUALLY#g"' -- --all
    git reset --hard
    git gc --aggressive --prune

    All the magic is in the first command, which walks through all commits in the current branch and replaces PASSWORD1, PASSWORD2, and PASSWORD3 with a safe placeholder: NOT_A_PASSWORD_ACTUALLY.