Rotate first: deleting the commit does not un-leak the key
The instinct is to delete the file and push again. Resist it until the credential is dead. A secret that has reached a remote may already sit in someone else's clone, a fork, a CI cache or a cached page, and removing it from your branch removes none of those. GitHub's own guidance on removing sensitive data from a repository makes this step zero: revoke or rotate the credential before rewriting history, and note that once it can no longer be used, rewriting history may be unnecessary.
If the key can reach sensitive data or was pushed somewhere public, disable it now and accept the outage. Where the exposure is limited, you can create the replacement, deploy it, then disable the old one. Either way, disable rather than delete where the provider allows it, because a disabled key can be restored if something unexpected still depends on it. AWS makes the same point in its guidance on exposed access keys, a 2014 post whose console steps have aged but whose sequence has not: work out what the key can reach, disable it, consider temporary credentials already issued from it (rotating an IAM user's key does not revoke those), restore access with something safer, then review activity.
The same shape applies to a database password or an OAuth client secret: issue a new one, ship it, kill the old one. Do not wait for a quiet moment.
Check whether the key was used
Rotation stops future use. It does not tell you whether the key was already used, and that is the question the rest of your response depends on. Most providers expose two kinds of evidence: last-used metadata on the credential, and an activity log.
On AWS, last-used metadata is one command (the key ID below is the placeholder from AWS's own documentation):
aws iam get-access-key-last-used --access-key-id AKIAIOSFODNN7EXAMPLE
It returns the most recent use of the key, with service and region. AWS's access key documentation recommends CloudTrail for monitoring key usage and spotting unauthorised access, which is where you look for the full story rather than just the last event. Other providers have equivalents under names like audit log, API usage or token activity. Read them for anything that does not match your own systems: unfamiliar source addresses, services you do not use, resources you did not create, or new credentials and users you did not make.
What attackers do with a leaked key depends entirely on what the key is allowed to do. AWS's guidance puts it plainly: anyone holding the credentials can perform any action permitted by the policies attached to them, with launching an EC2 instance and storing objects in S3 as its examples. That is why the scope of the key matters as much as its exposure, and why this is a good moment to find out what yours could reach. If the answer is "personal data", tell whoever in your organisation handles breach notification now, because a leaked credential with access to personal data can start duties that run on a clock. This is not legal advice, and it is not a conclusion that anything happened; it is a reason to involve them early.
Our first 24 hours playbook covers the same questions.
Remove the secret from Git history, safely
Only now clean up. The goal is hygiene, not secrecy; rotation already handled that. GitHub documents git filter-repo as the tool, and its --sensitive-data-removal flag needs version 2.47 or later. Work in a fresh clone, because the tool rewrites history and is designed to bail out of a repository that does not look like one.
git clone https://github.com/YOUR-ORG/YOUR-REPO
cd YOUR-REPO
# Remove a file that contained a secret, from every commit
git-filter-repo --sensitive-data-removal --invert-paths --path path/to/leaky-file.env
# Or replace specific strings wherever they appear in text files
git-filter-repo --sensitive-data-removal --replace-text ../replacements.txt
The replacements file holds one expression per line. Per the git-filter-repo manual, lines are literal by default, accept regex: and glob: prefixes, and a match is replaced with ***REMOVED*** unless you add ==> and your own text. Keep that file out of the repository.
With --sensitive-data-removal, filter-repo first fetches every ref from origin (including refs/pull/*) so all of them are rewritten, and it keeps the origin remote so you can push straight back. Without that flag it removes origin as a safety measure. If the file was ever renamed or moved, add a --path for each old path.
Before you push: merge or close open pull requests, because their diffs will change. Expect every commit hash from the leak onwards to change, so pinned SHAs, release automation and signed commits and tags will break (filter-repo strips signatures). Closed pull requests will lose their diff view. Run it in a fresh clone, since the fetch step can overwrite local-only work. Once pushed, the rewrite cannot be undone.
GitHub's documented command is git push --force --mirror origin, which overwrites every branch, tag and ref and discards anything collaborators pushed in the meantime. Pushes to refs/pull/ will fail because GitHub treats those refs as read-only; GitHub expects those failures, and Support deals with refs/pull/*. To see how many pull request refs were affected, run grep -c '^refs/pull/.*/head$' .git/filter-repo/changed-refs. If other branches fail, branch protection is the likely cause, and you will need to lift it temporarily.
Tell your team before you push. Everyone with a clone must not merge or git pull the old history back in, since that can reintroduce the secret; GitHub recommends rebasing local work onto the new history, and a fresh clone is the safer route.
What a rewrite cannot reach: forks, clones, caches and pull requests
A rewrite changes your repository. It does not change copies. Per GitHub's documentation, commits remain in any fork that contains them, you cannot clean other people's clones, and commits may stay reachable by their SHA in cached views and through pull requests until GitHub removes them. For the pull-request and cached-view cases, GitHub Support can dereference or delete affected pull requests, run garbage collection on the server and remove cached views. You ask through the Support portal and include the repository, the number of affected pull requests and the first changed commits from the filter-repo output. Set expectations: GitHub says Support will only help where the risk cannot be mitigated by rotating credentials, and only once every reference except pull requests is clean and no fork still holds the data. For a rotated API key, expect the answer to be rotation.
If the key was ever public, treat it as burned permanently, whatever the repository looks like now.
Find the rest: scan the whole history, not just HEAD
One leaked key usually means more. A file you fixed in the latest commit still exists in earlier ones, and a scanner that reads only the working tree will report a clean repository. Scan every commit. Two open-source tools do this, and they work differently, so running both is reasonable.
Gitleaks matches rules against the content of the history. Its git mode runs over git log -p, and --log-opts lets you include every ref. --redact keeps the secrets themselves out of your terminal and logs:
gitleaks git -v --redact --log-opts="--all" .
(Older tutorials show gitleaks detect. It was deprecated in v8.19.0 and replaced by the git and dir modes.)
TruffleHog also tries to verify whether a detected credential is still live. For a local repository:
trufflehog git file://.
By default it reports verified, unverified and unknown results (the last are ones where verification failed because of an error), so read all three. TruffleHog verifies a candidate by calling the provider's API with it, so those calls will show up in that provider's logs and last-used data; add --no-verification if you are still investigating. Remember that a credential you have already revoked will no longer verify as live, so a quiet result after rotation is not the same as "nothing was ever there". Treat every hit as something to rotate, whether or not the tool could confirm it.
Look beyond the repository too: build logs, chat messages, tickets and container image layers.
Why a private repository is not a safe place for secrets
Private means "limited audience", not "safe". Everyone with read access holds a full copy of the history on their laptop, forks and clones multiply the copies, CI systems and third-party integrations read the repository, and a single compromised account exposes all of it at once. If a private repository is ever made public, every secret ever committed goes with it. Secrets belong in a secrets manager, injected at runtime, never in the tree.
Stop it happening again
Four layers, in order of how early they catch the problem.
Pre-commit hooks stop the secret before it is committed at all. Gitleaks documents a setup through the pre-commit framework: add the hook to .pre-commit-config.yaml, run pre-commit autoupdate to pick the current release, then pre-commit install.
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.30.1 # run "pre-commit autoupdate" to bump this
hooks:
- id: gitleaks
Hooks run on a developer machine, so they can be skipped. They are a first line, not the last.
GitHub secret scanning and push protection are the server-side layer. According to GitHub's security features overview, secret scanning alerts are free and enabled by default on public repositories, and push protection for users is on by default on GitHub.com for pushes to public repositories. On private repositories both need GitHub Secret Protection, a paid add-on that organisations on GitHub Team or GitHub Enterprise Cloud can buy. Check your own plan before assuming you are covered. Push protection also has a bypass: anyone with write access can override a block by giving a reason, which, for repository-level push protection, creates an alert and an audit event; bypasses of user-level protection do not raise alerts (about push protection), so review those bypasses rather than letting them pile up.
Short-lived credentials remove the thing that can leak. For CI, use OpenID Connect so a workflow exchanges a short-lived token with your cloud provider at run time instead of holding a stored key. GitHub describes the benefit directly: there are no duplicate cloud secrets stored in GitHub, and each token is valid for a single job and then expires (about OIDC). AWS likewise advises temporary credentials such as IAM roles over long-term access keys. A key that expires in an hour is a far smaller incident than one that never does.
Your .gitignore is not a control. It does nothing for a file already committed, a secret pasted into source or a force-added file. Treat it as tidiness and put the real control in the layers above.
Review the rest of the repository
Finding a string that looks like a key is half the job. The other half is putting it in context: what else sits beside it in your dependencies, infrastructure-as-code and CI configuration, and which finding to fix first. That is what our GitHub SAST engine is for. It reviews a repository across secrets (including git history), dependencies and SBOM, IaC, CI/CD configuration and static analysis, using eight agents, at $399 per scan. It reads code and history only; it does not test whether a credential still works, so confirming rotation stays with you. It will not find every secret, and no tool will, so keep the hooks and scanning above in place.
Our free GitHub Action is a different tool for a different job: a passive, read-only check of the public security posture of a domain you own. It does not read your repository's source or secrets, so it does not replace anything in this article. For the cloud side of a leaked key, our cloud penetration testing guide covers what an over-permissioned credential exposes.
The first hour in one paragraph
Revoke or rotate the key. Read its last-used data and activity log, and involve whoever handles breach notification if personal data was reachable. Rewrite history in a fresh clone, warn your team before the force-push, and ask GitHub Support to clear cached views and pull requests if the risk justifies it. Scan every commit with gitleaks and TruffleHog. Then add the hooks, server-side scanning and short-lived credentials that make the next one a non-event.
Frequently Asked Questions
Does deleting a commit remove the secret?
No. Deleting or rewriting a commit changes your repository, not the forks, clones, caches and pull-request refs that already hold the old objects. Revoke or rotate the credential first, then clean the history as hygiene.
What should I do first if I committed an API key to GitHub?
Revoke or rotate the key before anything else, then check the provider's last-used data and activity log for unexpected use. Only after that should you rewrite history with git filter-repo. GitHub's own guidance puts rotation before the history rewrite.
Is a private repo safe for secrets?
No. Everyone with access holds a full copy of the history, integrations and CI can read it, and one compromised account or later change to public exposes everything ever committed. Store secrets in a secrets manager and inject them at runtime.
How do I find other secrets hidden in my Git history?
Scan every commit, not just the latest. For example, gitleaks git -v --redact --log-opts="--all" . and trufflehog git file://. both read the full history. Rotate every real hit, whether or not a tool could confirm it was live.
Does GitHub secret scanning and push protection cost money?
According to GitHub's documentation, secret scanning alerts are free on public repositories, and push protection for users is on by default for pushes to public repositories. For private repositories both require GitHub Secret Protection, a paid add-on that organisations on GitHub Team or GitHub Enterprise Cloud can buy. Check your plan, as pricing and packaging can change.