Rolling out gitleaks in GitHub Actions without blocking every pull request
Turning on gitleaks for an old repo can fail every pull request because of something committed years ago. Here is how I split it into a blocking scan of the PR's own commits, a report-only history scan with a job summary, and a pre-push hook, always with --redact.
Adding a secret scanner to a repo that has a few years of history is easy to get wrong. If the first version scans everything and fails on anything, then every pull request goes red because of a file somebody committed long before, and the person opening the PR can't fix it. A check that's always red gets turned off pretty quick.
When I added gitleaks to a backend repo at work, I split it up from day one. One job blocks a pull request only for secrets in the commits that pull request adds. A second job scans all history on a schedule and only reports. And every run uses --redact, so a failing build never prints the secret it caught.
In this blog we will look at both jobs, a pre-push hook that catches it even earlier, and one trap with shallow clones that made gitleaks say "no leaks found" when it hadn't scanned anything.
I tested everything here with gitleaks v8.30.1 on a throwaway git repo with fake GitHub tokens in it.
Why not the gitleaks GitHub Action
There's an official gitleaks/gitleaks-action, but for repos owned by an organisation it needs a GITLEAKS_LICENSE key (free, but you have to request it). User repos don't. I didn't want a licence secret just for this, so I run the gitleaks container directly with docker run. It is the same tool, and I control the flags.
Pin the image tag. I use ghcr.io/gitleaks/gitleaks:v8.30.1, not latest, so a new release with new rules doesn't turn your builds red on a random morning. Bump it on purpose. It sits at the top of the workflow with the triggers:
on:
pull_request:
push:
branches: [main]
schedule:
- cron: '30 2 * * 1' # Monday 02:30 UTC
workflow_dispatch:
permissions:
contents: read
env:
GITLEAKS_IMAGE: ghcr.io/gitleaks/gitleaks:v8.30.1
Job 1: block the PR on its own commits
gitleaks has a git mode that walks git log -p, and --log-opts passes options straight to git log. So you give it the range from the PR's base to its head:
pr-commits:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0 # the base commit must be in the clone
- name: Scan the PR commits
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
set -euo pipefail
# A missing base makes git log fail, and gitleaks then reports
# "0 commits scanned, no leaks found" with exit 0. Check first.
git cat-file -e "${BASE_SHA}^{commit}"
git cat-file -e "${HEAD_SHA}^{commit}"
echo "Scanning $(git rev-list --count --no-merges "$BASE_SHA..$HEAD_SHA") commit(s)"
docker run --rm -v "$PWD:/repo" -w /repo "$GITLEAKS_IMAGE" \
git /repo \
--log-opts="--no-merges $BASE_SHA..$HEAD_SHA" \
--redact \
--no-banner \
--exit-code 1 \
--report-format sarif \
--report-path /repo/gitleaks-pr.sarif
The SHAs go in through env instead of being pasted into the script with ${{ }}. It's a habit worth having for anything from the event payload.
--no-merges skips merge commits. When someone merges main into their branch, the merge commit itself brings no new code of its own, so I leave it out and the commit count in the log stays honest.
On my test repo, main had an old commit with a token in an .env file (deleted in the next commit, which doesn't help, it is still in history). The feature branch added a Go file with another token. The PR range scan found only the new one:
Finding: const token = "REDACTED"
Secret: REDACTED
RuleID: github-pat
File: client.go
Line: 3
Commit: c13f98a8e13aacf23abed9bb6b08245cdaebd5a0
...
INF 2 commits scanned.
WRN leaks found: 1
Exit code 1, so the job fails. Exactly what we want.
The shallow clone trap
actions/checkout fetches one commit by default. With that, the base SHA isn't in the clone and the range is invalid. I was expecting gitleaks to fail loudly. I cloned my test repo with --depth 1 and ran the same command:
ERR error="stderr is not empty"
INF 0 commits scanned.
INF scanned ~0 bytes (0) in 52.1ms
INF no leaks found
Exit code 0. Green. With --log-level debug you can see the real reason, fatal: Invalid revision range, but the job passes either way. That one honestly surprised me.
So two things. fetch-depth: 0 on the checkout, and the git cat-file -e lines before the scan. With set -e they stop the job when a commit is missing:
fatal: Not a valid object name 6fb4b787a97f9ad66fa9a49f9ca206c6083d92b4^{commit}
The rev-list --count line is just there so the log shows how many commits were checked. If that says 0 on a PR with commits, something's off.
Why --redact everywhere
Without --redact, gitleaks prints the full secret in the finding. I ran it once on the test repo itself to see, and there was the whole token in the output. CI logs are read by far more people than the code is, and on public repos by anyone. A failed check that publishes the key it just found is worse than no check.
--redact also covers the report files. In the JSON report both Secret and Match come out as REDACTED, so the artifact is safe to keep too.
Job 2: scan everything, report only
The full history scan runs on push to main, on a weekly schedule and by hand. It never fails the workflow:
full-history:
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
continue-on-error: true
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Scan all history
run: |
set -uo pipefail
docker run --rm -v "$PWD:/repo" -w /repo "$GITLEAKS_IMAGE" \
git /repo \
--redact \
--no-banner \
--exit-code 0 \
--report-format json \
--report-path /repo/gitleaks-history.json
- name: Write job summary
if: always()
run: python3 ci/leaksummary.py gitleaks-history.json >> "$GITHUB_STEP_SUMMARY"
--exit-code 0 makes gitleaks return 0 even with findings. continue-on-error is a second guard in case the tool itself fails. Nobody reads raw JSON artifacts though, so the useful part is the summary. Anything written to $GITHUB_STEP_SUMMARY shows up as Markdown on the run page:
rows = json.load(open(path))
print(f"**{len(rows)}** finding(s), values redacted. Rotate first, then clean up.")
print("| Findings | File | Rules |")
print("|---:|---|---|")
by_file = collections.defaultdict(collections.Counter)
for r in rows:
by_file[r["File"]][r["RuleID"]] += 1
for f, rules in sorted(by_file.items(), key=lambda kv: -sum(kv[1].values()))[:25]:
print(f"| {sum(rules.values())} | `{f}` | {', '.join(sorted(rules))} |")
On the test repo:
## Secrets in git history
**2** finding(s), values redacted. Rotate first, then clean up.
| Findings | File | Rules |
|---:|---|---|
| 1 | `client.go` | github-pat |
| 1 | `old.env` | github-pat |
Only file names, rule IDs and counts. The script never prints Secret or Match, even though they are redacted already. Belt and braces.
The "rotate first" line is there on purpose. Basically, deleting the file doesn't remove the secret, it's still in every clone. Rewriting history is a lot of pain for everyone with a checkout. Rotating the key at the provider makes the old value useless, which is the part that actually matters.
When the history list is empty, or you've added the leftover false positives to .gitleaksignore by fingerprint, you can make the full scan blocking too. Just change --exit-code 0 to 1 and drop continue-on-error.
A baseline, if you prefer one job
gitleaks can also ignore everything in an older report with --baseline-path. I tried it: made a report of the whole test repo, then scanned again with that report as the baseline, and it said no leaks found. It works, but you have to keep the baseline file in the repo and regenerate it, and I find the PR range easier to explain to people. If you have any doubts on which to pick, either is fine.
Catching it before the push
CI only sees a secret after it's on the server, and by then it's in the remote's history. A pre-push hook scans the same way, just for the commits you're pushing:
#!/usr/bin/env bash
# Block a push that adds a secret. Scans only the commits being pushed.
# Enable once per clone: git config core.hooksPath githooks
set -uo pipefail
zero=0000000000000000000000000000000000000000
rc=0
while read -r local_ref local_sha remote_ref remote_sha; do
[ "$local_sha" = "$zero" ] && continue # deleting a branch
if [ "$remote_sha" = "$zero" ]; then
range="--no-merges $local_sha --not --remotes" # new branch
else
range="--no-merges $remote_sha..$local_sha"
fi
if ! command -v gitleaks >/dev/null; then
echo "pre-push: gitleaks not installed, skipping secret scan" >&2
exit 0
fi
if ! gitleaks git . --log-opts="$range" --redact --no-banner --exit-code 1; then
echo "pre-push: secret found in commits for $remote_ref, push blocked" >&2
rc=1
fi
done
exit $rc
For a new branch there is no remote SHA, so --not --remotes limits it to commits no remote branch has yet. I tested it against a local bare repo: a clean commit pushed fine, a commit with a fake token was refused with pre-push: secret found in commits for refs/heads/f2, push blocked.
The hook lets the push through when gitleaks isn't installed. A hook that blocks people who don't have the tool just gets deleted, and anyone can skip it with --no-verify anyway. That's why it's a convenience and the CI job is the real gate.
If you're new to how jobs and triggers fit together, GitHub Actions from zero covers it. For the logging side of keeping secrets out of places, see failing the golang build when someone logs a password or token with zap.
Make pr-commits a required status check in branch protection, otherwise it's just a red cross people learn to ignore.