Devmatrix: Your Digital Transformation Partner

How to Prevent Secret Leaks into GitHub?

How to Prevent Secret Leaks into GitHub?

Leaking secrets (API keys, tokens, passwords) in GitHub repositories can be a major security risk. Here’s how to prevent, detect, and mitigate secret leaks:

1️⃣ Prevention: Avoid Hardcoding Secrets

Use GitHub Secrets Instead of Hardcoding

  • Store sensitive values in GitHub Secrets instead of committing them to code.
  • Access them in workflows like this:

– name: Use Secret
   env:
       API_KEY: ${{secrets.API_KEY }}
       run: echo “Using API key in script”

Use Environment Variables for Local Development

  • Store secrets in .env files and add them to .gitignore

echo “API_KEY=your-secret-key” > .env
echo “.env” >> .gitignore

Use Vaults & Secret Managers

  • AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault for secure storage.
  • Example: Fetching a secret from AWS

– name: Fetch Secret from AWS
  run: aws secretsmanager get-secret-value –secret-id MySecret

2️⃣ Detection: Scan for Secrets Before Committing

🚨 Use Pre-commit Hooks to Block Secrets

  • Install pre-commit hooks like git-secrets

brew install git-secrets
git secrets –install
git secrets –add ‘API_KEY’

🚨 Use GitHub Secret Scanning

  • Enable GitHub’s built-in secret scanning to detect exposed credentials in repositories.

🚨 Use Tools to Scan for Leaked Secrets

  • Gitleaks

gitleaks detect –source . –verbose

3️⃣ Mitigation: What to Do If a Secret is Leaked?

🛑 1. Revoke the Leaked Secret Immediately

  • Disable compromised API keys or credentials ASAP.

🛑 2. Rotate the Secret

  • Issue a new key and update all services using it.

🛑 3. Remove the Secret from Git History

  • If a secret is already committed, remove it from Git history using BFG Repo-Cleaner

bfg –delete-files “config.json”
git push –force

Alternatively, use Git commands:

git filter-branch –force –index-filter \
“git rm –cached –ignore-unmatch path/to/secret-file” \
–prune-empty –tag-name-filter cat — –all

🔐 Summary: Keep Secrets Safe

Use GitHub Secrets, Environment Variables, or Vaults
Enable GitHub Secret Scanning & Use Pre-commit Hooks
Scan for Secrets Before Pushing Code (Gitleaks, TruffleHog)
Immediately Revoke and Rotate Secrets if Leaked
Purge Secrets from Git History if Committed

By following these best practices, you can protect your sensitive data and keep your GitHub repositories secure.

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top