Hardcoded Secrets in Code: Detection and Prevention

How to detect and prevent secrets (API keys, database credentials, tokens) from being committed to version control.
One hardcoded AWS secret or database password committed to a public GitHub repository can lead to a multi-million dollar breach. Yet hardcoded secrets are still the #1 cause of cloud infrastructure compromise.
The problem: hardcoded secrets often start as temporary debugging code ("I'll remove this later") and accidentally get committed. By then, they're already in git history.
How Secrets Get Committed
1. Copy-paste from local config: "I'll use the prod key just to test locally"
2. Forgotten debug code: Hardcoded credentials with a TODO comment
3. Infrastructure-as-code drift: Secrets in CloudFormation or Terraform files
4. Test fixtures: Test data with real API keys embedded
5. Package dependencies: Leaked secrets in npm or PyPI packages
How to Detect Secrets in Code Review
Manual detection is unreliable. A developer reviewing a 300-line PR won't spot a production API key hidden in comments.
Automated secret detection uses pattern matching to find:
• AWS keys (AKIA...)
• Database connection strings (postgres://, mongodb://)
• API tokens (GitHub tokens, Slack tokens)
• Private keys (RSA, SSH, PGP)
• Credentials (basic auth in URLs)
Best Practices for Secret Management
1. Never commit secrets. Use environment variables or secret management systems (AWS Secrets Manager, HashiCorp Vault).
2. Scan PRs automatically. Catch secrets before merge using pre-commit hooks and CI scanning.
3. Rotate immediately. If a secret is ever committed, assume it is compromised. Rotate it even if it was deleted.
4. Use per-environment credentials. Don't use the same API key for dev, staging, and production.
5. Audit secret access. Log who accessed which secret and when.
About the Author
Elena Rodriguez
Security Research Lead, Codluma
Elena leads security research at Codluma, focusing on fintech security. 13+ years in AppSec and compliance auditing. CISA certified.