Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove sensitive data (API_KEY) across git commit history?

I finished an android project that requires me to use an api_key. I've added the api key in my build.gradle file like this:

     buildTypes.each {
         it.buildConfigField "String", "MDB_API_KEY", "\"243248324293938243\"" 
     }

(that's a random number btw)

Now that I finished the project I need to upload it to Github, for code review. Before doing so, I was asked to remove the api key, and I did

buildTypes.each {
     it.buildConfigField "String", "MDB_API_KEY", *putYaOwnApiKeyBrothar*
         }

and committed.

But if I push everything to Github, they could access any older commit, and retrieve my api_key.

I've seen similar questions, and the solution seems to be git filter-branch, but it seems that it removes a specific file across the commit history. I want to remove just the key (or that line, for that matter), since I want the *putYaOwnApiKeyBrothar* code available in all my commits. (In case they have to check an older one).

Is that even possible? Is there a simple way? If not, what should I do? Am I being dumb?

like image 526
ovalb Avatar asked Dec 15 '22 02:12

ovalb


2 Answers

git filter-branch is the way to go. It has various filters and you can remove files from the history, but you can also modify the files as you like. In your case you want to use the --tree-filter option with a command that replaces the String in your file. Something like git filter-branch --tree-filter "sed -i 's/243248324293938243/putYaOwnApiKeyBrothar/' your/file/here" --tag-name-filter cat --all

(if you are on macOS (or any *BSD) add '' after sed -i)

like image 155
Vampire Avatar answered Mar 16 '23 00:03

Vampire


git filter-branch worked for me:

 git filter-branch --tree-filter "sed -i "" 's/ENTER_API_KEY_TO_REMOVE/STRING_TO_REPLACE_THE_KEY/' filepath"

The file path should include the file name e.g /src/main/Application.java where the key was stored previously. When you try to push these changes to GitHub, they might be rejected, in which case use:

git push --force
like image 29
Enock Lubowa Avatar answered Mar 16 '23 00:03

Enock Lubowa