Sub topic 14
What to Do When a Key Leaks
This chapter assumes you know how to use Git (commit, push, .gitignore), you have read earlier chapters on environment variables and .env files, and you can read short Python snippets. It covers the response to a leaked LLM API key: the order of actions, what each action does, and what cleanup is still needed afterward.
Why Speed Matters
A leaked LLM key is usable by anyone who finds it. Automated scrapers watch public repositories and paste sites, and they test new keys within minutes. The usual abuse is running many requests on your account. You then pay for that usage, and the provider may rate-limit or suspend your account.
Treat every suspected leak as real until you have shown otherwise. Checking whether anyone actually used the key comes after you have stopped the key from working.
The Response Order
The steps below run from most urgent to least urgent.
Step 1: Revoke the Key
Open your provider console and delete or disable the exposed key. Revocation makes the key stop working on the provider's side, no matter who has a copy.
If you cannot tell which key leaked, look at the first and last few characters. Consoles usually show a partial key, so you can match it. If you still cannot tell, revoke every key that could be involved.
Revoking breaks anything that uses the key. Expect an outage in your own application until the new key is deployed. This is normal, and it is better than leaving the old key active.
If your provider supports a short overlap, you can create the new key first and revoke the old one right after. Do this only when the swap takes minutes. If the key is known to be public, revoke immediately and accept the downtime.
Step 2: Create and Deploy a Replacement
Create a new key in the console and store it at the moment it is shown. Use a different name or label, such as the date, so you can tell it from the old one.
Then update every place that held the old key:
- Your local
.envfile or shell environment. - CI secrets, such as the GitHub Actions repository secret.
- Deployment environment variables on your server or hosting platform.
- Any teammate machines or scheduled jobs that use the same key.
Missing one location is a common error. The symptom is a 401 or similar authentication status from one service while the others work. Search your notes and deployment settings for every consumer of the key.
Step 3: Review Usage
Look at the provider's usage and billing pages for the time range between the leak and the revocation. You are looking for:
- Requests you did not make, especially from unfamiliar times of day.
- A sudden rise in token counts or spend.
- Use of models your application never calls.
If you find unauthorized use, contact the provider's support. Many providers review charges caused by a leaked key, but this is not guaranteed. Keep screenshots and timestamps. Spend limits set earlier, as covered in the chapter on scoping, cap how much damage was possible.
Step 4: Remove the Key From Where It Leaked
Now clean up. This step reduces further exposure, such as confused teammates or future scanning. It does not protect you from anyone who already copied the key.
The cleanup depends on where the key appeared:
| Where it leaked | Cleanup |
|---|---|
| Committed to a local repository, not pushed | Remove it from history before pushing, then still revoke it |
| Pushed to a repository | Remove it from the current files and history, and treat it as public |
| Application logs | Delete or redact the log lines and fix the logging code |
| Chat message or ticket | Delete the message if the tool allows it |
| Screenshot or screen recording | Delete the file or post and replace it with a redacted version |
| Client-side code (browser or mobile app) | Remove the key from the code, ship a fixed version, and move the call to your backend |
Cleaning a Committed Key
Suppose .env was committed by mistake. First stop tracking it while keeping your local copy:
git rm --cached .env
echo ".env" >> .gitignore
git check-ignore -v .env
git commit -m "Stop tracking .env"This removes the file from future commits. The key still exists in every earlier commit, so anyone who clones the repository can read it from history.
To rewrite history, use a dedicated tool. git filter-repo is the one the Git project recommends over the older git filter-branch. It is installed separately, for example with pip install git-filter-repo. Run it on a fresh clone, because it rewrites the repository.
git filter-repo --invert-paths --path .envAfter rewriting, you must force-push the rewritten history. Force-pushing replaces the remote branches, so coordinate with your team first. Everyone else must re-clone or reset their copies, otherwise old commits can come back.
Rewriting history has limits:
- Forks and clones made before the rewrite keep the old commits.
- Hosting platforms may cache old commits and pull request references for a time. Contact the platform's support if you need those purged.
- If the repository was public at any point, assume the key was copied.
This is why rewriting history is a cleanup step and never a replacement for revocation.
Verifying the New Setup
After you deploy the new key, confirm that it works without printing it. The check below prints only the status code, in the same style as earlier chapters. The URL is a placeholder, so use your provider's documented endpoint.
import os
import requests
api_key = os.environ["LLM_API_KEY"]
response = requests.post(
"https://api.example.com/v1/chat", # placeholder URL: use your provider's documented endpoint
headers={"Authorization": f"Bearer {api_key}"},
json={"prompt": "Say hello"},
timeout=30,
)
print(response.status_code)A 200 means the new key works. A 401 means the key is wrong or has not reached this environment. Also confirm that the old key now fails the same way. If it still returns 200, revocation did not take effect, and you should check the console again.
Common Errors During Response
- Deleting the repository instead of revoking. A deleted repository can still exist as forks, clones, and caches. Revoke the key.
- Committing the fix and stopping. A new commit that removes the key leaves it in history.
- Pasting the new key into the same unsafe place. If the leak came from a chat message or a hard-coded string, do not repeat the habit. Use the environment variable or CI secret route.
- Revoking but not redeploying. Production keeps failing with authentication errors until the new key reaches every environment.
- Skipping the usage review. Without it, you will not learn whether the key was abused or how much it cost.
After the Incident
Once the key is replaced and usage is reviewed, find out how the leak happened. The earlier chapters cover the most common paths: a committed .env, a key in client code, a key in logs, or a shared screenshot. Pick the control that would have stopped it:
- A
.gitignoreentry for secret files. - A pre-commit hook or secret scanner that blocks commits containing keys.
- A spend limit that caps loss.
- A separate key per environment, so one leak does not force changes everywhere.
Write down what happened, with times: when the key was exposed, when you noticed, when you revoked it, and what usage you saw. A short record helps the team and supports any billing request to the provider.
Exercise
You accidentally pushed a commit containing your LLM API key to a public repository 20 minutes ago. List the first three actions you take, in order, and explain why rewriting Git history is not one of them.
Show answer
First, revoke the key in the provider console. Second, create a new key and deploy it to every place that used the old one (local environment, CI secrets, production). Third, review usage and billing for the exposure window. Rewriting history is not first because the repository was public, so the key may already be copied by scrapers. Only revocation makes a copied key useless. History cleanup is done later to reduce further exposure.
Exercise
After revoking and replacing a key, your web app works but a nightly job fails with a 401 status. What is the most likely cause, and how do you confirm the fix?
Show answer
The nightly job still uses the old, revoked key, for example from its own environment variable or scheduler configuration. Update the key in that job's configuration, then run it once and check that the status code is 200 without printing the key.