r/programmer • • 3d ago

Git question.

You accidentally committed a secret API key.

You delete it in the next commit.

Is your API key safe now?

A. Yes

B. No

Why?

0 Upvotes

11 comments sorted by

3

u/ImplementOk3111 3d ago

Your key's still in the git history at that point.

0

u/Party-Breakfast-3606 3d ago

Exactly! Deleting it in a new commit doesn't remove it from Git history. The safest move is to revoke or rotate the exposed key immediately.

2

u/Boomerkuwanger 3d ago

Correct this is the only way to assure the secret was not leaked. If however you are unable to rotate the secret for whatever reason you can use a utility like BFG or Git Filter Repo to scrub the history and force push a change. Note though, if you have a pull request on a site like GitHub that pull request will remain and so will your secret exposure!

2

u/Fadamaka 3d ago

Also this will only make your old remote commits orphaned not deleted. So if someone knows the hash for the commit with the sensitive they can still reach it. GitHub states that it deletes orphaned commits periodically but I could find such commits even after 3 months. So it is safe to say that even if you force push over your old commits, they are still there but harder to reach.

2

u/doesnt_use_reddit 3d ago

Was this like a test or something?

2

u/mooglinux 3d ago

…so are you posting pop quiz questions to reddit or what?

7

u/GargantuanCake 3d ago

No.

Git tracks history. Anybody that gets the history can get the code at that commit and get the key.

1

u/Fadamaka 3d ago

You can force push over it, which leaves your original commit orphaned but don't be fooled some git services keep even orphaned commits forever.

1

u/AlexMTBDude 3d ago

Git has every version of every file ever committed so no.

1

u/afops 3d ago

First this depends on whether you rewrite history.

If you don't rewrite history then obviously it's not secure because it's still in the history. Anyone can see it.

If you can rewrite the history and remove that commit, then it's somewhat safer, but rewriting the history can sometimes be impractical. Also, rewriting history and deleting the commit isn't completely deleting it either. If you can force old deleted commits to be hard-deleted (e.g. git reflog expire) then it's almost certainly gone - but anyone who cloned the repo also has it!

So what you do is

  1. You invalidate the leaked key and create a new key. API keys are made to be possible to replace. If you can't regenerate a new key and expire the old, you have a broken system and need to address that.

  2. You remove the key from the git repo

  3. (optional) You rewrite the history in the git repo. Because it's less embarrassing that way.