Secret Leaks in Git: Set Up gitleaks, Key Rotation, and History Rewriting
A developer commits a .env file "just for a quick test". The commit gets amended, the file is deleted in the next commit, and everyone moves on. Six weeks later, the AWS access key inside that blob is still perfectly rea
A developer commits a .env file "just for a quick test". The commit gets amended, the file is deleted in the next commit, and everyone moves on. Six weeks later, the AWS access key inside that blob is still perfectly readable in git log -p, and it has already been indexed by three bots scanning public GitHub pushes.
This article walks through both halves of the problem: blocking future leaks with gitleaks in pre-commit and CI, and cleaning up a repository that is already compromised — revocation, rotation, and history rewriting with git filter-repo. No prior security tooling experience is assumed.
Why a leaked secret in Git is worse than it looks
Git is an append-only object database. Deleting a file in a new commit does not delete the blob; it just stops referencing it from the tip of the branch. The secret stays reachable through:
- the full commit history (
git log --all -p) - every clone, fork, and mirror made since the leak
- CI caches, build artifacts, and Docker layers that copied the repo
- GitHub/GitLab web caches, which can serve an orphaned commit by SHA for a long time
Public repositories are scanned continuously. Measured time-to-exploitation for an AWS key pushed to public GitHub is often under five minutes. Private repositories are not safe either: anyone with read access, any CI job, any compromised laptop, and any future open-sourcing of the repo exposes the secret.
The operational conclusion: once a secret hits a Git object, treat it as compromised, forever. Rewriting history is cleanup, not remediation. Rotation is remediation.
Part 1 — Detection: gitleaks in pre-commit and CI
gitleaks is a single Go binary that scans files and Git history against a set of regex + entropy rules (AWS keys, GCP service accounts, Slack tokens, private keys, JWTs, and ~170 more).
Install and run your first scan
# macOS
brew install gitleaks
# Linux (pin the version you test with)
VERSION=8.21.2
curl -sSL -o gitleaks.tar.gz \
"https://github.com/gitleaks/gitleaks/releases/download/v${VERSION}/gitleaks_${VERSION}_linux_x64.tar.gz"
tar -xzf gitleaks.tar.gz gitleaks && sudo install gitleaks /usr/local/bin/
gitleaks version
Two scan modes matter:
# Scan the working tree only (fast, no history)
gitleaks dir . --report-format json --report-path gitleaks-wt.json
# Scan the whole commit history (what an attacker would do)
gitleaks git . --log-opts="--all" \
--report-format json --report-path gitleaks-history.json
# Exit code: 0 = clean, 1 = leaks found, 2 = execution error
echo "exit=$?"
On gitleaks < 8.19 the equivalent commands are
gitleaks detect --source .andgitleaks protect --staged. Both still work in recent versions but print a deprecation notice.
A finding looks like this:
{
"RuleID": "aws-access-token",
"File": "deploy/terraform/dev.tfvars",
"Commit": "9c1f0f2a3b...",
"Author": "[email protected]",
"Date": "2024-11-03T09:12:44Z",
"Secret": "AKIA****************",
"Fingerprint": "9c1f0f2a3b...:deploy/terraform/dev.tfvars:aws-access-token:14"
}
Tune the rules with .gitleaks.toml
Committed test fixtures and example files generate false positives. Handle them with an allowlist keyed on the fingerprint, never by disabling whole rules:
# .gitleaks.toml
[extend]
useDefault = true
[[rules]]
id = "internal-api-key"
description = "Internal platform API key"
regex = '''(?i)plat_(live|test)_[0-9a-z]{32}'''
keywords = ["plat_live_", "plat_test_"]
[allowlist]
description = "Known-safe placeholders and fixtures"
paths = [
'''(^|/)test/fixtures/''',
'''(^|/)docs/examples/''',
]
regexes = [
'''AKIAIOSFODNN7EXAMPLE''', # AWS doc placeholder
'''(?i)(changeme|dummy|placeholder)''',
]
Review every allowlist entry in code review — an allowlist is the easiest place to hide a real leak.
Block the commit: pre-commit hook
pre-commit runs hooks locally before the commit object is created. This is the cheapest possible control: the secret never becomes a Git object.
# .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.21.2
hooks:
- id: gitleaks
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: detect-private-key
- id: check-added-large-files
args: ["--maxkb=512"]
pipx install pre-commit # or: pip install --user pre-commit
pre-commit install # writes .git/hooks/pre-commit
pre-commit run --all-files # first full pass
Now a bad commit fails locally:
$ echo 'AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' >> .env
$ git add .env && git commit -m "wip"
gitleaks.................................................................Failed
- hook id: gitleaks
- exit code: 1
Local hooks are advisory: git commit --no-verify bypasses them, and nothing forces a new contributor to run pre-commit install. That is why CI enforcement is mandatory.
Enforce in CI: GitHub Actions
Run gitleaks on every pull request over the full history of the PR branch. Note fetch-depth: 0 — without it you only get a shallow clone and history scanning is useless.
# .github/workflows/secret-scan.yml
name: secret-scan
on:
pull_request:
push:
branches: [main]
schedule:
- cron: "17 3 * * 1" # weekly full re-scan
permissions:
contents: read
jobs:
gitleaks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install gitleaks
run: |
VERSION=8.21.2
curl -sSL -o gl.tar.gz \
"https://github.com/gitleaks/gitleaks/releases/download/v${VERSION}/gitleaks_${VERSION}_linux_x64.tar.gz"
tar -xzf gl.tar.gz gitleaks && sudo install gitleaks /usr/local/bin/
- name: Scan history
run: |
gitleaks git . --log-opts="--all" \
--redact \
--report-format sarif --report-path gitleaks.sarif
- name: Upload SARIF
if: always()
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: gitleaks.sarif
--redact keeps the secret value out of CI logs — otherwise you leak it a second time into a log store that is often more widely readable than the repo.
Make this job a required status check on main (Settings → Branches → Branch protection rules), otherwise it is just a red cross people learn to ignore.
gitleaks vs trufflehog
They are complementary:
- gitleaks — fast, regex/entropy based, great as a blocking gate. Low latency, some false positives.
- trufflehog — has verified detectors: it calls the provider API to check whether a candidate credential is actually still live. Slower, but the output is a prioritized incident list.
A good pattern: gitleaks blocks PRs, trufflehog runs nightly on the full org to triage what is genuinely exploitable.
# Only report credentials confirmed as still valid
docker run --rm trufflesecurity/trufflehog:latest \
github --repo=https://github.com/acme/platform --only-verified
Scheduled scan from inside the cluster (OpenShift/Kubernetes)
If your Git server is internal, run the scan as a CronJob next to it:
apiVersion: batch/v1
kind: CronJob
metadata:
name: gitleaks-nightly
namespace: security-scanning
spec:
schedule: "0 2 * * *"
concurrencyPolicy: Forbid
jobTemplate:
spec:
backoffLimit: 1
template:
spec:
restartPolicy: Never
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- name: gitleaks
image: ghcr.io/gitleaks/gitleaks:v8.21.2
args:
- "git"
- "/workspace/repo"
- "--log-opts=--all"
- "--redact"
- "--report-format=json"
- "--report-path=/tmp/report.json"
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
resources:
requests: { cpu: 200m, memory: 256Mi }
limits: { cpu: "1", memory: 1Gi }
volumeMounts:
- { name: workspace, mountPath: /workspace }
- { name: tmp, mountPath: /tmp }
initContainers:
- name: clone
image: registry.access.redhat.com/ubi9/toolbox:latest
command: ["/bin/sh", "-c"]
args:
- git clone --mirror "$GIT_URL" /workspace/repo
env:
- name: GIT_URL
valueFrom:
secretKeyRef: { name: scanner-git-url, key: url }
volumeMounts:
- { name: workspace, mountPath: /workspace }
volumes:
- { name: workspace, emptyDir: {} }
- { name: tmp, emptyDir: {} }
Part 2 — Handling a real incident
gitleaks just flagged a live Kubernetes service account token and an AWS key in main. Work in this order; do not start with the history rewrite.
Step 1 — Contain and revoke (minutes, not hours)
The only action that stops exploitation is invalidating the credential at the provider.
# AWS: deactivate first (reversible), then delete once traffic is confirmed clean
aws iam update-access-key --user-name ci-deployer \
--access-key-id AKIAEXAMPLE1234567890 --status Inactive
# Check who used it over the exposure window
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=AccessKeyId,AttributeValue=AKIAEXAMPLE1234567890 \
--start-time 2024-11-03T00:00:00Z --max-results 50
aws iam delete-access-key --user-name ci-deployer \
--access-key-id AKIAEXAMPLE1234567890
For a Kubernetes/OpenShift service account token:
# Legacy (long-lived) token secrets: delete them, the SA token is immediately invalid
oc delete secret deployer-token-abcde -n production
# Modern bound tokens are short-lived; force new ones and restart consumers
oc delete pods -n production -l app=api --wait=false
# Check what the identity did
oc get events -n production --sort-by=.lastTimestamp | tail -50
Write down the exposure window (first commit date → revocation time) — you need it for the audit log review and any disclosure obligation.
Step 2 — Rotate and re-deploy
Generate a new credential and inject it through a path that never touches Git.
# Create the replacement secret imperatively (nothing written to disk)
read -rsp "New AWS secret key: " AWS_SK; echo
oc create secret generic aws-deployer \
--from-literal=AWS_ACCESS_KEY_ID=AKIANEWKEY0987654321 \
--from-literal=AWS_SECRET_ACCESS_KEY="$AWS_SK" \
--dry-run=client -o yaml | oc apply -f - -n production
unset AWS_SK
oc rollout restart deployment/api -n production
oc rollout status deployment/api -n production --timeout=180s
Better: stop storing the value in the cluster at all and let the External Secrets Operator pull it from Vault or AWS Secrets Manager. The manifest you commit contains references only:
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: aws-deployer
namespace: production
spec:
refreshInterval: 1h
secretStoreRef:
name: vault-backend
kind: SecretStore
target:
name: aws-deployer
creationPolicy: Owner
data:
- secretKey: AWS_ACCESS_KEY_ID
remoteRef:
key: platform/prod/aws
property: access_key_id
- secretKey: AWS_SECRET_ACCESS_KEY
remoteRef:
key: platform/prod/aws
property: secret_access_key
Rotation then becomes a Vault write plus a refresh — no commit, no leak surface.
Step 3 — Rewrite the history with git filter-repo
git filter-repo is the supported replacement for the deprecated git filter-branch. It rewrites every affected commit, which changes all SHAs from the first rewritten commit onward. Coordinate with the team: everyone re-clones.
pipx install git-filter-repo # or: pip install --user git-filter-repo
# Always work on a fresh mirror clone, never your working checkout
git clone --mirror [email protected]:acme/platform.git platform-mirror
cd platform-mirror
Option A — the file should never have existed:
git filter-repo --invert-paths \
--path .env \
--path deploy/terraform/dev.tfvars
Option B — the file must stay, but the value must be scrubbed:
cat > /tmp/replacements.txt <<'EOF'
AKIAEXAMPLE1234567890==>AWS_ACCESS_KEY_ID_REMOVED
regex:plat_live_[0-9a-z]{32}==>PLATFORM_KEY_REMOVED
EOF
git filter-repo --replace-text /tmp/replacements.txt
Verify, then publish:
gitleaks git . --log-opts="--all" --redact # must exit 0
git push --force --mirror origin
Then — and this is the part people forget:
- Delete every fork. A fork keeps the old objects; GitHub can even serve them through the upstream repo's network.
- Ask GitHub/GitLab support to garbage-collect cached orphaned commits (old SHAs stay accessible by URL otherwise).
- Expire open pull requests that reference rewritten commits.
- Tell every developer to re-clone; a
git pullon a rewritten branch produces a merge that reintroduces the old objects.
# Developer side: discard the old clone
cd .. && rm -rf platform && git clone [email protected]:acme/platform.git
For very large repos, BFG Repo-Cleaner is faster but less precise; filter-repo is the better default.
Security best practices
- Rotate first, rewrite second. History cleanup reduces exposure; only revocation ends it.
- Defense in depth: pre-commit (fast feedback) + required CI check (enforcement) + scheduled org-wide scan (drift). No single layer is enough.
-
Pin tool versions (
rev: v8.21.2, pinned action SHAs). A floatinglatestin a security gate is an unreviewed supply-chain dependency. -
Always use
--redactin CI, and restrict who can read scan artifacts and SARIF uploads. - Never store raw secrets in Git, even encrypted-by-convention. Use External Secrets Operator, Sealed Secrets, or Vault Agent injection; commit references, not values.
- Enable platform-side scanning: GitHub Secret Scanning with push protection, GitLab Secret Detection. They catch what your hooks miss and some providers auto-revoke on detection.
- Prefer short-lived credentials: OIDC federation between GitHub Actions and AWS/Azure/GCP removes static keys entirely; Kubernetes bound service account tokens expire by default.
- Enforce least privilege so a leaked credential has a small blast radius, and enable audit logging so you can answer "what did they do with it?".
-
Add
.env,*.pem,*.kubeconfig,*.tfvarsto.gitignoreand ship that file in your repo templates. - Write the runbook before the incident — contain, revoke, rotate, audit, rewrite, notify — and rehearse it once with a deliberately planted dummy key.
Conclusion
Secret leaks in Git are a question of when, not if. The tooling is cheap and the setup takes an afternoon:
- gitleaks in pre-commit stops most leaks before a Git object exists.
-
gitleaks as a required CI check with
fetch-depth: 0and--redactmakes the control non-bypassable. -
trufflehog
--only-verifiedon a schedule tells you which historical findings are actually live. - When a leak happens: revoke → rotate → audit the exposure window → rewrite with
git filter-repo→ delete forks → everyone re-clones. - Long term, remove the class of problem: external secret stores and OIDC short-lived credentials mean there is no static secret left to commit.
Start today with gitleaks git . --log-opts="--all" --redact on your main repository. Whatever it finds has been there for a while — and rotating it is a better Monday than reading about it in a breach report.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.