← All Insights

Hardcoded API Keys in Source Code: How to Find, Fix and Prevent Credential Leaks

Hardcoded credentials in source code are one of the most common and most damaging security vulnerabilities I encounter during architectural assessments. The risk is straightforward: anyone who can access the code may potentially access the credential as well.

The risk escalates significantly when repositories are public, shared across teams, or when the same code is forked. Credentials get copied and distributed across systems you cannot track.

This guide covers how to find hardcoded credentials, how to properly remediate them, and how to prevent them from appearing in the first place.


Why Hardcoded API Keys Are Dangerous

The core issue is access control. A hardcoded credential in source code is accessible to everyone with repository access: developers, contractors, CI/CD systems, and anyone who gains access through any means.

The problem compounds with time. A credential committed three years ago and never rotated is still valid. If the repository was ever public, even briefly, that credential may have already been indexed by automated scanners that specifically hunt for exposed API keys.

The consequences range from unauthorized API usage and unexpected billing to complete account compromise, data breaches, and regulatory violations.


How to Find Hardcoded Credentials

Basic text searches with grep catch obvious cases but miss encoded, obfuscated, or non-standard credential patterns. Purpose-built secret scanning tools are significantly more effective.

Gitleaks is a fast, open-source tool that scans repositories, including their full git history, for secrets. It uses a rule-based detection engine with patterns for hundreds of credential types.

gitleaks detect --source . --verbose

TruffleHog scans git history with entropy analysis to find high-entropy strings that may be credentials even without matching known patterns.

Trivy includes secret scanning as part of its broader vulnerability scanning capabilities:

trivy fs --scanners secret .

Run all three. They use different detection approaches and complement each other.


When You Find a Credential: What to Investigate First

Before fixing anything, assess the exposure systematically:

  • What systems does this credential access, and with what permissions?
  • Is the credential currently active, or has it already been rotated?
  • Is the repository public, private, or was it previously public?
  • How far back in git history does this credential appear?
  • Could the credential appear in logs, CI/CD artifacts, or deployment outputs?

This assessment determines urgency. A credential with read-only access in a private repository is different from an admin key in a repository that was public for any period.


Remediation: The Common Mistake

The most common mistake teams make when finding a hardcoded credential is deleting it from the current code and committing the change.

This does not fix the problem. The original secret is still in git history, still accessible to anyone with repository access, and still valid if it has not been rotated.

Proper remediation requires three steps in this order:

  1. Rotate or revoke the credential immediately. Do this before anything else. The exposed credential should be considered compromised regardless of whether you can confirm it was accessed.
  2. Review and clean git history. Use git filter-repo or BFG Repo Cleaner to remove the credential from git history. Force-pushing a cleaned history requires coordination with the team.
  3. Verify across all artifacts. Check CI/CD logs, deployment scripts, backups, and anywhere the code may have been copied. Rotating the credential makes all existing copies inert, which is why step 1 is non-negotiable.

The Right Way to Handle Credentials

Credentials should never appear in source code. They should be retrieved from external systems at runtime.

Environment variables are the minimum baseline. The application reads credentials from the environment at startup rather than having them compiled in. This separates configuration from code.

Secret management platforms are the right approach for production systems:

  • HashiCorp Vault: self-hosted, highly configurable, supports dynamic secrets
  • Kubernetes Secrets: for containerized workloads
  • AWS Secrets Manager, Azure Key Vault, GCP Secret Manager: cloud-native options

The advantage of dedicated secret management is rotation without redeployment, audit logging of secret access, and fine-grained access control over which systems can retrieve which credentials.


Prevention: Automate the Detection

The most reliable way to prevent hardcoded credentials is to catch them before they are committed or deployed.

Pre-commit hooks run secret scanning tools before a commit is accepted. Gitleaks includes a pre-commit hook configuration. This stops credentials at the developer's machine before they ever reach the repository.

CI/CD pipeline scanning adds a mandatory security gate. Add a Gitleaks or Trivy secret scan as a required step in your pipeline. Any scan that finds credentials fails the build and blocks the deployment.

Combining both approaches creates defense in depth: pre-commit hooks catch most issues locally, and pipeline scanning acts as a backstop for anything that slips through.


Conclusion

Hardcoded credentials are a preventable vulnerability. The technical fixes are straightforward. The harder challenge is organizational: building the habit of treating credentials as sensitive infrastructure rather than configuration values, and automating the detection so it does not depend on individual discipline.

Rotate any credential you find. Clean the history. Move to environment variables or a secret manager. Add scanning to your CI/CD pipeline. These four steps eliminate the vast majority of credential exposure risk in practice.