Keeping secrets safe
Overview
Every year, thousands of API keys, database passwords and cloud credentials are accidentally pushed to GitHub — and automated scanners find public ones within minutes. A leaked cloud key can run up huge bills or expose customer data. This lesson covers how to keep secrets out of Git, what to do when one gets in anyway, and how to prove your commits are really yours.
Keeping secrets out
Don’t put them in code
Read secrets from the environment at runtime:
const apiKey = process.env.PAYMENTS_API_KEY;For local development, keep values in a .env file that is ignored, and commit a template without values so others know what to set:
# .gitignore
.env
.env.*
!.env.example# .env.example — committed
PAYMENTS_API_KEY=
DATABASE_URL=In production and CI, use the platform’s secret store: GitHub Actions secrets, your cloud’s secret manager, or a vault.
Catch them before they’re committed
- Review what you stage:
git diff --stagedbefore every commit, and avoid blindgit add .. - A pre-commit secret scanner such as gitleaks or detect-secrets (easily added with the pre-commit framework from Git hooks).
- GitHub push protection: GitHub checks pushes for known secret formats (cloud keys, tokens, payment keys…) and blocks the push with an explanation. It’s on by default for your account when you push to public repositories, and administrators can enable it for repositories. You can bypass it only by giving a reason, which is logged and alerts the owners.
- Secret scanning: GitHub scans repositories for secrets and raises alerts — and many providers (AWS, Stripe, GitHub itself…) are notified to revoke leaked tokens automatically.
When a secret leaks
1. Revoke it — first, always
Go to the service (cloud console, payment provider, GitHub settings) and revoke or rotate the credential. Assume it’s already been copied: public repositories are scanned by attackers continuously, and even private repositories are cloned to many machines. Once the old key no longer works, the leak is harmless — and often that’s enough.
2. Remove it from the code
Replace it with an environment variable and commit that change. This stops future copies, but the secret is still in the history.
3. If it was pushed, consider rewriting history
If the secret was only committed locally and never pushed, simply amend or rebase it away (Amend and revert, Interactive rebase). If it was pushed — especially to a public repository, or if it’s personal data rather than a revocable key — GitHub recommends rewriting history with git filter-repo:
git clone --no-local … fresh-clone && cd fresh-clone
# remove a file from all history
git filter-repo --sensitive-data-removal --invert-paths --path config/secrets.yml
# or replace text everywhere (one "secret==>replacement" per line)
echo 'sk_live_51HxQ2a9b8c7d6e5f4==>***REMOVED***' > ../replacements.txt
git filter-repo --sensitive-data-removal --replace-text ../replacements.txt
git push --force --mirror origin(--sensitive-data-removal needs git-filter-repo 2.47 or later. BFG Repo-Cleaner is an older alternative.)
Rewriting history has real costs: every commit ID after the leak changes, signatures are lost, open pull requests break, and anyone with an old clone can push the secret right back. So after force-pushing:
- ask GitHub Support to purge cached views and pull request references that may still contain the data;
- tell collaborators to re-clone (or rebase their work onto the new history — never merge the old history back in);
- contact owners of forks, which keep their own copies.
That’s why step 1 matters most: a revoked key in old history is just an embarrassment; a live one is an incident.
Signing commits
Anyone can set user.name and user.email to anything — Git doesn’t check. Signed commits prove a commit was made by someone holding your private key. GitHub shows signed commits from keys on your account as Verified, and a ruleset can require signed commits on protected branches.
The simplest method uses an SSH key (Git 2.34+):
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true # sign every commit
git config --global tag.gpgsign true # and every annotated tagThen add the same public key on GitHub as a Signing key (Settings → SSH and GPG keys → New SSH key → Key type: Signing Key). Your commits now show the Verified badge.
To verify signatures locally, Git needs a list of trusted keys:
echo "asha@example.com $(cat ~/.ssh/id_ed25519.pub)" >> ~/.config/git/allowed_signers
git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers
git log --show-signature -1
git verify-commit HEADGPG keys and S/MIME certificates work too, if your organisation already uses them. Commits made in GitHub’s web interface are signed by GitHub automatically.
A security checklist for repositories
-
.envand credential files in.gitignore;.env.examplecommitted - push protection and secret scanning enabled
- a pre-commit secret scanner for the team
- Actions secrets for CI — never secrets in workflow files
- least-privilege
permissions:in workflows, and third-party actions pinned - Dependabot alerts and security updates turned on
- a
SECURITY.mdexplaining how to report vulnerabilities - signed commits required on
main(for teams that need it)
The one thing to remember: if a secret is ever pushed, revoke it immediately. Everything else is cleanup.
Clean up a leaked key and sign your commits
Part 1: a live API key was committed in config.js two commits ago and is still in the latest version. Pretend you’ve already revoked it (always step one!). Move the key out of the code into an ignored .env file, then rewrite all history in a fresh clone with git filter-repo --sensitive-data-removal --replace-text so the key appears nowhere, and verify with git log -S. Part 2: set up SSH commit signing, make a signed commit, and verify it with git verify-commit.
mkdir leaky && cd leaky && git init -qb main
echo "export const apiUrl = 'https://api.example.com';" > config.js
git add . && git commit -qm "Add config"
echo "export const apiKey = 'sk_live_51HxQ2a9b8c7d6e5f4';" >> config.js
git commit -qam "Connect to payments API"
echo "# Shop" > README.md && git add . && git commit -qm "Add README"
cd ..
# Part 1
# 0. (Real life: revoke/rotate the key in the provider's dashboard FIRST.)
# 1. Read the key from the environment instead; ignore .env
# 2. Rewrite history in a fresh clone so the key is gone everywhere
# 3. Verify
# Part 2
# 4. Create a signing key and configure SSH signing
# 5. Make a signed commit and verify itmkdir leaky && cd leaky && git init -qb main
echo "export const apiUrl = 'https://api.example.com';" > config.js
git add . && git commit -qm "Add config"
echo "export const apiKey = 'sk_live_51HxQ2a9b8c7d6e5f4';" >> config.js
git commit -qam "Connect to payments API"
echo "# Shop" > README.md && git add . && git commit -qm "Add README"
cd ..
# Part 1
# 0. (Real life: revoke/rotate the key in the provider's dashboard FIRST.)
# 1. Read the key from the environment instead; ignore .env
cd leaky
echo "export const apiUrl = 'https://api.example.com';" > config.js
echo "export const apiKey = process.env.PAYMENTS_API_KEY;" >> config.js
echo ".env" > .gitignore
echo "PAYMENTS_API_KEY=new-rotated-key" > .env # local only, never committed
git add config.js .gitignore && git commit -qm "Read payments key from the environment"
cd ..
# 2. Rewrite history in a fresh clone so the key is gone everywhere
git clone -q --no-local leaky leaky-clean && cd leaky-clean
echo 'sk_live_51HxQ2a9b8c7d6e5f4==>***REMOVED***' > ../replacements.txt
git filter-repo --sensitive-data-removal --replace-text ../replacements.txt --no-fetch
# Then on GitHub: git push --force --mirror origin, ask GitHub Support to purge
# cached views and pull request refs, and have everyone re-clone.
# 3. Verify
git log --all -S "sk_live_51HxQ2a9b8c7d6e5f4" --oneline | wc -l # 0
git show HEAD~2:config.js # apiKey = '***REMOVED***'
# Part 2
# 4. Create a signing key and configure SSH signing (use your real key in practice)
ssh-keygen -q -t ed25519 -N "" -C "asha@example.com" -f ../signing_key
git config gpg.format ssh
git config user.signingkey "$(cd .. && pwd)/signing_key.pub"
echo "asha@example.com $(cat ../signing_key.pub)" > ../allowed_signers
git config gpg.ssh.allowedSignersFile "$(cd .. && pwd)/allowed_signers"
git config user.email asha@example.com
# 5. Make a signed commit and verify it
echo "Security: report issues to security@example.com" > SECURITY.md
git add SECURITY.md && git commit -qS -m "Add security policy"
git verify-commit HEAD && echo "signature verified ✓"Summary
- Never commit secrets: use environment variables or a secret manager, ignore
.env, and commit a.env.exampleinstead. - If a secret is pushed, revoke or rotate it first — removing it from Git doesn’t un-leak it.
- Rewrite history with
git filter-repo(GitHub’s recommended tool), force-push, and have collaborators re-clone. - Turn on secret scanning and push protection, and add a pre-commit secret scanner.
- Sign commits with an SSH or GPG key so GitHub can show them as Verified.