DEV Community

Raghunathan R
Raghunathan R

Posted on

How to remove a sensitive file from GitHub

Yes! this has happened to most of the people, especially when we are just starting. We accidentally commit sensitive data to GitHub. We forget to gitignore our config file containing database passwords or API keys or jwt secrets. And we immediately start to panic.

This happened to me a couple of days ago. I forgot to ignore my default JSON file that contained my database connection password and jwt secret. I had just gotten a feature to finally work and in the excitement, I immediately committed and pushed to GitHub. I only realized my error when I got a notification from GitGuardian that my latest commit contained secret keys.

If you find yourself in the same position, the first thing you do is change the visibility of the repo. So, if it's a public repo, make it private. This way, you're sure no one else sees the file while you're working on deleting it.

Next thing, if you aren't already in the project folder, cd into it on git bash or whatever terminal you are using. Let's assume my project folder is My-Project and I have a file named secretFile.json I want to delete.

cd My-Project

then run the following command. You have to include the path to the file and not just the file name.

git filter-branch --force --index-filter \
  "git rm --cached --ignore-unmatch config/secretFile.json" \
  --prune-empty --tag-name-filter cat -- --all
Enter fullscreen mode Exit fullscreen mode

replacing config/secretFile.json with the path to the file you want to be removed. In my case, secretFile.json is inside of a folder named config.

Note: The command above deletes the file from your local repository too, so ensure you have copied the content to a notepad or whatever you use before running the command.

Then create and add your file to .gitignore so you don't accidentally push it to GitHub again. You can do that with

echo "name-of-your-file" >> .gitignore

git add .gitignore

git commit -m 'add file to .gitignore'

Once you are satisfied with your changes, you can then push them to GitHub

git push origin --force --all

And that's it! Your repo history is clean without any trace of your sensitive file.

Thanks for reading.

Top comments (2)

Collapse
 
jazzyboy1 profile image
Jaz

I would suggest that you probably shouldn't assume that you're safe just by deleting the file from the repo. Automated bots can move very quickly through public pages on the web; a page could be archived at any second; etc.

The safest thing to do here in my opinion would be to revoke your secrets/API keys entirely and generate new ones as soon as possible. Better to be safe than sorry :)

Collapse
 
rindraraininoro profile image
Raininoro Rindra

Sometimes we need to remove old commits, rewrite the history on a file change. In that case, need to do an interactive rebase.