OpenAI API Key Leaked? 6 Steps from Revoking to Git History Cleanup

Blog / Developer tools

OpenAI API Key Leaked? 6 Steps from Revoking to Git History Cleanup

If your OpenAI API key leaks, the first thing to do is revoke it in the OpenAI dashboard, not clean up the repository. Once a key has been public, assume someone already has it; deleting the commit does not make it safe again. After revoking, check usage, create a new key, clean up git history, and finally put preventive measures in place.

The steps below are in processing order. Exact menu locations and field names depend on OpenAI's official documentation and the current dashboard, so this article does not give menu paths.

In what order should you handle a leak?

StepWhat to doWhy this order
1Revoke the leaked keyStop the loss first; everything else can wait
2Create a new key and update everywhere it is actually usedAvoid a long outage after revoking
3Check usage details for abnormal callsDetermine whether the key was abused
4Set a budget and spending limitCap the damage of the next incident
5Clean up code and git historyStop the same string from being scraped again
6Add prevention: .env, scanning, per-project keysKeep it from happening again

One caveat: there will be a short service interruption between revoking the old key and deploying the new one. If the production service is critical, create the new key and prepare the deployment before you revoke, but keep the gap as short as possible and do not leave it until tomorrow.

Step 1: How do you revoke the key?

Log in to OpenAI's developer dashboard, open the API Keys management page, find the leaked key, and choose delete or revoke. If you are not sure which key it is, compare the creation time, name, and the last few characters. If nothing matches, revoke all related keys in the same project.

Some platforms also scan public repositories for secrets and notify you or disable the key; check the official documentation for specifics. Treat this only as a backstop, not as your process: you may not get a notification, and the key may already have been scraped before it is disabled.

Step 2: Where should the new key go?

After creating a new key, put it only in environment variables or a secrets manager. Do not write it into code, a README, screenshots, or chat logs. There is usually more than one place to update, so use this checklist:

  • Your local .env file and each developer's own environment variables
  • Server or container environment variables, and CI/CD secrets
  • Configuration in cloud functions, scheduled jobs, and monitoring scripts
  • Third-party tools where you entered the key, such as editor plugins and desktop clients

If you miss one, the symptom is "a service suddenly starts returning 401." When that happens, go back to this checklist.

Step 3: How do you tell whether the key was abused?

Open the Usage page in the OpenAI dashboard and look at cost and request volume by date. Watch for three kinds of anomalies:

  1. Usage spikes after the time of the leak.
  2. Models appear that your application has never used.
  3. Large numbers of requests at night, on weekends, or at other times when your service normally has no traffic.

If your service logs every call, compare those logs against the platform's usage numbers. This site has a separate article on tracking usage yourself: How to track API usage: calculate daily spend from response headers and logs. If the platform's numbers do not match your own logs, first work out whether the cause is token counting differences, retries, or abuse; see Why is my API bill wrong? Token counting, duplicate charges, and line-by-line verification.

If you confirm abuse and charges were incurred, open a ticket with OpenAI support, attaching the timeline, how the key leaked, and usage screenshots. Whether charges are waived is OpenAI's decision; do not assume the outcome.

Step 4: How do you limit the damage next time?

In the dashboard, set budget alerts and a spending limit for the account or project. Whether it is a "soft alert" or a "hard cap," and whether it applies monthly or per project, depends on the current official documentation. The rule of thumb: set the limit slightly above normal monthly usage. It is better to hit it occasionally and raise it by hand than to set none.

Step 5: How do you remove the key from git history?

First, a clarification: the key is already revoked, so cleaning history is about stopping scanners from raising repeated alerts and keeping others from assuming the key is still valid. It is not what keeps you safe.

If the key appears only in the latest commit and has not been pushed, edit the file and run git commit --amend. If it has been pushed, or is in an earlier commit, you need to rewrite history. git-filter-repo (installed separately) is the recommended tool:

# 1. Make a full backup first
git clone --mirror <repo-url> repo-backup.git

# 2. Prepare a replacements file replacements.txt, one rule per line
#    sk-xxxxxxxx==>REMOVED_KEY

# 3. Rewrite history in a fresh working clone (filter-repo removes origin, so add it back)
git filter-repo --replace-text replacements.txt
git remote add origin <repo-url>

# 4. Force-push all branches and tags (requires permission; notify collaborators beforehand)
git push --force --all
git push --force --tags

A few things to note:

  • Rewriting history changes commit hashes. Collaborators need to re-clone or rebase as described in the official documentation.
  • Existing forks on GitHub, cached commit pages, and Pull Request references do not disappear when you force-push. For a complete cleanup, contact GitHub support following their official documentation; the exact process is defined there.
  • You can also use BFG Repo-Cleaner, which works on the same idea.

How do you prevent another leak?

Use .env and add it to the ignore list

# .gitignore
.env
.env.*
!.env.example

Commit only .env.example to the repository, with variable names and no real values.

Scan for secrets before commit and in CI

You can scan locally with open-source tools such as gitleaks or trufflehog, and wire them into a pre-commit hook or CI. For example:

gitleaks detect --source . --log-opts="--all"

If your repository is hosted on GitHub, also check whether GitHub's secret scanning and push protection apply to your repository type and plan, according to the official documentation.

One key per project

Do not use one key for everything. Create separate keys per project and per environment (development, testing, production), and name each one for its purpose. When something goes wrong you only revoke one key and other services are unaffected, and usage is easier to split out. For teams, see How teams manage API keys: one key per person, budget splits, and rotation.

Never put keys in the frontend

Code running in a browser or mobile app is visible to users. When you need to call a model, have your own backend forward the request, and keep the key on the server only.

Rotate regularly

Even without a leak, you can rotate keys on a fixed schedule (for example, quarterly) and add it to your operations checklist.

What if you are unsure which account and billing to use?

Many leaks happen in "just trying it out" situations: you paste a key into some tool and forget about it. First understand that a ChatGPT subscription and the API are two separate accounts with separate billing; see ChatGPT Plus vs. the OpenAI API: separate accounts, billing, and quotas. For how to enter an endpoint URL and key in your tools, see Custom API endpoints for Claude Code, Codex, and OpenCode.

A disclosure: AGI Plan is a commercial partner of cdnping. It is a multi-provider LLM aggregation gateway, billed by monthly subscription and settled in RMB (Chinese yuan). The operator states it is not an officially authorized channel. Available models and regions are listed on the AGI Plan models page; judge it against your own compliance requirements. For an introduction, see agiplan.dev/startup. Whether you use an official key or a gateway key, the principles above apply: separate keys per project, set limits, and keep them out of the repository.

If requests fail during the cleanup, first work out whether the problem is a mistake in your key swap or a server-side issue; compare against the OpenAI API status page.

Post-incident checklist

  • The leaked key has been revoked in the dashboard
  • The new key is updated everywhere it is used, and the service is healthy
  • Usage details have been checked; anomalies are recorded and a ticket filed if needed
  • Budget alerts and a spending limit are set
  • The old key has been removed from code and git history
  • .env is ignored, and secret scanning runs on commit or in CI
  • Each project uses its own key

Next step: open your dashboard right now and look at how many keys you have and when each was last used. Disable any key whose purpose you cannot explain, and restore it only once someone claims it.

Related articles

Keep reading