Leaked an API key on GitHub? How to fix it

2026-11-10来源 dev.to GitHubEnglish

Revoke the key at the provider before you touch git. Deleting the file, deleting the commit, or making the repository private does not un-leak a key that has already been pushed. GitHub's guide to removing sensitive data from a repository says those commits can still be read in any clone or fork, by SHA-1 in cached views on GitHub, and through any pull request that references them. Secret scanning for partners also reads public repositories and notifies the provider. Treat the string as copied, and make it stop authenticating.

The rest is cleanup: where to revoke an OpenAI, Claude, or Gemini key, where else to look, how to rewrite history, and the .gitignore that should have blocked the file. Prevention (one key per tool, expiry, spend caps, server-only calls) is in Secure your OpenAI API key. git-filter-repo and GitHub both say a revoked secret may no longer need a rewrite to stop abuse. Cleaning the history is still not the fix.

Revoke and rotate the key

A new key does not turn the old one off. If charges are already running, revoke first and accept a short outage. If you cannot see the key, you are in the wrong project or workspace, or you lack permission.

OpenAI. Where do I find my OpenAI API Key? says keys are managed on the API key page in the OpenAI Platform. Delete with the trash can icon. A deleted key cannot be used. Best practices for API key safety says to rotate immediately from that page if you believe a key leaked, then update production, and to read the Usage page. Set a monthly spend limit with hard enforcement. OpenAI's spend limits guide says alerts do not stop traffic, enforcement is not instantaneous, and spend can slightly exceed the cap.

Anthropic (Claude). API key best practices says to revoke immediately: Claude Console, platform.claude.com/settings/keys, the three-dot menu, Delete API key. The workspaces guide also lists Disable API key. Delete cannot be undone. Disable can be turned back on. Check Usage and Logs. Spend limits are on Workspaces (open the workspace, then Spend limits), not on the Default Workspace. On Billing, auto-reload limits are the safeguard that article names for a leaked key.

Gemini. The checklist in Using Gemini API keys is: create a replacement in Google AI Studio or the Cloud console, deploy it, disable or delete the old key in the Cloud console once the new key works, then audit billing and API usage. That order avoids downtime. If the key is already public, do not leave it enabled while you edit git. The same guide says auth keys, the default for AI Studio keys since 28 May 2026, have fast-acting leaked key enforcement for keys Google detects. Disable the key yourself anyway.

Project spend caps live in AI Studio. Billing calls them experimental: about a 10 minute lag, and batch jobs and agent sessions can overshoot. Prepay accounts can set a monthly auto-charge limit on AI Studio Billing.

Find every place it leaked

  • Branches and tags. git log -S'PASTE_THE_LEAKED_KEY_HERE' --all finds commits that add or remove the string (-S is documented in git-log).
  • Forks. Setting repository visibility says that if you make the repo private, current forks stay public and are detached. Ask those owners to delete or clean them. GitHub will not give you their contacts.
  • Issues, pull requests, discussions, wikis, gists. Partner scanning reads titles, descriptions, and comments. A comment is not a commit, so filter-repo will not touch it, and GitHub says dereferencing a pull request does not wipe a secret quoted in the conversation. Edit the text.
  • CI logs and the host. Delete Actions runs that printed the environment, and replace any Actions secret that still holds the old value. Update the host's env, including previews, and redeploy. On Vercel that store is environment variables.
gitleaks git -v --log-opts="--all" trufflehog git https://github.com/OWNER/REPO --results=verified trufflehog github --repo=https://github.com/OWNER/REPO --issue-comments --pr-comments 

Gitleaks scans with git log -p. --log-opts is how the README passes --all when every branch matters. TruffleHog's README uses trufflehog git for commits and github --repo with --issue-comments --pr-comments for issues and pull requests. Known patterns also show as alerts under the repository Security and quality tab.

Remove it from git history

GitHub recommends git-filter-repo 2.47 or newer, for --sensitive-data-removal. Use a fresh clone. The tool refuses a repo that does not look like one, and it deletes origin so you cannot push by accident. Pass the path from the repo root, plus every old path if the file was renamed. Renames are not followed.

git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY.git cd YOUR-REPOSITORY git-filter-repo --sensitive-data-removal --invert-paths --path .env 

--invert-paths keeps everything except those paths. If the secret is a string inside other files, put rules outside the repo. The manual replaces a line that has no ==> with ***REMOVED***. literal: matches the key as text, not as a regex.

printf '%s\n' 'literal:PASTE_THE_LEAKED_KEY_HERE==>***REMOVED***' > ../replacements.txt git-filter-repo --sensitive-data-removal --replace-text ../replacements.txt 

Run a second pass only if you need both. Then confirm, put origin back, and force-push every branch and tag. GitHub's guide uses --force --mirror. Pushes of refs/pull/ fail because those refs are read-only. Other failures are usually branch protection: turn it off, push, turn it back on.

git log -S'PASTE_THE_LEAKED_KEY_HERE' --all git remote add origin https://github.com/YOUR-USERNAME/YOUR-REPOSITORY.git git push --force --mirror origin 

Tell collaborators to delete their clones and clone again. The filter-repo manual calls re-clone the reliable path. git pull then git push from an old clone puts the secret back. Do not have them re-run filter-repo: the same command can hash commits differently.

GitHub can still serve the old commits by SHA-1, and pull request refs can still point at them. Contact Support with the owner/repository, the affected pull request count, and the "First Changed Commit(s)" filter-repo prints:

grep -c '^refs/pull/.*/head$' .git/filter-repo/changed-refs 

Support only helps when they decide rotation cannot mitigate the risk, and they will not remove non-sensitive data. For a key you already revoked, rotation is that mitigation. Ask if a cached view still shows the secret, and edit comments yourself either way.

BFG Repo-Cleaner (docs) is the alternative. It does not change the latest commit on HEAD unless you pass --no-blob-protection, so clean that commit first. --delete-files matches the file name, not a directory. On a mirror clone, git push updates every remote ref.

git clone --mirror https://github.com/YOUR-USERNAME/YOUR-REPOSITORY.git java -jar bfg.jar --delete-files .env YOUR-REPOSITORY.git cd YOUR-REPOSITORY.git git reflog expire --expire=now --all && git gc --prune=now --aggressive git push 

For a string, that site uses bfg --replace-text passwords.txt repo.git.

Stop the next leak

Next.js loads .env, .env.local, .env.development, .env.production, and .env*.local, and says you almost never want them committed. Commit .env.example with empty values.

.env .env.* !.env.example 

.env.* matches .env.local and .env.development.local. !.env.example keeps the example committable. If .env is already tracked, gitignore does nothing until you untrack it. git rm --cached drops the index entry and leaves the file on disk. History is unchanged.

git rm --cached .env 

Push protection for users is on by default for public repositories and can be bypassed. Also enable secret scanning and repository push protection under Settings, then Advanced Security (docs). On the pattern table (10 November 2026), OpenAI and Anthropic API keys have push protection. The row named Google Gemini API Key does not.

Gitleaks can block the commit. This file is the README example as of 10 November 2026. Run pre-commit autoupdate, then pre-commit install. Anthropic's key guide names Gitleaks and a CI scan too.

repos: - repo: https://github.com/gitleaks/gitleaks rev: v8.24.2 hooks: - id: gitleaks 

Keep the live key on the server. Next.js inlines NEXT_PUBLIC_ into the browser bundle. Vite exposes VITE_ to client code and says not to use that prefix for secrets. Either prefix publishes a model key even when git is clean. The server-only split is in the Next.js + Supabase pre-launch security checklist.

Shipping a product that calls OpenAI, Claude, or Gemini and want the keys, caps, and server boundary set before launch?

What actually fixes the leak

Action Fixes the leak? Why
Delete the file in a new commit No Older commits still hold the file.
Delete or revert the commit No The original commit stays reachable. GitHub's data-leak guide says git revert leaves it in history.
Make the repository private No Clones already exist. Public forks stay public. The key works until the provider rejects it.
Rewrite history (filter-repo or BFG) No Cleanup of refs you can force-push. Forks, old clones, and some GitHub caches can keep the string.
Revoke or rotate the key Yes The provider rejects the old string. Update every deploy still sending it, including preview env vars.

FAQ

Is deleting the commit enough after an API key hits GitHub?

No. Deleting the file in a later commit leaves the old blob in history. GitHub's data-leak guide says git revert is not a valid undo, because the original commit stays. Revoke at the provider. A history rewrite does not erase forks, other clones, or every cached view.

Does making the GitHub repo private fix a leaked API key?

No. The key works until the provider revokes it. Setting repository visibility says current forks stay public and are detached. Existing clones still have the string. The removal guide says cached views and pull request refs survive a force-push.

Will OpenAI, Anthropic, or Google detect a leaked API key automatically?

Partner scanning notifies the provider. You cannot turn that off on a public repo. The provider validates the string and decides whether to revoke, replace, or contact you.

From GitHub's pattern table on 10 November 2026:

Secret (GitHub's name) Partner (provider is notified) Push protection Validity check
OpenAI API Key Yes Yes Yes
Anthropic API Key Yes Yes Yes
Google API Key Yes No Yes
GCP API Key Bound to a Service Account Yes Yes No
Google Gemini API Key No No No

Anthropic's help center says they automatically deactivate a Claude key GitHub reports from a public repo, and they email you. OpenAI's key-safety article tells you to rotate it yourself. It does not say OpenAI revokes leaked keys for you. Google's API key guide says auth keys (default in AI Studio since 28 May 2026) stop usage of leaked keys their systems detect. The "Google Gemini API Key" row is not a partner pattern, so do not assume GitHub sends that pattern to Google. Revoke the key yourself either way.

How do I remove a .env file from git history?

In a fresh clone: git-filter-repo --sensitive-data-removal --invert-paths --path .env (one --path per old name), then git log -S, git remote add origin, and git push --force --mirror origin. git rm --cached .env only untracks the file from the next commit. BFG's --delete-files .env on a mirror clone works after HEAD is clean, because BFG leaves that latest commit alone unless you pass --no-blob-protection.

How fast are leaked API keys abused?

Treat the key as compromised the moment it is pushed to a public repository. Anyone can clone it, partner scanning reads public repositories, and copies survive in forks and caches. Revoke the key before you clean up git.

About the author

I'm Joan Comadran, an industrial engineer turned AI engineer and full-stack developer in Barcelona. I build Next.js on Vercel (this site). The commands and UI paths in this post were checked against the official GitHub, git-filter-repo, OpenAI, Anthropic and Google docs on 10 November 2026. For that setup on a product, that's what I do.

Originally published on joancomadran.dev. I'm Joan, an AI engineer in Barcelona — work with me.

原文:https://www.a8q9.cn/en/article/leaked-an-api-key-on-github-how-to-fix-it-9e2404.html

相关文章