Corporate Software
API Key Leak: What to Do If You Accidentally Push One to GitHub

Short answer
The moment you notice an API key or .env file sitting in a GitHub repository, your first move is not deleting the file. It is revoking that key at the provider and issuing a fresh one immediately. Git keeps every commit retrievable forever.
An api key leak stays readable long after the file disappears from the latest snapshot, so the only real fix is making the old key worthless, then cleaning the history with a tool like git-filter-repo.
Why does an api key leak matter so much?
Git is a version control system built around keeping every commit permanently retrievable. That design makes removing something you added by mistake far harder than it sounds. Once a key gets committed, a later commit that deletes the file leaves the earlier version untouched in history. Anyone with git log access, or just a link to that old commit, can still read it. On public repositories the clock runs faster still. Automated scanners crawl new commits within minutes, searching for known key prefixes used by services like AWS, Stripe, and OpenAI.
Working in a private repository lowers the odds but never eliminates them. Every collaborator, connected CI service, and third-party integration with repo access can read the key, and so can any fork taken before access changed. Once a teammate leaves the project or permissions shift, tracking exactly who can still reach that key becomes genuinely hard to verify. That is why a private repository never removes the obligation to revoke a leaked credential.
The most common ways an api key leak happens
| Scenario | Typical cause | First action |
|---|---|---|
.env committed before .gitignore is set up |
Secrets file forgotten during project setup | Revoke the keys, then purge .env from history |
| A placeholder in sample code gets swapped for a real key | A real key is copied in for a quick test | Treat the test key exactly like a production one |
| A key is hardcoded directly into a CI/CD script | A quick fix is used instead of a secrets manager | Remove it, move it into the CI provider’s secret store |
| A personal config file rides along in an open-source contribution | git add . sweeps up a local settings file in a fork |
Withdraw the pull request, rotate the key |
| A screenshot or log output pasted into an issue | Environment variables show up during debugging | Edit the issue, revoke the key anyway |
Every row in that table shares the same root cause: the key reaches the repository, or some public-facing platform, as plain text. Whatever channel it travelled through, the correct first step stays identical: treat the key as compromised before you investigate, not after. Investigating first and deciding later wastes the exact minutes that matter most.
What steps should you take once you spot an api key leak?
1. Revoke the key and issue a new one immediately
Opening the provider’s API keys or credentials dashboard and disabling the leaked key is the first and most urgent step, well before touching the git history itself. Generating a replacement and updating your application takes only a few minutes, and that small cost closes the window during which the old key could be misused. Most major providers also show when and from which IP address a key was last used, which helps you judge whether it was actually picked up by someone else.
2. Check usage logs and billing
Before or right after rotating the key, scanning the provider’s recent request logs lets you catch misuse early rather than discovering it on next month’s invoice. An unusual spike in request volume, calls arriving from an unexpected region, or a sudden jump in billed usage all signal that the key was put to use after it leaked. If you see any of that, notify the provider and loop in your security contact if one exists.
3. Clean the key out of git history
Writing a commit that deletes the file does not remove the key from earlier commits, so you need to rewrite history itself. GitHub’s own documentation recommends git-filter-repo for this exact job: the tool strips a given file or pattern out of every commit permanently. The repository then needs a force-push, and every teammate has to replace their local clone with the rewritten history, because the rewrite changes the hash of every commit that follows the leaked one.
4. Tell the team before force-pushing
Schedule the history rewrite for a moment when nobody else is about to push, otherwise someone’s commit built on the old history collides with the rewritten one and creates a confusing mess. A short heads-up message, stating clearly that everyone needs to re-clone or hard-reset their local branch once the rewrite lands, keeps the whole process from turning into a cleanup job on its own.
Why doesn’t deleting the file fix an api key leak?
Git’s entire design philosophy revolves around never silently losing a commit, a property that is a genuine strength until you are trying to erase a secret. Deleting a file in a new commit only changes what the latest snapshot shows; it does nothing to the commits that came before it. Anyone who checks out an older commit hash, or simply opens a direct link to it, can still read the removed content in full. GitHub’s own search index and several third-party code-scanning services also crawl historical commits, so a key can remain reachable through another channel even after it vanishes from the file browser.
How do you prevent an api key leak in a CI/CD pipeline?
Automation scripts tend to hardcode credentials directly into configuration for the sake of speed, and that habit is one of the most common sources of an api key leak inside larger engineering teams; most api key leak incidents in CI/CD trace back to exactly this shortcut. Secret stores built into GitHub Actions, GitLab CI, and similar platforms hold keys encrypted and inject them only as environment variables while a job runs, so the key itself never touches a tracked file. Pre-commit hooks add a second layer on top of that: a tool like git-secrets scans a commit for known key patterns before it completes and blocks it outright, warning the developer on the spot.
GitHub’s secret scanning closes most of the remaining gap. It is enabled by default on public repositories and checks new commits against known formats from major providers. A match triggers an alert to both the repository owner and usually the provider itself. Private repositories can turn on the equivalent feature through GitHub Advanced Security, which adds a meaningful extra layer for enterprise projects. Even so, treat it as one layer rather than a sole line of defense, since custom formats and lesser-known provider keys are not always recognized.
Reducing this risk for good across your team
The most durable fix is keeping keys entirely separate from source code in the first place. Adding .env to .gitignore the moment a project is created, before the very first commit, means there is nothing left to purge from history later. Keeping an .env.example file with placeholder values lets teammates see exactly which variables the project needs without ever exposing a real credential.
Setting a rotation schedule limits the damage from an api key leak even when nobody notices it right away; rotating keys every few months quietly erases the risk from an old, forgotten exposure. Adding a review step that checks whether .env files or key-shaped strings appear among the changed files turns this habit into something the whole team enforces, not just one careful developer. If you want this kind of security discipline built into your software projects from day one, our custom software service designs code review workflows and CI/CD security checks around your team’s actual setup.
Common mistakes
Deleting the file and calling it done, without rotating the key first, is the single most common and most dangerous mistake, because the old key stays valid for as long as it sits readable in history. Force-pushing a rewritten history without warning the team creates a separate problem, since every other developer’s local clone now conflicts with the new one and turns a simple fix into a confusing recovery exercise. Another frequent misjudgment is assuming a private repository makes an api key leak harmless, when in reality every collaborator and every connected integration remains a potential exposure point. Skipping the usage-log check after rotating the key and cleaning history is the last common gap, and it costs you the only real chance to learn whether the api key leak was actually exploited.
Checklist
Work through these questions in order the moment you spot a leak. Has the key actually been revoked and replaced? Do the provider’s usage logs show anything unusual? Has the git history been cleaned with git-filter-repo? Has every teammate re-cloned the repository after the force-push landed? Once you can answer yes to all four, the technical side of an api key leak is closed. What remains is locking in the .gitignore habit and a proper secrets workflow, so the same mistake does not repeat on the next project.
Next step
An api key leak is fully recoverable within minutes when you act in the right order, and the real failure is treating a deleted file as a closed case. If you want secrets management, CI/CD security, and code review discipline built properly into your engineering process, our group company Web Tasarım Ofisi provides technical infrastructure consulting for exactly this kind of work.
Explore our custom software service to set up secure development and deployment pipelines end to end, or get in touch with us to talk through your setup. If a tangled git history is giving you trouble elsewhere, our guide to resolving a git merge conflict and our walkthrough of the git permission denied publickey error cover two other situations developers run into often.
Sources
- GitHub Docs, Removing sensitive data from a repository, the official recommended steps for purging a leaked secret from history
Frequently asked questions
Is deleting the file enough after an API key leak?
No. Deleting the file in a new commit does not remove it from git history; the key still sits in earlier commits, forks, and some caches. The only real fix is revoking the key at the provider and issuing a new one.
Does a private repository reduce the risk of an api key leak?
It reduces it but does not remove it. Every collaborator, connected integration, and any fork taken before the repo went private can still read the key. A private repository never removes the need to revoke it.
Does rewriting git history affect other developers on the project?
Yes. Rewriting history changes every commit hash after the leaked file, so teammates have to replace their local clone with the new history. Coordinate the timing with the team before force-pushing.
Does GitHub's secret scanning automatically stop an api key leak?
Secret scanning is enabled by default on public repositories and flags recognized key formats, alerting both you and often the provider. Detection is not instant and custom patterns are not always recognized, so it should never be your only safeguard.
How do you know if a leaked API key was actually misused?
Check the usage or billing logs on the provider that issued the key. Unexpected calls, requests from unfamiliar locations, or a sudden spike in cost all point to the key having been picked up and used.