API Keys: How Developers Accidentally Leak Them and How to Stop
Leaked API keys have caused real catastrophes — AWS bills in the hundreds of thousands, data breaches, service shutdowns. Here's what you're doing wrong and how to fix it.
I know a developer who committed an AWS access key to a public GitHub repo at 9pm. By 11pm, attackers had spun up 50 EC2 instances. The bill reached $47,000 before AWS caught the anomalous usage. AWS eventually waived most of it. The recovery process took two weeks.
This isn't rare. It happens constantly. Here's how to not be that person.
How Keys Get Leaked
Committed to Git is the most common. Hardcoded in source code, or in a .env file that someone forgot to gitignore. Sometimes it's in config files, sometimes in test files, sometimes in scripts someone added 'temporarily.'
Other paths: accidentally pasted in a chat message, included in a bug report screenshot, logged by an exception handler that logs the full request (including headers with auth tokens), or in a container image pushed to a public registry.
The Setup That Prevents Git Leaks
Three lines of protection:
- .env is in .gitignore before you create it
- git-secrets or gitleaks pre-commit hook scans every commit for credential patterns
- GitHub secret scanning enabled on all repositories
The pre-commit hook is the insurance policy. Even if you forget that a file has credentials, the hook catches it before the push happens.
Principle of Least Privilege
Every API key should have only the permissions it needs. If your application only reads from an S3 bucket, the key should not have write or delete permissions. If your key only sends email, it shouldn't have access to billing or account management. Most developers use admin-level keys because it's easier than scoping permissions. The security cost is enormous — a leaked key with minimal permissions does minimal damage. A leaked admin key is a catastrophe.
If You've Already Leaked a Key
Revoke it immediately. Don't try to figure out if it was used first — revoke, then investigate. Time matters. Then audit your audit logs to understand what happened. Then figure out how it leaked and fix that gap. GitHub has a guide for removing sensitive data from history (git filter-repo) if you need to purge it from historical commits too.
Frequently Asked Questions
What happens if my API key is leaked on GitHub?+
How do I store API keys safely in development?+
What is the difference between client-side and server-side API keys?+
Should I rotate API keys regularly?+
🔧 Free Tools Used in This Guide
FreeToolKit Team
FreeToolKit Team
We build free browser-based tools and write practical guides that skip the fluff.
Tags: