Keeping secrets safe

Topic 1 of 3 in Production8 min readBeginnerFree course

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:

JavaScript
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:

Text
# .gitignore
.env
.env.*
!.env.example
Terminal
# .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 --staged before every commit, and avoid blind git 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

You committed a secret. What now? 1, revoke it: rotate the key in the service — assume it is already stolen. 2, remove it from the code: read it from an environment variable or secret store instead. 3, clean the history if it was pushed: git filter-repo or BFG, then force-push and tell the team. 4, prevent the next one: .gitignore .env, push protection and secret scanning. Order matters: rewriting history does not un-leak a key that has already been copied. Revoke first.

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:

Terminal
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+):

Terminal
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 tag

Then 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:

Terminal
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 HEAD

GPG 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

  • .env and credential files in .gitignore; .env.example committed
  • 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.md explaining 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.

Exercise

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.

Terminal
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 it

Summary

  • Never commit secrets: use environment variables or a secret manager, ignore .env, and commit a .env.example instead.
  • 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.