Sub topic 14
Preventing the next leak
Cleaning history after a leak is slow and never fully complete, because forks, caches, and old clones can keep copies. This chapter covers the controls that make the next leak less likely, and less harmful when it happens anyway.
This chapter assumes you have read the earlier chapters on rotation and git filter-repo. You should also know how Git hooks run and be comfortable editing YAML and shell scripts.
Think in layers
No single control stops every leak. A developer can skip a local hook, a scanner can miss an unusual token format, and a .gitignore entry does nothing for a file that is already tracked. Stack controls so that each one catches what the previous one missed.
Keep secrets out of the working tree
The best prevention is to make committing a secret unnecessary. Code should read secrets at runtime from the environment or from a secret manager, never from a tracked file.
- Store real values in environment variables, a secret manager, or your CI system's encrypted secrets.
- Commit a template such as
.env.examplethat has keys and placeholder values only. - Add the real file, such as
.env, to.gitignore.
cp .env.example .env
printf '.env\n' >> .gitignore
git add .gitignore .env.example
git commit -m "Add env template and ignore local env file"Check that the ignore rule works before you rely on it:
git check-ignore -v .envThe command prints the matching rule. If it prints nothing, the file is not ignored.
Ignore rules do not apply to tracked files
.gitignore only affects untracked files. If config/secrets.env was committed once, adding it to .gitignore later changes nothing. Stop tracking it with git rm --cached:
git rm --cached config/secrets.env
printf 'config/secrets.env\n' >> .gitignore
git add .gitignore
git commit -m "Stop tracking secrets file"This only stops future tracking. The earlier commits still contain the file, so history cleanup and rotation are still required.
Block commits locally with a pre-commit hook
A pre-commit hook runs before Git creates a commit. If the hook exits with a non-zero status, the commit is cancelled. A secret that never becomes a commit never needs a history rewrite.
Use a maintained scanner
Writing your own detection patterns does not scale. The pre-commit framework runs scanners such as gitleaks on staged changes. Create .pre-commit-config.yaml in the repository root:
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.4
hooks:
- id: gitleaksInstall the framework and activate the hook:
pip install pre-commit
pre-commit install
pre-commit run --all-filesThe last command scans the files currently in the repository, which is a quick check that the hook works. Pin rev to a release and update it on a schedule, so scanner behavior does not change unexpectedly.
A minimal hand-written hook
A simple hook is useful for a pattern specific to your organization, such as an internal token prefix. This example blocks AWS access key IDs, which start with AKIA:
#!/usr/bin/env bash
set -euo pipefail
if git diff --cached -U0 | grep -E '^\+.*AKIA[0-9A-Z]{16}' > /dev/null; then
echo "Possible AWS access key ID in staged changes. Commit blocked." >&2
exit 1
fiSave it as .githooks/pre-commit and make it executable. Hooks in .git/hooks are not shared when someone clones the repository. Keeping the script in a tracked directory and pointing Git at it lets every contributor use it:
chmod +x .githooks/pre-commit
git config core.hooksPath .githooksEach contributor must run the git config line once per clone. A setup script or a make setup target can do that for them.
Local hooks are advisory
Anyone can skip hooks with git commit --no-verify, and a fresh clone has no hooks until someone installs them. Treat the local hook as a convenience that catches honest mistakes early. Do not treat it as a security boundary.
Enforce on the server
Controls on the server cannot be skipped by a contributor's local settings, so they are the layer to rely on.
- Push protection. Some hosting platforms reject a push that contains a recognized secret. GitHub calls this push protection, and GitLab offers secret push protection. Availability depends on your host and plan, so check its documentation.
- Secret scanning of existing content. Hosts that offer scanning can alert on secrets already in history. Some can also notify the issuing provider, which may revoke the token automatically.
- CI scan of the full history. Run a scanner on every pull request and on a schedule. Scanning only the diff misses secrets already in older commits.
A CI step that scans the whole repository history with gitleaks looks like this:
gitleaks detect --source . --redact --verboseThe --redact option keeps the secret itself out of CI logs, which matters because build logs are often readable by more people than the repository. Newer gitleaks releases also offer gitleaks git for the same job, so use the form your pinned version supports. The command exits non-zero when it finds something, so the CI job fails.
Handling false positives
A noisy scanner trains people to ignore it. When a finding is a known false positive, such as a documented example key, record it in a .gitleaksignore file. Gitleaks uses the finding's fingerprint, which is printed with the finding. Review additions to this file in pull requests, because an ignore entry can also hide a real leak.
Limit the damage of a leak
Assume that one day a secret will get through. These practices decide whether that is an inconvenience or an incident.
- Least privilege. Give each credential only the permissions its job needs. A key that can read one bucket is far less dangerous than an administrator key.
- Short lifetimes. Prefer temporary credentials, such as those issued by a cloud provider's role mechanism, over long-lived keys. An expired token that leaks is harmless.
- One credential per use. Separate keys for each service and environment let you revoke one without breaking everything else.
- Easy rotation. If rotating a key needs a day of coordination, people delay doing it. Practice rotation before you need it, and keep the steps documented.
Write the response plan before you need it
The earlier chapters give you an order of operations. Write it down where your team will find it, so that nobody improvises under stress:
- Revoke and rotate the credential.
- Find where it appears in history and in logs, tickets, or chat.
- Rewrite history with
git filter-repoin a fresh clone. - Verify, force-push, and tell collaborators to re-clone.
- Check forks, cached pull request refs, and old clones.
- Add or tighten the control that should have caught the leak.
Step 6 turns each incident into a lasting improvement. Ask which layer failed: the hook was not installed, the scanner lacked a rule for that token format, or the secret lived in a file type nobody scanned. Then fix that gap.
What to adopt first
If you can only do a few things this week, do them in this order:
| Priority | Control | What it protects against |
|---|---|---|
| 1 | Server-side push protection or a CI history scan | Leaks that bypass local hooks |
| 2 | Secrets read from the environment or a manager | The reason to commit a secret at all |
| 3 | Local pre-commit hook | Honest mistakes, caught before a commit exists |
| 4 | Least-privilege, short-lived credentials | The cost of a leak that gets through |
| 5 | A written response plan | Slow or incomplete cleanup |
Summary
- Prevent the commit with environment-based secrets, ignore rules, and a local hook.
- Enforce the rule on the server with push protection and a CI scan of the full history.
- Reduce the cost of a leak with least-privilege, short-lived credentials.
- Rehearse the response plan, and use each incident to close the gap that allowed it.
Exercise
A developer adds config/secrets.env to .gitignore, but the file still shows up in git status as modified. What is wrong, and what two follow-up actions are needed if the file contains real credentials?
Show answer
The file was already tracked, and .gitignore only affects untracked files. Run git rm --cached config/secrets.env and commit to stop tracking it. Because earlier commits still contain the credentials, also rotate them and remove the file from history with git filter-repo --invert-paths --path config/secrets.env in a fresh clone.
Exercise
Your team installs a gitleaks pre-commit hook for every developer. Why is that not enough on its own, and which control should you add so that a skipped hook is still caught?
Show answer
Hooks are local and optional. A developer can run git commit --no-verify, and a fresh clone has no hooks installed until someone sets them up. Add a server-side control, either push protection on the hosting platform or a CI job that scans the repository, so that every push is checked regardless of local settings.