guides · 2026-10-11
Secret Hygiene Before Release: Stop API Key Leaks
Every leaked API key has the same epitaph: "it was only temporary." Keys pasted into client-side code, committed to git, dropped into AI chat prompts — each one is a credential that now belongs to everyone. Here's where secrets actually escape, and the hygiene habits that keep them contained.
Where secrets leak
1. Client-side code
The number-one leak vector. const STRIPE_KEY = "sk_live_..." in a JavaScript bundle isn't a secret — it's a string anyone can read with View Source. Frontend code can only safely hold publishable keys (designed to be public, like Stripe's pk_ keys); anything with sk_, "secret", "private" or "admin" in the name belongs on a server.
2. Git history
Committing a key and then deleting it in the next commit doesn't help — it's in the history forever, and secret-scanning bots watch public repos in real time. AWS, GitHub and Stripe all run scanners that revoke or alert on keys found in public commits, sometimes within minutes. Private repos aren't safe either: every clone is a copy, every ex-employee a risk.
3. AI chat prompts and generated code
Pasting production code into an AI assistant to "fix this auth bug" sends your secrets to a third party. Many AI tools train on or retain conversations; some have suffered prompt-data exposures. Treat AI chat like a public forum: sanitize before you paste. And review AI-generated code for hardcoded placeholder keys the model "helpfully" filled in — developers have shipped sk-test-123-style keys that turned out to be real keys from training data.
4. Logs, error messages and URLs
Keys end up in log files (logged request bodies), error trackers (stack traces with env dumps), and URLs (query parameters in access logs and browser history). Log the key's prefix for debugging, never the key.
5. CI/CD and chatops
Secrets in CI config files, echoed in build logs, or pasted into Slack "just for a sec" — each is a leak with an audience. CI secrets belong in the platform's secret store, masked in logs, with minimal scope.
The rotation runbook
When a key leaks — assume it has, the moment it touched anywhere public — rotate immediately:
- Generate the new key first in the provider's dashboard.
- Deploy the new key to every service that uses it.
- Revoke the old key — only after the new one is live everywhere, to avoid downtime.
- Check for abuse: review the provider's usage logs for the exposure window. Unexpected spikes mean someone found it.
- Remove the leaked value from code, history (rotate + purge, or accept history is burned), chats and logs.
Speed matters more than elegance. Most providers make rotation a three-click operation — the bottleneck is always human hesitation.
Building leak-proof habits
- Environment variables for everything: no secret ever lives in source code. Use
.envfiles locally (gitignored from day one) and a secret manager in production. - Pre-commit scanning: tools like gitleaks or trufflehog catch keys before they reach the repo. Make them blocking, not advisory.
- Least-privilege keys: scope every key to the minimum permissions it needs. A read-only analytics key that leaks is an embarrassment; a full-admin key that leaks is an incident.
- Separate keys per environment: development, staging and production get different keys, so a leaked dev key can't touch production.
- Expiry and rotation schedules: keys that rotate every 90 days limit the blast radius of silent leaks.
- Sanitize before AI: strip secrets from any code you paste into AI tools — or better, use tools that scan your snippets first.
Before you release: the pre-release secret scan
Checklist added 2026-11-23 · Guide reviewed 2026-11-23
Habits are the first line of defence; a release is where they get proven. API release hygiene means no build ships until the release candidate itself — not just today's code — has been scanned for secrets. Run these steps, in this order, on every release:
- Scan the full git history, not just the working tree. A key that was committed and then "removed" in the next commit is still in history and still live. Run a history-aware scanner over every branch you are about to publish — for example
gitleaks gitortrufflehog gitpointed at the repo — and treat any verified finding as an exposed key, not a false alarm to wave through. - Scan the working tree and the release artefacts. Run the scanner over the files themselves (source, config, docs, example files), then over what you actually ship: built JavaScript bundles, mobile app packages and container images. Keys get baked into build output and Docker image layers even when the source is clean — check the artefact, not just the repo.
- Check the env files explicitly. Confirm every
.env,.env.localand.env.productionis gitignored and untracked (git ls-files | grep envshould return only placeholders such as.env.example), that example files contain dummy values only, and that no real key sits in CI configuration files, release notes or changelog text. - Rotate anything the scan finds — before you ship. Deleting the string does not un-leak it. Follow the rotation runbook above: generate the new key, deploy it everywhere, revoke the old one, then check the provider's usage logs for the exposure window. Only then clean the code and, if the key reached a public repo, purge or rewrite the history knowing the old value is burned either way.
- Gate the release on the scan in CI. Make the secret scan a required CI job on the release branch: the pipeline runs the scanner and a finding fails the build and blocks the release — the same blocking pre-commit hook, enforced where nobody can skip it locally. Keep CI's own secrets in the platform secret store, masked in logs, so the gate does not become the leak.
- Re-scan after fixes and record the clean run. Fix, rotate, then run the whole scan again on the exact commit you are tagging. A release is clean when that final scan passes — note the date and result in your release notes so the next release starts from a known-good baseline.
A worked pre-release scan, run by run
Worked run added 2026-11-28 · Guide reviewed 2026-11-28
The checklist above gives the order. This section shows what it looks like on an actual release afternoon: the commands a developer really types, and the decision each result forces. Picture a small team tagging version 2.3 of a booking app late in the week. Nobody wants a delay. The scan takes about twenty minutes when it finds nothing, and the days it finds something are the ones that pay for all the others.
Run 1: history first, on the exact commit you will tag
Check out the release branch and scan every commit, not just the latest snapshot: gitleaks git --redact, or trufflehog git file://. --only-verified if you prefer TruffleHog. History goes first for a simple reason. A key removed last week still sits in an old commit, and a scan of the current files will smile and wave it through. Write down the commit hash you scanned. If anyone pushes another commit afterwards, that clean result no longer belongs to the thing you are shipping, and you scan again.
Run 2: the working tree, and the files people forget
Point the scanner at the whole tree (gitleaks dir .), then read the boring corners by hand. Check the .env.example that quietly grew real values last month. Open the API collection a teammate exported to share with support. Skim seed scripts for the temporary admin password that stopped being temporary, and look at the docs folder for a dashboard screenshot with half a key visible. Scanners are weak in these corners. Example files and exports are where real keys hide behind harmless names.
Run 3: the artefact, not the intention
Build the release the way production builds it, then scan what comes out. Search the bundled JavaScript for key prefixes; grep -r "sk_live" dist/ is crude and still catches real leaks. Unpack the mobile binary if you ship one. Inspect the container image layer by layer, because a key passed as a build argument lives in an image layer even when the final files look clean. A dirty artefact means a dirty release, whatever the repository says.
When the scan hits: the first thirty minutes
Sooner or later it hits. In this worked run it is a live payment key in a commit from six weeks ago, added during a late-night debugging session and removed the next morning. The worst first move is deleting the file and carrying on. Work the hit in this order instead:
- Stop and write down what you found. Which key, which provider, which commits and branches hold it, and whether any of them were ever pushed or published. Guesses get worse with time. A short note written now settles arguments later.
- Check whether anyone used it. Open the provider's usage and audit logs for the whole window since the first commit. Look for unfamiliar IP addresses, odd hours, and refund or export calls you do not recognise. What you find decides whether this stays a rotation or becomes an incident.
- Rotate in the runbook order. New key first, deployed everywhere the old one worked, verified with a real request, and only then the old key revoked. Revoking first, with abuse not showing in the logs, buys you a self-inflicted outage, and outages tempt tired people into reviving the leaked key.
- Clean up last. Remove the value from the tree. If the repository is public, purge or rewrite the history, and accept that the old value stays burned either way. History rewriting is hygiene, not rescue.
- Re-run all three scans on the new release commit. The release ships when the candidate you actually tag comes back clean. Record the date, the tool and the result in the release notes.
One judgement call is worth naming. A test-mode key in a private repository that was never pushed anywhere is a smaller problem: replace it, note it, move on. A live key, or anything that reached a public repo, a shared drive or a chat channel, gets the full treatment above. And when you cannot tell whether a key left the building, assume it did.
Scanning is the safety net
Habits fail; automation doesn't get tired. Vibe-Code Audit scans pasted code and live sites for 32 secret patterns (AWS, GitHub, Stripe, OpenAI, Supabase, Twilio, private keys, JWTs and more), shows each leak's blast radius, and Pro adds the exact rotation runbook for the key type found. Run it on every AI-generated change before merge — it's the cheapest incident you'll ever prevent.
Sources
- OWASP Cheat Sheet Series — Secrets Management, OWASP's best-practice guide to storing, rotating and auditing secrets: cheatsheetseries.owasp.org, 2026
- OWASP Top 10, the OWASP Foundation's standard awareness list of the most critical web application security risks: owasp.org, 2021
- CWE-89: Improper Neutralization of Special Elements used in an SQL Command, MITRE's weakness entry for SQL injection and its mitigations: cwe.mitre.org, 2026
- GitHub Docs, About secret scanning, GitHub's documentation of how secret scanning detects partner key patterns in repositories and alerts the key issuers: docs.github.com, 2026
Frequently asked questions
Where do API keys and secrets most often leak?
In client-side code (anything shipped to the browser is a public string), in git history (deleting a key in the next commit leaves it in history forever, and scanning bots watch public repos in real time), and in AI chat prompts and generated code pasted back and forth during debugging.
Is a key in a private repository safe?
Safer, not safe. Every clone, fork, CI log and ex-collaborator laptop is a copy. Keep real values in environment settings or a secret manager and commit only a placeholder example file.
Which keys are safe to ship in frontend code?
Only publishable keys designed to be public, like Stripe's pk_ keys. Anything with secret, private or admin in the name — sk_ keys, service-role keys, signing secrets — belongs on a server, never in a bundle.
What should I do the moment a key leaks?
Rotate it immediately — treat exposure as compromise, because you cannot prove nobody copied it. Then audit the provider's logs for the whole exposure window, and fix the path it escaped through so the replacement does not follow it.
How do I stop secrets reaching AI chat tools?
Treat AI chat like a public forum: redact keys before pasting code, use placeholder values in examples, and give the assistant the shape of the code rather than the production file. Rotate any key that has already been pasted.
What order should I run the pre-release secret scan in?
History first, on the exact commit you intend to tag, because a removed key still lives in old commits. Then the working tree, including example files, exports and documentation. Then the built artefact itself: JavaScript bundles, mobile packages and container image layers. A clean repository with a dirty bundle is still a dirty release.
The scan found a key the day before release. Do we have to delay?
Only long enough to rotate properly. Create the replacement key, deploy it, verify it works, revoke the leaked one, and check the provider's logs for the exposure window. Then clean the code and re-scan the new release commit. For a live key that reached a public repository, that work is the release now. Shipping first and rotating later leaves the leaked key working in the wild.
Informational explainer, not a security guarantee. Scan your code free before every deploy.