Tutorial
API Key Leaked in a GitHub Repo? What to Do, Step by Step
API key leaked in a GitHub repo? Revoke it first, check the logs, move secrets out of code, then decide if rewriting history or contacting Support is worth it.
If an API key leaked in a GitHub repo, the first move is to revoke or rotate it at the provider. Not to edit the file, not to force push. Everything else on this page comes after that, because a secret that’s been pushed is a secret somebody else may already have. This tutorial walks the steps in the order GitHub’s own documentation supports, and says plainly where each step helps and where it doesn’t. A companion post, GitHub secret scanning, Dependabot, TruffleHog and Gitleaks, covers the tooling that keeps this from happening again.
This is general guidance, not legal or compliance advice. If your organization has an incident process, follow that first and use this page to fill in the technical detail. The commands below come from the linked primary sources and were not run here, so test them on a throwaway copy before you use them on a real repository. Links, menu names and version numbers were last checked on 2026-11-12, and GitHub and the cloud providers change their docs, so confirm against the current pages.
Quick answer
Do these in order:
- Revoke or rotate the credential at the provider that issued it. If a short outage matters, create the replacement first, switch your app over, then revoke the old one.
- Check the logs for any use between the commit time and the revocation.
- Remove the secret from your current code and store it somewhere safer, such as a secrets manager or Actions secrets. For cloud access from Actions, OIDC federation can remove the stored secret entirely.
- Decide whether rewriting history is warranted. GitHub says a revoked secret “may be sufficient.”
- If it is warranted, make a backup copy first, clean the history with git-filter-repo, then force push. The force push cannot be undone.
- Contact GitHub Support only for the narrow cases it handles, after the clean push.
- Close the alert and tell your team.

This silent, captioned video of about one minute walks the seven steps in order, starting with revoking or rotating the key at the provider.
Why a pushed secret counts as compromised
Once a key sits in a Git history that anyone but you can read, you can’t know who copied it. GitHub’s guidance on partner-detected secrets is blunt: treat any secret GitHub messages you about as public and compromised.
How fast does abuse start? GitHub’s docs give no number, and neither does AWS’s page on how it responds to exposed credentials. The figures floating around come from secondary sources. A 2020 honeypot experiment reported by Comparitech saw first abuse of an AWS key in a public repo in about a minute, and a research note from Cloud Security Alliance Labs cites a 2023 Orca result of two minutes. Those are secondary reports, not provider documentation, and the original studies weren’t checked for this post, so read them as “can happen within minutes.”
Every minute you spend polishing history is a minute the live credential stays valid.
Step 1: revoke or rotate the credential
GitHub’s guide to removing sensitive data makes revoking or rotating the first step for a secret. Its leaked secret tutorial adds that removing the secret from your codebase is not enough on its own, and that the provider is “always the most reliable source of truth” on whether a secret is still active.
Do it at the provider: the AWS console, the Entra or Azure portal, Google Cloud IAM, the SaaS dashboard that issued the key. If revoking would cause downtime, GitHub suggests creating the replacement first, switching the application over, then revoking the old one. Then update every consumer: CI secrets, deploy keys, apps and integrations.
On AWS, an older AWS Security Blog post recommends disabling an exposed access key before deleting it, so you can restore it if something breaks. It also notes that rotating an IAM user’s key doesn’t invalidate temporary credentials already issued from it.
Don’t count on auto-revocation
Some providers do revoke leaked keys for you, but it’s patchy:
- GitHub says it automatically revokes GitHub personal access tokens leaked in public repositories.
- For other secret types that match a partner pattern in a public repo, GitHub reports the leak to the provider, “who may immediately revoke” it. What the provider then does is up to the provider.
- AWS says it applies quarantine policies to a publicly exposed key, which is not a full disable, and opens a support case. It states no timeframe.
- Google Cloud has an organization policy that can auto-disable detected leaked service account keys, but Google says it doesn’t guarantee detection and that if a key was committed you must delete it in IAM as quickly as possible.
If the leaked token is a GitHub personal access token in a private repo, GitHub’s tutorial describes a “Report leak” button (public preview) that asks GitHub to revoke it. The page advises rotating first so your workflows do not break.
Partner alerts also don’t show up in your repository’s alert list, so an empty list proves little.
Step 2: find out whether anyone used it
A revoked key can still have done damage before you revoked it. Check the logs for the window between the commit and the revocation, and treat any use that wasn’t yours as an incident.
GitHub. The personal security log, organization audit log and enterprise audit log show activity on your account. According to GitHub’s tutorial, the organization and enterprise logs can be searched for events by an access token.
AWS. The IAM console shows an “Access key last used” column, and there’s a credential report. You can also ask from the command line (not run here, with the AWS documentation’s example key ID):
# not run here
aws iam get-access-key-last-used --access-key-id AKIAIOSFODNN7EXAMPLE
For what the key actually did, search CloudTrail. See AWS’s page on managing access keys.
Azure and Entra. The Microsoft Entra sign-in logs include service principal sign-ins and managed identity sign-ins. If the leaked secret guarded a Key Vault, its AuditEvent logs record data-plane access, but you have to enable logging to a storage account for them to exist.
Google Cloud. Cloud Audit Logs keep Admin Activity entries on by default. Data Access logs are off by default except for BigQuery, so absence of data access entries may only mean nobody turned them on.
Also look for new users, keys or resources you did not create.
Step 3: move the secret out of the code
Now fix the cause. Remove the secret from the current code in a normal commit and put the new one somewhere that isn’t the repository. Which place depends on what the secret is.
Secrets managers
Azure Key Vault stores secrets, keys and certificates, authenticated through Entra ID and Azure RBAC. AWS Secrets Manager lets your code fetch credentials at runtime instead of hardcoding them, and supports automatic rotation. Google Secret Manager keeps versioned secrets under IAM with audit logging. Google says not to store service account keys in it, and to avoid keys altogether where you can.
GitHub Actions secrets and environments
Actions secrets can live at the repository, environment or organization level. They are not passed to workflows triggered from forks (except GITHUB_TOKEN), and log redaction is best effort, so never print one. Use these for CI values that can’t be federated.
OIDC federation, so there’s no stored cloud secret
For cloud access from Actions, the better answer is often to store no long-lived cloud secret at all. With OpenID Connect in GitHub Actions, the runner requests a short-lived token and your cloud provider trusts its claims. The job needs:
# workflow snippet, not run here
permissions:
id-token: write
On Azure, the trust record is a federated identity credential. It lives in Microsoft Entra ID, attaches to an app registration or a user-assigned managed identity, and says which external token (issuer, subject and audience) Entra should accept. The workload swaps the GitHub token for an Entra access token, so there’s no secret to leak. Subjects follow patterns like these:
# subject patterns, shown for illustration, not run here
repo:ORG/REPO:environment:NAME
repo:ORG/REPO:ref:refs/heads/BRANCH
repo:ORG/REPO:pull_request
Per Microsoft’s guide to creating the trust, there’s a limit of 20 per app or identity, no wildcards, and a wrong subject fails silently. GitHub’s Azure guide uses the azure/login action and requires at least one trust condition.
AWS and Google Cloud follow the same idea. GitHub’s AWS guide has you add an IAM OIDC provider for token.actions.githubusercontent.com, write a role trust policy and use aws-actions/configure-aws-credentials. The Google Cloud guide uses a Workload Identity Pool and provider, google-github-actions/auth, and a service account with roles/iam.workloadIdentityUser.
One change matters if you create new repositories. For repos created after July 15, 2026 (and renamed or transferred ones, per GitHub’s changelog), the OIDC sub claim switched to an immutable format that includes numeric IDs, like repo:OWNER@OWNER-ID/REPO@REPO-ID:.... Older repos keep the name-only format unless they opt in, and this applies on github.com only. A trust condition written for the old name-only subject will not match a new repo’s token. GitHub’s OIDC reference has the details.
Federation isn’t a universal replacement, though. It covers cloud access from Actions, and it does not cover third-party API keys. A Stripe key, an OpenAI key or a database password still needs a vault or an Actions secret, and federation does nothing for a secret that’s already leaked. That one still needs step 1.
What about .env files?
GitHub lists .gitignore and environment variables as prevention. But .gitignore does not untrack a file Git already tracks and does nothing for history. OWASP’s secrets management cheat sheet also warns that environment variables are generally accessible to all processes and may land in logs or system dumps, so it suggests them only when other injection methods aren’t possible.
Step 4: decide whether to rewrite history
You may not need to. GitHub says that once a secret is revoked, that “may be sufficient,” and that a further history rewrite “may not be warranted.” GitHub’s tutorial calls a rewrite destructive and puts cleanup at step 7 of 9, after rotation and log review.
Rewriting is the right call when the exposed data cannot be rotated, such as personal information or proprietary content, or when your compliance requirements say the data has to come out of the history. The side effects GitHub lists are real:
- Commit hashes change.
- Open pull requests get different diffs and comments on the old diff can be lost, so merge or close them first. Closed pull requests built on later history get broken diffs.
- Commit and tag signatures are removed, and branch protection may need lifting.
- Collaborators with old clones can bring the secret back by pulling and pushing.
Step 5: clean the history with git-filter-repo
If you’ve decided to rewrite, the tool GitHub documents is git-filter-repo. Its manual repeats the point that you should revoke and rotate first. Start from a fresh clone, and use a version of git-filter-repo that supports --sensitive-data-removal. GitHub’s page requires 2.47 or later for that flag.
Do this in a fresh clone, never in your only copy. GitHub says that until you push, you can discard the clone and start over, but once you move on to the next step the rewrite is irreversible. Before you push, keep an untouched backup of the original repository somewhere private (a second clone, for example). The backup still contains the secret, so protect it and delete it once you’re done.
To remove a file, use its full path in Git (repeat for any other path the file ever had):
# not run here
git-filter-repo --sensitive-data-removal --invert-paths --path PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA
To replace text instead, put the strings in a file, one per line, and point the tool at it. That file holds the secret itself, so keep it outside the repository, as the ../ path in GitHub’s example does, and delete it afterwards:
# not run here
git-filter-repo --sensitive-data-removal --replace-text ../passwords.txt
By default each line is matched literally and replaced with ***REMOVED***. You can prefix a line with regex: or glob:, or write old==>new for a custom replacement. None of these commands were run here.
Verify that the data is gone before you push. The filter-repo manual suggests these checks:
# not run here
git log --all --name-status -- FILE
git log -S"STRING" --all -p --
The --sensitive-data-removal mode also reports the first changed commits and any orphaned Git LFS objects. Keep that output for Support. To count affected pull requests:
# not run here
grep -c '^refs/pull/.*/head$' .git/filter-repo/changed-refs
Then push every ref, not only your current branch. This is the irreversible step. It overwrites the remote’s branches, tags and other refs with your local ones, including anything pushed by others since you cloned, so tell your team to stop pushing first and check you are in the cleaned clone:
# not run here
git push --force --mirror origin
GitHub notes that --force is already implied by --mirror, and includes it as a reminder that this discards other people’s pushes. Protected branches may need protection lifted for a while. Expect the refs/pull/* refs to fail, since GitHub makes them read-only. That’s expected, and it’s why Support has a role in step 6.
Clean up the other clones
You can’t clean anyone else’s clone. The easiest fix is for each person to delete the old clone and clone again, after copying out or pushing any work they haven’t saved elsewhere. If someone has unpushed work, the filter-repo manual gives a longer route: delete all tags, run git fetch --prune --tags, rebase local work onto the new history (never merge), then run git reflog expire --expire=now --all and git gc --prune=now. Running git cat-file -t <first-changed-hash> should then error. Nobody should rerun your filter-repo command, because that produces different hashes, and people should stop pushing while this happens.
Forks
If the commit exists in a fork, it stays reachable there. GitHub’s advice is to coordinate with the fork owners and ask them to remove the data or delete the fork. GitHub cannot give you their contact details. And as the next step explains, deleting your own repo doesn’t fix this.
Step 6: ask GitHub Support only if you need to
After a force push, the old data can still be reachable through clones, forks, “cached views” on GitHub by commit SHA, and pull requests that reference it. GitHub Support can handle some of that, with conditions. Per GitHub’s guide, if all your non-pull-request refs are clean and no forks reference the data, Support will:
- delete or dereference the affected pull requests (deleting removes the conversation, reviews and diffs, while dereferencing keeps the body and comments but makes the historical diffs inaccessible, and sensitive text quoted in comments remains),
- run server-side garbage collection,
- remove cached views,
- purge orphaned LFS objects.
You submit through the GitHub Support portal with the owner and repo name, the number of affected pull requests, the “First Changed Commit(s)” from the filter-repo output, and any orphaned LFS file.
Now the limit, which GitHub states in an “Important” box. Support will not remove non-sensitive data, and it helps only where GitHub determines the risk can’t be mitigated by rotating affected credentials. For an API key you’ve already rotated, Support may decline. Never paste the secret into the ticket.
GitHub’s docs do not say whether Support will remove an unreachable commit by SHA on request, so don’t promise that to anyone.
Step 7: close the alert and tell the team
If secret scanning raised an alert, close it only after you’ve revoked or rotated the credential. GitHub’s tutorial uses the “Revoked” resolution for this. Closing an alert is only bookkeeping: it doesn’t revoke the credential or remove it from the repository. Leave a comment saying what you did.
Then tell the team what you rotated, whether the logs showed any use and whether history was rewritten. If it was, they need the re-clone instructions from step 5.
Clean up one more place: Actions logs and artifacts. If a workflow printed the secret, delete that run. Artifacts and logs are kept for 90 days by default (configurable), deleting a run deletes its artifacts, and the deletion is permanent. See GitHub’s pages on deleting a workflow run and removing artifacts.
What not to do
- Don’t only delete the file or run
git revert. The original commit stays in history. GitHub says a revert isn’t a valid way to undo adding sensitive data. - Don’t assume a force push fixes it. Clones, forks, pull request refs and cached views can all keep the data, and nothing un-leaks the secret.
- Don’t delete the repo and call it done. Per GitHub’s page on what happens to forks, deleting a public repository does not delete its forks, and Git data in a repository network can be reached from any repository in the same network, even after a fork is deleted. GitHub’s page on deleting a repository says nothing about purging sensitive data.
- Don’t rewrite history before you revoke. Every source puts revocation first.
- Don’t dismiss the alert as a false positive or “won’t fix” to make it go away.
- Don’t let colleagues pull and push from old clones, and don’t merge old branches. Rebase onto the cleaned history.
- Don’t rely on partner auto-revocation. It depends on the provider and GitHub does not guarantee it.
How to stop it happening again
GitHub’s prevention list covers .gitignore, environment variables or secret managers (it names Azure Key Vault, AWS Secrets Manager and HashiCorp Vault), pre-commit hooks such as git-secrets and gitleaks, avoiding git add ., and push protection.
Push protection blocks the push before the secret lands. If someone bypasses it, GitHub records an alert and an audit log entry and emails admins. Bypass reasons that close the alert are tests and false positives. “Fix it later” leaves it open.
Setting up scanners, hooks and push protection is its own job. The companion post, GitHub secret scanning, Dependabot, TruffleHog and Gitleaks, compares the options.
FAQ
What should you do first when an API key is leaked on GitHub?
Revoke or rotate the key at the provider that issued it. GitHub’s guidance puts that first, and its tutorial says removing the secret from your codebase isn’t enough. If downtime is a concern, create a replacement, switch your app over, then revoke the old key.
Does removing the secret from the repo fix the leak?
No. The secret stays in Git history, and a git revert does not undo it because the original commit remains. Revoking the credential is what ends the risk, and cleaning history is an optional extra step.
Do you need to rewrite Git history after a leak?
Not always. GitHub says a revoked secret may be sufficient. A rewrite makes more sense when the data can’t be rotated or compliance demands removal, and it changes hashes and breaks open pull requests.
Does force pushing remove a leaked secret from GitHub?
A force push of cleaned history fixes the branches and tags in your repository, but data can still be reachable through clones, forks, pull request refs and cached views on GitHub. Pull request refs under refs/pull/* cannot be force pushed at all. It also doesn’t make the secret safe again, so the key still has to be revoked.
Will GitHub Support remove a leaked key?
Only in limited cases. After you’ve pushed clean history, Support can delete or dereference affected pull requests, remove cached views, run garbage collection and purge orphaned LFS objects. GitHub says it helps only where the risk cannot be mitigated by rotating the credentials, so for a rotatable API key it may decline.
Does deleting a forked repo or the original repo remove the secret?
Not reliably. Deleting a public repository doesn’t delete its forks, and GitHub says Git data in a repository network can be accessed from any repository in that network, even after a fork is deleted. GitHub’s documentation does not describe deletion as a way to purge a secret, so ask fork owners to remove the data or delete their forks, and rotate the key.
Where to go next
Set up the guardrails before the next leak. The companion post on GitHub secret scanning, Dependabot, TruffleHog and Gitleaks covers scanning and push protection. For the primary sources behind this page, start with GitHub’s guide to removing sensitive data from a repository and the git-filter-repo manual.


