AI API Key Leaked? A Step-by-Step Response, Rotation and Prevention Guide for Claude Code, Codex and CI (2026)
Summary: If an AI API key has appeared anywhere other people or bots can see it (a public repo, a CI log, a screenshot, a chat message), treat it as compromised. Contain it first by disabling or replacing the key, then move every tool to the new key, review usage, scrub the old value from Git history, and fix the cause so it can't happen again. This guide walks through that order as of 2026-11-25, with commands for git filter-repo, GitHub secret scanning, CI secrets, and safer key storage in Claude Code (apiKeyHelper) and Codex CLI. QCode is an independent third-party API service and is not affiliated with Anthropic, OpenAI or any other model vendor.
Updated 2026-11-26
Key facts
- Deleting the commit does not un-leak a key. Old commits, forks, clones, caches and CI logs keep the value. Replacing the key is the only fix that works; history cleanup comes after.
- Order matters: contain (disable or replace) → update tools → review usage → clean history → prevent. Doing cleanup first leaves the key live while you work.
- QCode keys start with
cr_. On a personal plan, check the console for a reset or disable action and contact support if your account does not offer one. On the Team plan, each member has a sub-key, so an exposed key does not force the whole team to rotate. - Generic scanners won't recognise every key format. GitHub's built-in patterns cover its partner providers; a
cr_key may not match any of them, so use your own pattern (gitleaks, or a GitHub custom pattern on plans that support it). - Claude Code can fetch the key from your OS keychain through
apiKeyHelper, so the key never sits in a shell profile orsettings.json.
How do you know a key has leaked?
Sometimes you see the mistake yourself: you pushed .env, pasted a config into an issue, or shared your screen with the terminal open. Other times the first sign is in your usage. Watch for:
- Quota running out early. On QCode's dashboard, the daily cost limit is used up long before your normal working day ends, or "Today's Model Calls" lists far more requests than you made.
- Models you never use. The per-model breakdown shows calls to a model you don't work with, or traffic at hours when you were offline.
- Rate-limit errors while you're idle. If requests fail with
429while none of your tools are running, something else may be using your key. - A scanner alert. GitHub, GitLab or your own pre-commit tool flags a secret in a push or an existing commit.
If you see any of these, don't wait to prove a leak. Disabling and replacing a key costs a few minutes; an exposed key can keep burning quota until you act.
The first hour: a response checklist
| Step | What to do | Why |
|---|---|---|
| 1. Contain | Disable or replace the exposed key | Stops further use |
| 2. Replace everywhere | Put the new key into every tool, shell and CI secret | Avoids breaking your own work |
| 3. Review usage | Compare dashboard usage with what you actually ran | Tells you the impact |
| 4. Clean the source | Remove the value from Git history, logs and pastes | Limits future exposure |
| 5. Prevent | Add scanning, sub-keys and safer storage | Stops a repeat |
Step 1: Contain the key
Personal plans. In the QCode console, check whether your key has a reset, disable or delete action. If it does, use it. If it does not, contact support through the Contact Us button in the console or by email at hi@qcode.cc and ask how to disable the exposed key and get a replacement. Identify the key by your QCode ID or account email and the last four characters only. Never send the full key, not even to support.
Team plan. Each member has a sub-key, so replace only the exposed one and hand the new key to the person or pipeline that owned it; the rest of the team keeps working. That isolation is the main reason to give every person and pipeline its own sub-key. If the admin console does not show the control you need, contact support.
Other providers. If the leaked value was an Anthropic, OpenAI or other vendor key, revoke it in that vendor's console and create a new one. The same order applies.
Step 2: Replace the key everywhere it lives
Make a list before you start, because a key often lives in more places than you remember:
- Shell profiles (
~/.zshrc,~/.bashrc, PowerShell$PROFILE) exportingANTHROPIC_AUTH_TOKENor another variable - Claude Code: the
envblock in~/.claude/settings.jsonor.claude/settings.local.json - Codex CLI:
~/.codex/auth.json(whenconfig.tomlhasrequires_openai_auth = true) or the variable named byenv_key - IDE extensions and clients (Cursor, Cline, Cherry Studio and so on) that store the key in their own settings
- Config switchers such as CC Switch
- CI/CD secrets, deployment environments,
.envfiles on servers and cloud agents
After replacing, run one small request from each tool to confirm it works, then make sure the old key fails.
Step 3: Review usage
Open the dashboard's usage view for the period since the key could have been exposed. Compare daily cost and per-model calls with your own activity. Write down what you find (dates, models, rough amounts) before you contact support, so the conversation is short. If the key belonged to a team, check whether the same mistake could have exposed other keys.
Step 4: Clean Git history
Once the key is disabled, remove the value from history so it stops spreading. git filter-repo is the tool Git's own documentation recommends over git filter-branch:
# 1. Work on a fresh clone (filter-repo refuses to run on a used clone without --force)
git clone https://github.com/you/your-repo.git your-repo-clean
cd your-repo-clean
# 2. List what to replace: the exact leaked value, and optionally a pattern
cat > ../replacements.txt <<'EOF'
cr_PASTE_THE_EXACT_LEAKED_KEY_HERE==>REDACTED_QCODE_KEY
regex:cr_[A-Za-z0-9_-]+==>REDACTED_QCODE_KEY
EOF
# 3. Rewrite every commit, then delete the replacements file
git filter-repo --replace-text ../replacements.txt
rm ../replacements.txt
# 4. filter-repo removes the origin remote as a safety measure; add it back and force-push
git remote add origin https://github.com/you/your-repo.git
git push --force --all
git push --force --tags
Adjust the regex to your real key format, and check the result with git log -p | grep -n "cr_" before you push. After the force-push:
- Ask every collaborator to re-clone. Merging an old clone brings the secret back.
- Forks and pull-request refs on the hosting service may still hold old commits. For a public repository, assume the key was seen even after cleanup, and contact the host's support if you need cached views removed.
- Delete CI logs, gists, issue comments and wiki pages that contain the value.
Step 5: Prevent the next one
Scan before you push. A pre-commit scanner catches most accidents locally. With gitleaks you can add a rule for QCode keys on top of the built-in ones:
# .gitleaks.toml
[extend]
useDefault = true
[[rules]]
id = "qcode-api-key"
description = "QCode API key (cr_ prefix)"
regex = '''cr_[A-Za-z0-9_-]+'''
Run gitleaks git -v on the repository, or wire it into the pre-commit framework, so every commit is checked.
Use GitHub secret scanning and push protection. Push protection blocks pushes that contain known secret formats. GitHub's default patterns cover its partner providers, so a cr_ key may need a custom pattern. According to GitHub's documentation, custom patterns are available for organization-owned repositories on GitHub Team or Enterprise with GitHub Secret Protection enabled, and after a dry run you can enable push protection for that pattern.
Keep secrets out of files the agent reads. Add .env to .gitignore, commit only a .env.example with placeholders, and add deny rules so Claude Code cannot read secret files:
{
"permissions": {
"deny": ["Read(./.env)", "Read(./.env.*)"]
}
}
Store keys safely in each tool
| Tool | Common storage | Safer option |
|---|---|---|
| Claude Code | export ANTHROPIC_AUTH_TOKEN=... in a shell profile, or the env block in ~/.claude/settings.json |
apiKeyHelper script that reads the OS keychain |
| Codex CLI | ~/.codex/auth.json with requires_openai_auth = true |
env_key = "QCODE_API_KEY" and a variable set from a secret manager (use one method, not both) |
| SDK scripts | Hard-coded strings | Environment variables loaded from a secret manager; .env only on your machine and ignored by Git |
| CI | Variables in the workflow file | The platform's encrypted secrets, one sub-key per pipeline |
Never put a key in a project's shared .claude/settings.json: that file is committed and every clone gets it.
Claude Code: read the key from the keychain with apiKeyHelper
apiKeyHelper is a Claude Code setting that runs a command and uses whatever it prints as the credential. Per Anthropic's Claude Code docs, the value is sent in both the Authorization and x-api-key headers, so it works with a bearer-token gateway such as QCode, and the output is cached for five minutes by default (CLAUDE_CODE_API_KEY_HELPER_TTL_MS changes this, in milliseconds).
On macOS, store the key once in the login keychain (the command prompts for the value, so it never lands in your shell history):
security add-generic-password -a "$USER" -s qcode-api-key -w
Create ~/bin/qcode-key.sh and make it executable with chmod +x:
#!/bin/sh
security find-generic-password -a "$USER" -s qcode-api-key -w
On Linux with a Secret Service keyring, store it with secret-tool store --label="QCode API key" service qcode-api-key and read it with secret-tool lookup service qcode-api-key in the script instead.
Then point Claude Code at the helper in ~/.claude/settings.json:
{
"apiKeyHelper": "~/bin/qcode-key.sh",
"env": {
"ANTHROPIC_BASE_URL": "https://api.qcode.cc/api"
}
}
Remove any ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY export from your shell, because Claude Code ranks both variables above apiKeyHelper. Run /status to confirm the helper is the active credential. The script must print only the key: extra output makes the helper fail. When you rotate, update the keychain entry; Claude Code picks up the new value after the cache expires.
CI: one secret, one sub-key, minimal exposure
In GitHub Actions, store the key as an encrypted repository or environment secret and pass it through env:
env:
ANTHROPIC_BASE_URL: https://api.qcode.cc/api
ANTHROPIC_AUTH_TOKEN: ${{ secrets.QCODE_CI_KEY }}
A few habits matter more than the syntax:
- Give each pipeline its own sub-key with a low daily quota, so a leak is capped and easy to disable.
- Never
echothe secret, runenvorprintenv, or enableset -xin steps that see it. Log masking hides the exact value but not encoded or transformed versions. - Secrets are not passed to workflows triggered from forks. Don't work around that with
pull_request_targetplus a checkout of untrusted code. - Restrict who can edit workflows, since anyone who can change a workflow can read its secrets.
Team rules: one sub-key per person and pipeline
A shared key is the most common reason a small leak turns into a big incident: you can't tell who leaked it, and replacing it breaks everyone at once. QCode's Team plan includes sub-keys per member, so give each person and each CI pipeline or server agent its own:
- One sub-key per person, named after them, and one per CI pipeline or server agent.
- Keep the scope of each key as small as the job allows; check the admin console for the quota and rate-limit controls your plan exposes.
- Replace a person's key on the day they leave, and retire a pipeline's key when the pipeline is retired.
- Keep an eye on usage; with one key per person and pipeline, a spike points straight to the source.
Never paste keys into chats, tickets or screenshots
Most leaks are not hacks. They are copy-paste accidents:
- Chats and AI conversations. Don't paste keys into team chats, forums, support tickets or AI chat windows. If a tool needs a key, put it in the tool's config, not the prompt.
- Screenshots and screen sharing. Close or blur terminals and settings pages first. Settings screens and dashboards often show the full value.
- Recordings and logs. Terminal recordings, debug logs and crash reports capture environment variables. Redact before sharing.
- Agents. Coding agents run with your permissions and can read environment variables and files. Keep deny rules for secret files and approve commands that touch credentials one by one.
Common mistakes
- Cleaning Git history first and disabling the key later.
- Rotating the key but forgetting the copy in CI or on a server, then "fixing" the outage by pasting the old key back.
- Sending the full key to support or a colleague to "prove" which one it is.
- Keeping the key in both
auth.jsonand anenv_keyvariable in Codex; withrequires_openai_auth = true, Codex ignoresenv_key.
FAQ
I deleted the commit straight away. Do I still need to replace the key?
Yes. The value stays in old commits, other clones, forks and possibly caches, and automated scanners watch public repositories continuously. Replace the key first, then clean history.
Can I reset my QCode key myself?
Check the console for a reset or disable action on your key. If your account does not offer one, contact support via the console's Contact Us button or hi@qcode.cc and quote only the last four characters. On the Team plan, each member has a sub-key, so only that key needs replacing.
Will GitHub push protection catch a QCode key?
Not by default: GitHub's built-in patterns cover its partner providers, and a cr_ key may not match them. Add a custom pattern (available on GitHub Team or Enterprise with Secret Protection) or use a local scanner such as gitleaks with a cr_ rule.
Is it safe to keep the key in ~/.claude/settings.json ?
It is better than a project file, but it is still plain text on disk. apiKeyHelper with your OS keychain keeps the key out of config files entirely. Never put it in the shared .claude/settings.json.
How should I store a key for Codex CLI?
Use either ~/.codex/auth.json with requires_openai_auth = true, or env_key = "QCODE_API_KEY" with the variable set from a secret manager. Pick one; Codex ignores env_key when requires_openai_auth = true.
Someone on my team leaked a shared key. What now?
Replace it, then move everyone to individual sub-keys so the next incident affects one person and one key. Shared keys make it impossible to trace usage.
Do I need to tell anyone else?
If the key was used inside a company, tell your security contact and anyone whose pipelines used it. If client code or data was in the same commit, follow your company's incident process.
For teams: use the Team plan's sub-keys
If several people, machines or pipelines use AI coding tools, QCode's Team plan gives each member a sub-key. Each unit includes $4,000 of pooled monthly quota (monthly reset, no daily cap) and 35 concurrent requests, and covers 3–5 people. See the Team plan page for current pricing and pricing for all plans.