Programming & Coding How-TosTechnology

Remove a Password From Git History Safely

Admin
Remove a Password From Git History Safely

It happens in a single careless moment. You are testing an app, you paste a real database password or API key into a config file, and you commit and push before you notice. Now that secret sits in your Git history, where anyone with access to the repository may be able to find it.

Deleting the password and making a new commit is not enough. Git keeps old versions, so the secret stays in earlier commits. You must rewrite history and treat the secret as exposed.

This guide explains both parts calmly and clearly: how to change or rotate the leaked secret, how to remove it from every commit using modern tools, and how to push the cleaned history safely when you work with other people.

Quick Answer

First, change the leaked password immediately, because anything pushed should be treated as public. Then remove it from history with a tool such as git filter-repo or BFG Repo-Cleaner, force-push the cleaned repository, and ask every collaborator to re-clone. A normal delete commit does not remove a secret from Git history.

Why Deleting the File Is Not Enough

Git does not store only your latest files. It stores a snapshot of your project at every commit, and those snapshots stay reachable through the history. If a password existed in commit five, it remains in commit five even if you removed it in commit six.

Anyone can look back through history and read old file versions, and scanning tools can find patterns that look like keys in seconds.

That is why secret leaks are handled in two stages. Stage one is damage control: the old secret must stop working. Stage two is cleanup: the secret must be scrubbed from history so it does not keep spreading to every new clone.

Step 1: Rotate the Secret Immediately

Do this before anything else. If the password was pushed to a shared or public place, assume others already have it.

  1. Log in to the service the password belongs to, such as your database host, cloud provider, or API provider.
  2. Change the password or revoke the API key and generate a new one.
  3. Update your local app with the new secret, using an environment variable or a private config file that is not tracked.
  4. Test that your app still works with the new secret.
  5. Check access logs, if available, for use of the old secret.

This step matters more than cleaning. A cleaned repository does not help if the old password still works — rotation makes the leaked value useless.

Our complete GitHub beginner guide for new developers covers safe habits like this that protect projects from day one.

Step 2: Find Where the Secret Appears

Before rewriting history, learn the size of the problem. You need to know which files contain the secret and roughly when it was added.

  1. Search the current files with grep -r "your-password" . or your editor’s search tool.
  2. Search all history with git log -p --all -S "your-password" to see commits that added or removed that text.
  3. Note the file names, such as config.js, .env, or settings.py.
  4. Decide whether the whole file should be removed from history, or only the secret line replaced.

Often the safest choice is to remove the sensitive file from history completely, then re-add a safe version that reads secrets from the environment.

Step 3: Back Up Before You Rewrite

History rewriting changes commit IDs and is hard to undo. Make a simple backup first.

  1. Clone a fresh copy of the repo into a backup folder, or copy your current project folder somewhere safe.
  2. Make sure all your real work is committed and pushed, so nothing exists only on your machine.
  3. Tell any collaborators to pause pushing until the cleanup is finished.

Step 4: Remove the Secret with git filter-repo

The recommended modern tool is git filter-repo. It is fast, careful, and designed exactly for rewriting history. You may need to install it first using your package manager or pip, following its official instructions.

Option A: Remove a Whole File From History

If the secret lives in a file that should never have been tracked, remove that file from every commit:

git filter-repo --path .env --invert-paths

Replace .env with your real file path. The --invert-paths flag means “keep everything except this path.” The tool rewrites the history and removes the file everywhere it appeared.

Option B: Replace Only the Secret Text

If the file itself is fine and only one line is sensitive, you can replace just that text everywhere:

  1. Create a plain text file called replacements.txt.
  2. Add a line with your secret followed by its replacement, like this: myRealPassword123==>***REMOVED***
  3. Run git filter-repo --replace-text replacements.txt.
  4. Delete replacements.txt afterwards, since it contains the secret too.

The official Git documentation about rewriting history explains the built-in older tool and why careful history rewriting matters, while the filter-repo project is now the preferred choice for most cleanups.

Step 5: Using BFG Repo-Cleaner as an Alternative

BFG Repo-Cleaner is another popular tool for this job. Make a fresh mirror clone with git clone --mirror https://github.com/you/repo.git, then run java -jar bfg.jar --delete-files .env repo.git to remove a file, or java -jar bfg.jar --replace-text passwords.txt repo.git to replace listed passwords. Afterwards run git reflog expire --expire=now --all && git gc --prune=now --aggressive to clear leftover objects. Choose one tool and follow it fully — do not mix BFG and filter-repo on the same cleanup.

Step 6: Verify the Secret Is Gone

Never assume the cleanup worked. Check it directly before pushing.

  1. Run git log -p --all -S "your-password" again. It should return nothing.
  2. Search all commits with git grep "your-password" $(git rev-list --all) if you want an extra check.
  3. Open a few old commits and confirm the file or line no longer contains the secret.
  4. Run your project and its tests to confirm the rewrite did not damage real code.

If the secret still appears, repeat the cleaning step on a fresh clone. Do not push a half-cleaned history.

Step 7: Force-Push and Help Your Team

Rewriting history means your local history no longer matches the remote. A normal push will be rejected, so you must force-push the cleaned version.

git push --force --all
git push --force --tags

After the push, every collaborator must get the new history. The cleanest method is for each person to delete their local copy and clone again fresh. Trying to merge old and new history often brings the secret back.

  • Announce when it is safe to clone again.
  • Ask everyone to delete old local copies, including backup clones and forks if the secret reached them.
  • For public repositories, contact the hosting provider’s support if cached views or forks still expose the secret.

The GitHub guide to removing sensitive data explains the hosting side of this process, including forks and cached pages, in clear detail.

How to Prevent This Next Time

These small habits stop secrets entering Git in future projects:

  • Keep secrets in a .env file and list that file in .gitignore before your first commit.
  • Share a safe example file called .env.example with fake values and clear labels.
  • Read secrets in code from environment variables, not from hard-coded strings.
  • Review git status and your staged changes before every commit.
  • Turn on secret scanning and push protection in your repository settings if your host offers them.
  • Use a pre-commit scanning tool that warns you when a change looks like a key or password.

Common Mistakes to Avoid

  • Only deleting the file in a new commit: The secret stays in old commits and can still be found in seconds.
  • Cleaning history but not rotating the password: Anyone who copied it earlier can still use it. Rotation always comes first.
  • Force-pushing without warning the team: Teammates may re-push the old history and restore the secret by accident.
  • Forgetting forks and clones: The secret can live on in copies outside the main repository.
  • Leaving the replacements file in the project: That file contains the real secret, so delete it or keep it far outside the repo.
  • Panicking and deleting the whole repository: In most private cases, rotation plus history cleaning solves the problem without losing your project.

Conclusion

A password in Git history feels like a disaster, but it is a fixable and very common mistake. Rotate the secret first so the leaked value stops working, then rewrite history with git filter-repo or BFG, verify the secret is truly gone, and force-push so everyone starts again from the clean history.

Afterwards, protect yourself with a proper .gitignore, environment variables, and a quick review before each commit.

Frequently Asked Questions

Can I just delete the repository and start again?

You can for a small personal project, and it is sometimes the simplest option. For team or public projects, deleting loses issues, pull requests, and history you need, so rotation plus history cleaning is usually the better path.

Does changing the file in the latest commit remove the secret?

No. Git keeps every earlier snapshot. The secret remains visible to anyone who looks at the older commit, which is exactly why history rewriting tools exist for this job.

Will rewriting history break my project?

It changes commit IDs, so old links to commits stop working and collaborators must re-clone. The files and code themselves stay the same when the cleanup is done correctly and verified before pushing.

What if the secret was only in a private repository?

Still rotate it. Private repos can be cloned, shared, or made public later, and team members change over time. Treating every pushed secret as exposed is the safe professional rule.

How long does GitHub keep the old commits after a force-push?

Cached views and forks can keep data reachable for a while. If the secret is serious, contact GitHub Support after cleaning and ask them to clear cached views of the affected commits.

Admin

Passionate about the intersection of style and storytelling. I simplify fashion trends and industry news into easy-to-follow advice, helping you stay stylish and informed in the fast-paced world of fashion.

Leave a Reply

Your email address will not be published. Required fields are marked *