Prompt & Done · KEYSAFE

Keep API keys out of Git, and what to do if one already leaked

Deleting a key in a new commit doesn't remove it: every commit is a snapshot, so the commit before still has it. We tested it on 7 Nov 2026 in a local repo with a fake key: git show HEAD~1:app.py printed the key after the delete.

1 The setup (do this before the first commit)

echo ".env" >> .gitignore
echo "OPENAI_API_KEY=sk-..." >> .env
git check-ignore -v .env      # must print .gitignore:1:.env
git status --short --ignored  # .env shows as !! (ignored)

Read it in code from the environment. Python: pip install python-dotenv, then from dotenv import load_dotenv; load_dotenv(); key = os.environ["OPENAI_API_KEY"]. Node 20+: node --env-file=.env app.js and process.env.OPENAI_API_KEY.

Commit a .env.example with the variable names and no values, so others know what to set. Using Claude Code or another agent? Add to your CLAUDE.md: "Never write secrets into source files; read them from environment variables in .env."

2 Check your history

git log -p -S "sk-" --all     # every commit that added or removed the string
git grep "sk-" $(git rev-list --all)

Swap sk- for your provider's key prefix. Anything that shows up is in your history, even if it's gone from the current files.

3 If a key leaked: the checklist

  1. Revoke it in the provider's dashboard (OpenAI, Anthropic, Stripe...). Deleting the line does nothing for a key that's already out.
  2. Make a new key and put it only in .env.
  3. Check usage and billing on the old key for anything you didn't do.
  4. Optionally rewrite history (git filter-repo) and force-push; GitHub notes copies may still exist elsewhere (forks, clones), which is why revoking comes first.

On public repos GitHub runs secret scanning automatically and, for partner key formats, notifies the provider. Don't count on it to protect you: anyone can clone a public repo's history.

docs.github.com: removing sensitive data · docs.github.com: about secret scanning · git-scm.com: gitignore