Secret Scanning: Stop Secrets From Leaking Into Git
Secrets slip into git through habit and haste, and the only reliable fix is catching them before they're committed, not after.
Key takeaways
- Secret scanning detects API keys, tokens and private keys in code so they never reach shared git history.
- Run gitleaks or detect-secrets as a pre-commit hook, repeat the scan in CI because hooks can be skipped, and enable GitHub push protection as the backstop.
- If a secret leaks anyway, rotate it first.
On this page
Stop secrets leaking into git by scanning at three points: a gitleaks or detect-secrets pre-commit hook on every laptop, the same scan in CI because hooks can be skipped, and GitHub push protection on the hosted repo. Secret scanning is automated detection of credentials, keys and tokens in code. When something leaks anyway, rotate the credential before anything else.
Verified against
gitleaks 8.30.1, detect-secrets 1.5.0, against the gitleaks and detect-secrets READMEs and the GitHub Docs secret scanning and push protection pages. Checked October 2026.
On GitHub, secret scanning runs automatically and for free on public repositories and scans the entire git history on all branches. Private and internal repositories in an organization need GitHub Secret Protection, available on GitHub Team or Enterprise Cloud.
Why do secrets end up in git anyway
Every engineer knows not to commit credentials. They end up in git constantly. The pattern is almost always the same: a developer hardcodes an API key while debugging a third-party integration, gets the thing working, and moves on to the next bug without stripping the key back out before the commit. A .env file gets created for local testing and the .gitignore update happens after the first commit, not before. Someone pastes a database connection string into a commit message to document what they were testing against. A config file gets checked in "temporarily" to unblock a deploy, with a mental note to remove it that never gets acted on.
None of this is negligence in the dramatic sense. It's the natural result of optimizing for speed under deadline pressure, in a workflow where nothing stops you from committing a secret. Git was not built with credential hygiene in mind, and by default it will happily version anything you hand it.
Why is a leaked secret in git history so hard to undo?
Because deleting the file in a later commit doesn't delete the secret. Git tracks history as a chain of snapshots, and the old snapshot containing the secret is still reachable through the commit graph, git log, and git blame even after the file is gone from the working tree. Anyone who cloned the repo before the fix has a full copy of every commit, including the one with the exposed key, sitting on their disk whether they ever check it out or not.
If the repository is public, the exposure window is measured in minutes, not days. Bots scrape public GitHub pushes continuously looking for patterns that match cloud provider keys, database URLs, and webhook tokens. A key pushed to a public repo at 2 a.m. can be scanned, extracted, and tested for validity before you've had coffee. Private repos aren't immune either: they get cloned to laptops, forked into personal accounts, mirrored to CI runners, and archived in backups, all of which extend the blast radius past whatever access control the platform enforces on the original repo.
The three layers of defense
No single scanning point catches everything, which is why this works best as three checks stacked in sequence rather than one you pick.
Layer 1: pre-commit, before the secret leaves your machine
A git hook that scans staged changes before git commit completes is the cheapest place to catch a secret, because at that point it hasn't gone anywhere yet. Tools like gitleaks and detect-secrets run entirely locally, comparing staged diffs against regex and entropy-based patterns for API keys, private keys, and tokens. If a match is found, the commit is blocked and nothing leaves your laptop.
A minimal .pre-commit-config.yaml entry using gitleaks looks like this:
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.30.1
hooks:
- id: gitleaks
Pin rev to a real release tag; v8.30.1 is the latest gitleaks release as of October 2026. Or use detect-secrets, which supports a baseline file to track accepted false positives:
repos:
- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets
args: ["--baseline", ".secrets.baseline"]
v1.5.0 is still the latest detect-secrets release (May 2024) as of October 2026. Generate the baseline once, then review what it flagged:
detect-secrets scan > .secrets.baseline
detect-secrets audit .secrets.baseline
pre-commit install
Layer 2: pre-push and CI, for what got past the hook
Pre-commit hooks are opt-in on every developer's machine, and git commit --no-verify skips them entirely, sometimes deliberately, sometimes out of habit when a hook is slow or misbehaving. That's why a scan step belongs in the CI pipeline too: it runs against every pushed branch regardless of local configuration and fails the build if a secret pattern is detected, catching what pre-commit missed, skipped, or bypassed. This is also the natural place to run the same tool against every commit in the pull request rather than just staged files. Since gitleaks 8.19 the detect and protect commands are deprecated in favour of git, dir and stdin, so CI scripts copied from old blog posts deserve a check:
# Scan only the commits this branch adds on top of main
gitleaks git -v --log-opts="origin/main..HEAD" .
# Scan a directory or build artifact that is not a git repo
gitleaks dir -v ./dist
For the rest of what belongs in that pipeline, see how to secure your CI/CD pipeline, and for the workflow-level side (token permissions, pinned actions), our GitHub Actions security hardening guide.
Layer 3: continuous and platform scanning, the safety net
Even with both earlier layers in place, something eventually slips through: a fork with different hook settings, a direct push from an admin account, a secret format the regex list doesn't cover yet. GitHub push protection blocks pushes containing partner-pattern tokens, generic secrets such as private keys and connection strings, and your own custom patterns before they land. Two details matter. Repository-level push protection is off by default and requires Secret Protection, while user-level push protection is on by default but only covers pushes to public repositories. And anyone with write access can bypass it by giving a reason, which creates an alert and an audit-log entry, so someone has to read those. GitHub also reports partner-format tokens straight to the issuing provider so it can act, for example by revoking the token. GitGuardian and similar services run the same kind of continuous scan across repositories and history.
What do you do when a secret leaks?
Rotate it immediately. GitHub's own guidance puts rotation first and calls history rewriting optional. The value is compromised the moment it's pushed, even to a private repository, even if you catch it and delete the file within minutes. Treat "was it accessed" as unknowable and act as if it was.
Deleting the file in a new commit is not a fix; the secret is still in history as described above. Rewriting history with git filter-repo or BFG Repo-Cleaner can strip the secret out of every commit and force-push a clean history, and that's worth doing to reduce future exposure and keep the repo tidy. But it only helps going forward. It does nothing to undo exposure that already happened, and it doesn't reach anyone who already cloned the repo with the old commits intact. Rotation is the step that actually neutralizes the leak; history rewriting is cleanup on top of it, not a substitute for it.
After rotating, check the provider's access logs for the credential if they're available, and confirm the new value is deployed everywhere the old one was before you consider the incident closed. This whole workflow sits inside the broader practice covered in application security best practices. Rotation is also far less painful when secrets live in a manager rather than in files; Vault vs Secrets Manager vs Doppler compares the usual choices.
Questions people ask
Does GitHub scan private repositories for secrets?
Only with GitHub Secret Protection enabled, which is available on GitHub Team and GitHub Enterprise Cloud for organization-owned private and internal repositories. Public repositories are scanned automatically and free. When enabled, secret scanning covers the entire git history on all branches, plus issues, pull requests, discussions and wikis, and GitHub rescans when it adds new secret types.
Which is better, gitleaks or detect-secrets?
They solve the same problem with different ergonomics. gitleaks is a single Go binary with a large built-in rule set and commands for git history, directories and stdin, which makes it easy in CI. detect-secrets, from Yelp, is Python and centres on a reviewed .secrets.baseline file, which suits large existing codebases with many known false positives. Pick one and run it both locally and in CI.
The call we'd make
Put a pre-commit hook on every repo with gitleaks or detect-secrets and treat a CI scan step as non-negotiable, not optional. Turn on GitHub push protection or a GitGuardian integration as the backstop, not the primary defense. And write down a rotation runbook now, before you need it, so the response to a leaked secret is a five-minute checklist instead of a scramble.
Sources
Cite this article
Kiril Urbonas (2026). Secret Scanning: Stop Secrets From Leaking Into Git. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/secret-scanning-git-guide
[Secret Scanning: Stop Secrets From Leaking Into Git](https://www.devopsness.com/blog/secret-scanning-git-guide) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)
More from DevOps
Explore more articles in this category
NGINX CVE-2026-123007: An HTTP/2 RCE Back to 1.9.5. Patch to 1.30.7, and Retired ingress-nginx Gets No Fix
F5 fixed five NGINX memory-safety bugs on November 18, led by an HTTP/2 flow-control overflow present since 2015. Fixed versions, a config check that tells you which bugs you can reach, and what to do about ingress-nginx, which bundles a vulnerable NGINX and will never ship a patch.
Fix Git "Updates Were Rejected" on Push
Your push bounces because the remote moved on without you. Here is how to catch up cleanly, when to rebase versus merge, and when a force-push is actually safe.
Blue/Green Deploys for Stateful Services: A Postgres Cutover Story
Blue/green is easy for stateless services. We did it for our primary Postgres cluster with 3.2TB of data and ~8k connections. Here's exactly how — and what almost went wrong.
You might have missed
Evergreen posts worth revisiting.