By Flavio
Use gitleaks to find API keys in Git history and files, tune it with a config, and block commits and pushes from coding agents with hooks and CI.
A coding agent trying to get an S3 upload working will sometimes paste the access key straight into the code. Or it commits a .env file “for local testing”, or drops a real API response with a token inside into a test fixture.
Agents commit fast. Once a key lands in a commit, it stays in your Git history even if the very next commit deletes it.
gitleaks is a small open source scanner that catches those keys before they get out. It reads your Git history, your files on disk, or anything you pipe into it, and exits with an error when it spots a secret.
That exit code is what makes it so useful. We can wire it in front of git commit, git push, and CI so leaks get blocked automatically.
I’m using gitleaks 8.30.1 throughout this tutorial. If you see gitleaks detect or gitleaks protect in older posts and READMEs, those were replaced in v8.19.0 by gitleaks git, gitleaks dir, and gitleaks stdin.
The old commands still work for now, though they’re hidden from --help.
How gitleaks finds a secret #
In version 8.30.1, gitleaks ships with 222 built-in rules. Each rule defines an id like aws-access-token or github-pat, a regular expression, and usually a list of keywords.
Keywords act as a fast pre-filter. A rule only runs its regex when the content contains one of its keywords, which keeps scans fast.
Some rules also check entropy, which measures how random a string looks. A repeated string like aaaaaaaaaaaaaaaaaaaaaaaa has very low entropy, while a real API key looks like random noise.
The generic-api-key rule uses entropy to catch secrets that don’t share a known prefix. You can test this right away with gitleaks stdin, which scans whatever you pipe into it:
echo 'API_KEY=aaaaaaaaaaaaaaaaaaaaaaaa' | gitleaks stdin --no-banner
3:08PM INF no leaks found
Now try the same variable with a random-looking value:
echo 'API_KEY=Zq7vN2xR8kL4pT9wM3bC6hJ1' | gitleaks stdin --no-banner
3:08PM WRN leaks found: 1
Before a match becomes a finding, gitleaks checks your allowlists, any gitleaks:allow comments, and the .gitleaksignore file. We’ll set those up later, and here is the full flow it follows:
gitleaks also decodes encoded text before running its rules. In 8.30.1, --max-decode-depth defaults to 5, so even a base64-encoded GitHub token gets caught:
echo "token: $(printf 'ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo' | base64)" | gitleaks stdin --no-banner -v
Finding: token: Z2hwX1I3eDJLcTlMbVQ0dkI4blpwVzNjWTZkRjFzSDVqQTBnVWVYbw==
Secret: Z2hwX1I3eDJLcTlMbVQ0dkI4blpwVzNjWTZkRjFzSDVqQTBnVWVYbw==
RuleID: generic-api-key
Entropy: 4.988171
Finding: ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo
Secret: ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo
RuleID: github-pat
Entropy: 5.221928
Every key in this post is fake. They match the rule patterns, but none of them belong to a real account.
Install gitleaks #
On macOS, install gitleaks with Homebrew:
brew install gitleaks
Check the installed version next, since some flags changed across releases:
gitleaks version
8.30.1
On Linux, you can grab a prebuilt binary from the releases page, such as gitleaks_8.30.1_linux_x64.tar.gz. There’s also a Docker image available.
Plant some secrets in a test repo #
Let’s build a small repo that repeats the mistakes coding agents tend to make. We’ll add a server, an S3 client with a hardcoded AWS key, and a .env file that gets committed and later untracked.
mkdir invoice-app && cd invoice-app
git init -b main
Here’s our S3 client in src/s3.js:
import { S3Client } from '@aws-sdk/client-s3'
export const s3 = new S3Client({
region: 'eu-west-1',
credentials: {
accessKeyId: 'AKIAZ4X7QF3NRT2LWVDK',
secretAccessKey: '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'
}
})
Next, let’s commit a .env file. Even a global .gitignore that lists .env won’t stop git add -f, and an agent trying to “make the tests work in CI” can run that exact command:
echo "GITHUB_TOKEN=ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo" > .env
git add -f .env
git commit -m "Add env for local testing"
A commit later, we notice the mistake and untrack the file:
git rm --cached .env
echo .env > .gitignore
git add .gitignore
git commit -m "Stop tracking .env"
.env is gone from the latest commit, but the commit that added it is still sitting in the history:
git log --oneline
99c5dba Stop tracking .env
9b83811 Add env for local testing
2341b2f Upload invoices to S3
5516d0b Initial server
Scan the Git history with gitleaks git #
gitleaks git runs git log -p under the hood and scans the diff of every commit. Run it from your repo root with -v so it prints the details of each finding:
gitleaks git -v .
○
│╲
│ ○
○ ░
░ gitleaks
Finding: ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo
Secret: ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo
RuleID: github-pat
Entropy: 5.221928
File: .env
Line: 1
Commit: 9b83811fe42a601ec72dd63a9206a7221df037a0
Author: Flavio Copes
Email: flavio@flaviocopes.com
Date: 2026-11-04T14:06:36Z
Fingerprint: 9b83811fe42a601ec72dd63a9206a7221df037a0:.env:github-pat:1
Finding: secretAccessKey: 'n8Vq2pXkT7mR4sLw9YbE1cHf6JdZ3aGu0oKiNyWe'
Secret: n8Vq2pXkT7mR4sLw9YbE1cHf6JdZ3aGu0oKiNyWe
RuleID: generic-api-key
Entropy: 5.321928
File: src/s3.js
Line: 7
Commit: 2341b2f6c2f5323b862d2ed9efc7f5ed1630b74d
Author: Flavio Copes
Email: flavio@flaviocopes.com
Date: 2026-11-04T14:06:31Z
Fingerprint: 2341b2f6c2f5323b862d2ed9efc7f5ed1630b74d:src/s3.js:generic-api-key:7
Finding: AKIAZ4X7QF3NRT2LWVDK
Secret: AKIAZ4X7QF3NRT2LWVDK
RuleID: aws-access-token
Entropy: 4.121928
File: src/s3.js
Line: 6
Commit: 2341b2f6c2f5323b862d2ed9efc7f5ed1630b74d
Author: Flavio Copes
Email: flavio@flaviocopes.com
Date: 2026-11-04T14:06:31Z
Fingerprint: 2341b2f6c2f5323b862d2ed9efc7f5ed1630b74d:src/s3.js:aws-access-token:6
3:06PM INF 4 commits scanned.
3:06PM INF scanned ~412 bytes (412 bytes) in 48ms
3:06PM WRN leaks found: 3
Without -v, gitleaks only prints the last three summary lines.
Each finding gives you everything you need to track it down:
RuleIDis the rule that matched. Here,generic-api-key(the entropy-based rule) caught the AWS secret because AWS secret keys don’t have a fixed prefix.File,Line, andCommitpoint straight to the patch. You can inspect it withgit show 9b83811.Findingis the full matched text, whileSecretis the specific part the rule extracted.Fingerprintis the unique id for this occurrence. We’ll use it later when we want to ignore a finding.
Look at that .env finding at the top. The file is no longer in the latest commit, so a plain grep of tracked files would miss it, whereas the history scan catches it immediately.
When you don’t want to scan the whole history, pass --log-opts to forward options to git log. For example, this checks only the last two commits:
gitleaks git --log-opts="HEAD~2..HEAD" .
We’ll use that same flag in our pre-push hook later.
Scan files on disk with gitleaks dir #
gitleaks dir scans files straight from disk without touching Git. It also has two aliases, gitleaks file and gitleaks directory:
gitleaks dir -v .
Finding: ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo
Secret: ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo
RuleID: github-pat
Entropy: 5.221928
File: .env
Line: 1
Fingerprint: .env:github-pat:1
Finding: secretAccessKey: 'n8Vq2pXkT7mR4sLw9YbE1cHf6JdZ3aGu0oKiNyWe'
Secret: n8Vq2pXkT7mR4sLw9YbE1cHf6JdZ3aGu0oKiNyWe
RuleID: generic-api-key
Entropy: 5.321928
File: src/s3.js
Line: 7
Fingerprint: src/s3.js:generic-api-key:7
Finding: AKIAZ4X7QF3NRT2LWVDK
Secret: AKIAZ4X7QF3NRT2LWVDK
RuleID: aws-access-token
Entropy: 4.121928
File: src/s3.js
Line: 6
Fingerprint: src/s3.js:aws-access-token:6
3:06PM INF scanned ~412 bytes (412 bytes) in 1.94ms
3:06PM WRN leaks found: 3
Notice the fingerprints don’t include a commit hash because Git isn’t involved. And .env still gets scanned even though it’s listed in .gitignore, since dir ignores .gitignore.
That makes dir great for checking a build folder before you deploy or upload it. If a bundler accidentally inlined a key into dist, this catches it:
gitleaks dir --no-banner dist
In short, use git to check if a secret was ever committed, and dir to check the files sitting on disk right now. stdin handles everything else, like command output an agent is about to paste into a GitHub issue.
Redact secrets in the output #
By default, gitleaks prints the secrets right in the scan output. That’s a problem when the output lands in CI logs or inside a coding agent’s transcript.
Add --redact to replace every secret with REDACTED:
echo "export GITHUB_TOKEN=ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo" | gitleaks stdin --no-banner --redact -v
Finding: REDACTED
Secret: REDACTED
RuleID: github-pat
Entropy: 5.221928
3:06PM INF scanned ~61 bytes (61 bytes) in 12.3ms
3:06PM WRN leaks found: 1
If you want to keep part of the value visible, pass a percentage instead. With --redact=20, gitleaks hides the last 20% of the string, leaving enough visible to tell two tokens apart:
gitleaks git -v --redact=20 .
Finding: ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5...
Secret: ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5...
RuleID: github-pat
I recommend always passing --redact in hooks and CI. Remember that hook output goes straight into the agent’s context.
Write reports in JSON, SARIF, or your own format #
Use --report-format (or -f) to pick an output format: json, csv, junit, sarif, or template. Then set --report-path (or -r) to the destination file, or - to write to stdout:
gitleaks git --redact -f json -r gitleaks-report.json .
In JSON, each finding is an object with extra metadata that the terminal doesn’t print, including the commit message:
{
"RuleID": "github-pat",
"Description": "Uncovered a GitHub Personal Access Token, potentially leading to unauthorized repository access and sensitive content exposure.",
"StartLine": 1,
"EndLine": 1,
"StartColumn": 14,
"EndColumn": 53,
"Match": "REDACTED",
"Secret": "REDACTED",
"File": ".env",
"SymlinkFile": "",
"Commit": "9b83811fe42a601ec72dd63a9206a7221df037a0",
"Entropy": 5.221928,
"Author": "Flavio Copes",
"Email": "flavio@flaviocopes.com",
"Date": "2026-11-04T14:06:36Z",
"Message": "Add env for local testing",
"Tags": [],
"Fingerprint": "9b83811fe42a601ec72dd63a9206a7221df037a0:.env:github-pat:1"
}
You can also export SARIF, the standard security report format that GitHub code scanning and many code editors understand:
gitleaks git --redact -f sarif -r gitleaks.sarif .
For a report meant for humans, you can write a Go template. gitleaks passes the list of findings as . and supports sprig helper functions like substr.
Here’s a minimal report.html.tmpl:
<!doctype html>
<meta charset="utf-8">
<title>gitleaks report</title>
<h1>{{ len . }} leaks found</h1>
<table>
<tr><th>Rule</th><th>File</th><th>Line</th><th>Commit</th><th>Message</th></tr>
{{- range . }}
<tr>
<td><code>{{ .RuleID }}</code></td>
<td><code>{{ .File }}</code></td>
<td>{{ .StartLine }}</td>
<td><code>{{ substr 0 7 .Commit }}</code></td>
<td>{{ .Message }}</td>
</tr>
{{- end }}
</table>
The --help output says --report-template implies the template format, but in 8.30.1 it fails with Unknown report format unless you also pass -f template:
gitleaks git --redact -f template --report-template report.html.tmpl -r report.html .
With a few lines of CSS added, the generated page looks like this:
Use the exit code #
gitleaks exits with 0 when it finds nothing and 1 when it detects a leak. That exit code is the whole integration API:
gitleaks git --no-banner . ; echo "exit: $?"
3:06PM INF 4 commits scanned.
3:06PM INF scanned ~412 bytes (412 bytes) in 54.8ms
3:06PM WRN leaks found: 3
exit: 1
You can override the leak exit code with --exit-code. Passing --exit-code 0 turns gitleaks into a report-only check, which is handy when you’re auditing an old repo for the first time.
Don’t use --exit-code 0 in hooks or CI, though. Runtime errors (like a bad report format or a path that isn’t a Git repo) also exit with 1, so any non-zero exit from gitleaks means you should stop and check what happened.
Ignore a finding with .gitleaksignore #
Some findings don’t need a fix. Maybe the key was revoked years ago, and rewriting Git history isn’t worth the disruption.
Copy the finding’s fingerprint into a .gitleaksignore file at your repo root:
9b83811fe42a601ec72dd63a9206a7221df037a0:.env:github-pat:1
The next scan skips it:
gitleaks git --no-banner .
3:07PM INF 4 commits scanned.
3:07PM INF scanned ~412 bytes (412 bytes) in 38.1ms
3:07PM WRN leaks found: 2
Because the fingerprint includes the commit hash, it only silences that single occurrence. If someone commits the same key again later, gitleaks flags it again.
Using a baseline on an older repo
If you’re adding gitleaks to an old repo full of historical findings, a baseline is much faster than ignoring fingerprints one by one. Save a JSON report of existing leaks, then pass it with --baseline-path so only new leaks trigger a failure.
By this point in our test repo, I’ve added a fifth commit that moves the keys in src/s3.js to environment variables (we’ll see that change at the end of the post):
gitleaks git -r baseline.json .
gitleaks git --baseline-path baseline.json .
3:09PM INF 5 commits scanned.
3:09PM INF scanned ~1093 bytes (1.09 KB) in 36.2ms
3:09PM INF no leaks found
Notice I left out --redact when generating baseline.json. In 8.30.1, a redacted report won’t match anything as a baseline, so every old finding shows up again.
Because that baseline file is unredacted, make sure you keep it out of your Git repository.
Allow one line with gitleaks:allow #
Sometimes a test file needs a string that looks like a real token. Add a gitleaks:allow comment to that line:
const key = 'ghp_Z9yX8wV7uT6sR5qP4oN3mL2kJ1iH0gFeDcBa' // gitleaks:allow
gitleaks skips that line in both git and dir scans.
Keep an eye on new gitleaks:allow comments during code review, though, because it’s also the easiest way for a coding agent to silence the scanner. In CI, you can pass --ignore-gitleaks-allow to force gitleaks to scan those lines anyway.
Extend the default config with .gitleaks.toml #
Place a .gitleaks.toml file at the root of the scanned path and gitleaks picks it up automatically. You can also point to a config explicitly with --config or the GITLEAKS_CONFIG environment variable.
In most projects, we want to keep the 222 default rules and layer our own rules and exceptions on top.
Suppose our app calls an internal API called Invoicely whose keys start with inv_live_. The built-in rules don’t know that prefix.
Here’s a script that uses one of those keys:
curl -u inv_live_7Hq2Lx9PzR4mK8vT3nW6: https://api.invoicely.dev/v1/invoices
With the default config, gitleaks misses it completely:
3:07PM INF scanned ~77 bytes (77 bytes) in 854µs
3:07PM INF no leaks found
Test fixtures have the opposite problem. test/fixtures/webhook.json contains a fake Stripe key, and gitleaks flags it on every run:
{
"type": "invoice.paid",
"api_key": "sk_test_51Hx8QeLkd9TmP2vRw7YzBn4cFg6JsAq"
}
We can solve both problems in .gitleaks.toml. Setting useDefault = true under [extend] keeps the built-in rules, [[rules]] adds our custom Invoicely rule, and [[allowlists]] skips the fixtures folder:
title = "invoice-app"
[extend]
useDefault = true
[[rules]]
id = "invoicely-live-key"
description = "Invoicely live API key"
regex = '''inv_live_[A-Za-z0-9]{20}'''
keywords = ["inv_live_"]
[[allowlists]]
description = "Fake keys in test fixtures"
paths = ['''^test/fixtures/''']
Run the scan again and gitleaks catches the Invoicely keys under the custom rule id while ignoring the Stripe test fixture:
gitleaks dir -v .
Finding: inv_live_7Hq2Lx9PzR4mK8vT3nW6
Secret: inv_live_7Hq2Lx9PzR4mK8vT3nW6
RuleID: invoicely-live-key
Entropy: 4.487123
File: scripts.sh
Line: 1
Fingerprint: scripts.sh:invoicely-live-key:1
Finding: ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo
Secret: ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo
RuleID: github-pat
Entropy: 5.221928
File: .env
Line: 1
Fingerprint: .env:github-pat:1
Finding: inv_live_7Hq2Lx9PzR4mK8vT3nW6
Secret: inv_live_7Hq2Lx9PzR4mK8vT3nW6
RuleID: invoicely-live-key
Entropy: 4.487123
File: src/billing.js
Line: 2
Fingerprint: src/billing.js:invoicely-live-key:2
3:07PM INF scanned ~700 bytes (700 bytes) in 1.8ms
3:07PM WRN leaks found: 3
A few extra details about .gitleaks.toml that help when writing custom rules:
- Rules use Go regular expressions, which don’t support lookaheads (like
(?=...)). - Setting
entropy = 3.5on a rule enables an entropy check, andsecretGroupchooses which regex capture group holds the secret. - Adding
disabledRules = ["generic-api-key"]under[extend]turns off a default rule if it produces too much noise in your codebase. - Allowlists also support
regexes,stopwords, andcommits, and you can addtargetRulesto scope an allowlist to specific rules. - Older configs use a single
[allowlist]table, but since v8.25.0 the format uses[[allowlists]]as an array.
You can check the README for every config field, and the default config is a great reference for rule examples.
Block commits with a pre-commit hook #
A history scan only tells you about a leak after it happened. A pre-commit hook stops the secret before the commit even exists.
Running gitleaks git --pre-commit --staged scans only your staged changes. Save this script as .git/hooks/pre-commit:
#!/bin/sh
gitleaks git --pre-commit --staged --redact --no-banner -v
Make it executable:
chmod +x .git/hooks/pre-commit
Now let’s try committing a file that contains a SendGrid key:
git add src/mailer.js
git commit -m "Send invoice emails"
Finding: apiKey: 'REDACTED'
Secret: REDACTED
RuleID: sendgrid-api-token
Entropy: 5.369111
File: src/mailer.js
Line: 2
Fingerprint: src/mailer.js:sendgrid-api-token:2
3:07PM INF 0 commits scanned.
3:07PM INF scanned ~124 bytes (124 bytes) in 17.8ms
3:07PM WRN leaks found: 1
Because the hook exited with 1, Git blocked the commit and left the repo untouched.
One thing to keep in mind: Git doesn’t share .git/hooks when someone clones the repo. To version your hooks with the project, put them in a folder like .githooks and run git config core.hooksPath .githooks in each clone.
I covered that shared-hooks setup in Git hooks for AI engineering.
With the pre-commit framework
If you already use the pre-commit framework, gitleaks provides a ready-made hook. Add this entry to .pre-commit-config.yaml:
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.30.1
hooks:
- id: gitleaks
Then install the hook:
pre-commit install
Run pre-commit autoupdate later to bump rev to the latest release. If you don’t want to install the gitleaks binary locally, you can use the gitleaks-docker hook id instead.
Block pushes with a pre-push hook #
A pre-commit hook only inspects staged files, whereas a pre-push hook checks every commit about to leave your machine. That boundary is what matters most, because once a key hits GitHub, you have to assume someone already grabbed it.
When you push, Git sends one line per ref to the hook on stdin with four values: local ref, local commit, remote ref, and remote commit. Our script scans the commit range between the remote commit and the local one.
For a brand-new branch, the remote commit hash is all zeros, so we scan everything reachable from the local commit instead. Save this as .git/hooks/pre-push and run chmod +x on it:
#!/bin/sh
zero=0000000000000000000000000000000000000000
while read local_ref local_sha remote_ref remote_sha; do
[ "$local_sha" = "$zero" ] && continue
if [ "$remote_sha" = "$zero" ]; then
range="$local_sha"
else
range="$remote_sha..$local_sha"
fi
gitleaks git --log-opts="$range" --redact --no-banner -v || {
echo "gitleaks found secrets in $range, push blocked"
exit 1
}
done
The first line inside the loop skips branch deletions, since there are no commits to scan there.
Here’s what happens on a repo after its initial push, once we add a new commit with a token in deploy.js:
git push
3:13PM INF Unknown SCM platform. Use --platform to include links in findings. host=
Finding: const token = 'REDACTED
Secret: REDACTED
RuleID: github-pat
Entropy: 5.221928
File: deploy.js
Line: 1
Commit: 871f239f633bff4cd69ad57177581b85cf19b558
Author: Flavio Copes
Email: flavio@flaviocopes.com
Date: 2026-11-04T14:13:33Z
Fingerprint: 871f239f633bff4cd69ad57177581b85cf19b558:deploy.js:github-pat:1
3:13PM INF 1 commits scanned.
3:13PM INF scanned ~57 bytes (57 bytes) in 21.7ms
3:13PM WRN leaks found: 1
gitleaks found secrets in 3592868135e4a808e004597699a1c98a7f24e2e3..871f239f633bff4cd69ad57177581b85cf19b558, push blocked
error: failed to push some refs to '../invoice-app.git'
That first info line appears only because this test remote is a local folder instead of GitHub or GitLab. Against a GitHub remote, --platform github adds clickable links to each finding.
Notice that gitleaks only scanned the single new commit, which keeps pushes fast even on large repositories.
When I tested the same hook on the first push of invoice-app, it scanned the entire history and blocked the push because of the AWS key in the second commit. That’s what we want, since fixing the latest file never removes a key from older commits.
Make sure a coding agent can’t skip the check #
Claude Code, Codex, and other coding agents run git commit and git push just like you do, so they trigger your Git hooks automatically. I like the pre-push hook because it covers every agent without any agent-specific config.
There is one gap, though. Both git commit and git push accept --no-verify, which bypasses your hooks completely:
git push --no-verify
php
To ../invoice-app.git
3592868..871f239 main -> main
That pushed the token right through. If an agent sees a hook fail, it can sometimes decide --no-verify is the quickest way past the error.
In Claude Code, we can block those flags directly in .claude/settings.json:
{
"permissions": {
"deny": [
"Bash(git push --no-verify:*)",
"Bash(git commit --no-verify:*)"
]
}
}
Running gitleaks in a Claude Code hook
We can also run gitleaks from an agent hook, which fires before the tool call runs regardless of which Git flags the agent passes.
A Claude Code PreToolUse hook receives the pending tool call as JSON on stdin. Exiting with code 2 blocks the command and feeds stderr back to the agent.
Save this script as .claude/hooks/gitleaks.sh:
#!/bin/sh
cmd=$(jq -r '.tool_input.command')
case "$cmd" in
*"git push"*|*"git commit"*)
gitleaks git --redact --no-banner >&2 || {
echo "gitleaks found secrets in the Git history. Do not push. Tell the user." >&2
exit 2
}
;;
esac
We can test it inside invoice-app by piping in the same JSON payload Claude Code sends:
echo '{"tool_name":"Bash","tool_input":{"command":"git push origin main"}}' | .claude/hooks/gitleaks.sh
3:08PM INF Unknown SCM platform. Use --platform to include links in findings. host=
3:08PM INF 5 commits scanned.
3:08PM INF scanned ~1093 bytes (1.09 KB) in 39ms
3:08PM WRN leaks found: 2
gitleaks found secrets in the Git history. Do not push. Tell the user.
That returned exit code 2, while an unrelated command like npm test passes through with 0. Register the hook in .claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/gitleaks.sh"
}
]
}
]
}
}
This script scans the entire history on every commit and push, which works fine for small repos. On a large repo, add --log-opts="@{u}..HEAD" so it only scans unpushed commits.
Even with local hooks in place, checks can still be bypassed in a fresh clone without hooks, a cloud sandbox, or a rushed push. So the final check runs on the server, completing the full chain:
Scan every push in GitHub Actions #
The official gitleaks-action runs gitleaks on every push and pull request, and posts comments directly on PR lines that contain leaks. Save this workflow as .github/workflows/gitleaks.yml:
name: gitleaks
on:
pull_request:
push:
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: gitleaks/gitleaks-action@v3
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Don’t skip fetch-depth: 0. By default, actions/checkout only fetches the latest commit, and gitleaks can’t scan history that wasn’t downloaded.
The action is free for personal repositories. On an organization repository, it requires a GITLEAKS_LICENSE secret from gitleaks.io.
If you prefer not to depend on the action, you can download the binary directly and upload a SARIF report to GitHub code scanning instead:
name: gitleaks
on:
pull_request:
push:
jobs:
scan:
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Install gitleaks
run: |
curl -sSL https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz | tar -xz gitleaks
sudo mv gitleaks /usr/local/bin/
- name: Scan
run: gitleaks git --redact --no-banner --ignore-gitleaks-allow -f sarif -r gitleaks.sarif .
- uses: github/codeql-action/upload-sarif@v4
if: always()
with:
sarif_file: gitleaks.sarif
Adding if: always() ensures GitHub still uploads the SARIF report when the scan step fails, which is the exact moment you need it. Don’t add continue-on-error or || true to the scan step, because a failing check is what blocks the merge.
I covered CI pipelines for agent-driven deployments in more detail in How to protect secrets when coding agents deploy your app.
Finally, mark this job as a required status check in your branch protection rules so nothing can merge past a leak. Here is how the four checks compare:
| Check | What it scans | Bypassed by --no-verify ? |
Where it runs |
|---|---|---|---|
pre-commit hook |
Staged files before the commit is written | Yes | Local repo |
pre-push hook |
New commits in remote..local (or full branch on first push) |
Yes | Local repo |
Claude Code PreToolUse hook +deny rules |
Full history (or @{u}..HEAD ) beforegit commit orgit push |
No | Inside Claude Code |
| GitHub Actions CI | Full history ( fetch-depth: 0 ) on pushes and pull requests |
No | GitHub runner |
What to do when gitleaks finds a real secret #
Rotate the key first, and rewrite Git history second.
If the commit was ever pushed, treat the key as compromised right away. Automated bots scan public GitHub pushes within minutes, and private repos still get cloned to laptops, CI runners, and agent sandboxes that a history rewrite won’t touch:
Rotating a key means creating a new one, deploying it to your app, and deleting the old one at the provider. In AWS you’ll find this in the IAM console, and on GitHub it’s under Settings, Developer settings, Personal access tokens.
While you’re in the provider dashboard, check the audit logs to see if anyone used the old key.
Next, pull the secret out of the source code. The S3 client should read both values from environment variables instead:
import { S3Client } from '@aws-sdk/client-s3'
export const s3 = new S3Client({
region: 'eu-west-1',
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
}
})
If the commit never left your machine
When the leak is still local, you can clean it up without touching the remote. If it’s in your latest commit, edit the file and amend it:
git add src/s3.js
git commit --amend --no-edit
If the secret is in an older local commit, run git rebase -i and edit that commit in place.
If the commit was already pushed
Once a commit has been pushed, rewrite the history with git filter-repo. Install it with brew install git-filter-repo, then run it inside a fresh clone (it refuses to rewrite a working repo unless you pass --force).
To strip a file out of every commit:
git filter-repo --invert-paths --path .env
To scrub specific secret values everywhere they appear, list them one per line in a file outside the repo, with an optional replacement after ==>:
AKIAZ4X7QF3NRT2LWVDK==>REDACTED
n8Vq2pXkT7mR4sLw9YbE1cHf6JdZ3aGu0oKiNyWe==>REDACTED
git filter-repo --replace-text ../secrets.txt
After the rewrite, git filter-repo removes the origin remote as a safety measure. Add it back and force-push all branches and tags:
git remote add origin git@github.com:flaviocopes/invoice-app.git
git push --force --all
git push --force --tags
Run gitleaks git again to confirm the history is clean. Every existing clone (including CI caches and agent worktrees) needs to be re-cloned, otherwise the next push can bring the old commits right back.
On GitHub, old commits can remain reachable through pull request refs and forks until GitHub support purges them. That’s one more reason to rotate first, since revoking the key is the only step that makes it useless right away.
I wrote about dealing with a leaked key back in 2019 in I posted my password / API key on GitHub, and that order of steps still holds.
Before making some of my small tools public, I ran gitleaks git across each repo’s full history, as I described in Things I let coding agents do unattended. With the pre-push hook and GitHub Actions job wired up, that same check runs automatically on every push instead of just once.
Want me to talk about your product? You can sponsor this site.