# Scan your repo for leaked secrets with gitleaks before an agent pushes

> 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.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2026-12-01 | Topics: [AI](https://flaviocopes.com/tags/ai/), [Git](https://flaviocopes.com/tags/git/) | Canonical: https://flaviocopes.com/gitleaks/

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](https://github.com/gitleaks/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:

```bash
echo 'API_KEY=aaaaaaaaaaaaaaaaaaaaaaaa' | gitleaks stdin --no-banner
```

```text
3:08PM INF no leaks found
```

Now try the same variable with a random-looking value:

```bash
echo 'API_KEY=Zq7vN2xR8kL4pT9wM3bC6hJ1' | gitleaks stdin --no-banner
```

```text
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:

```mermaid
flowchart TD
  accTitle: How gitleaks turns content into a finding
  accDescr: Content is filtered by rule keywords, matched against the rule regex, checked for entropy, then checked against allowlists, inline allow comments and the ignore file before it is reported as a finding.
  A[Commit patch, file or stdin] --> B{Contains a rule keyword?}
  B -- no --> X[Skip the rule]
  B -- yes --> C{Regex matches?}
  C -- no --> X
  C -- yes --> D{Entropy above the threshold?}
  D -- no --> X
  D -- yes --> E{Allowlist, gitleaks:allow or .gitleaksignore?}
  E -- yes --> X
  E -- no --> F[Finding, exit code 1]
```

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:

```bash
echo "token: $(printf 'ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo' | base64)" | gitleaks stdin --no-banner -v
```

```text
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:

```bash
brew install gitleaks
```

Check the installed version next, since some flags changed across releases:

```bash
gitleaks version
```

```text
8.30.1
```

On Linux, you can grab a prebuilt binary from the [releases page](https://github.com/gitleaks/gitleaks/releases), 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.

```bash
mkdir invoice-app && cd invoice-app
git init -b main
```

Here's our S3 client in `src/s3.js`:

```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:

```bash
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:

```bash
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:

```bash
git log --oneline
```

```text
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:

```bash
gitleaks git -v .
```

```text
    ○
    │╲
    │ ○
    ○ ░
    ░    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:

- `RuleID` is 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`, and `Commit` point straight to the patch. You can inspect it with `git show 9b83811`.
- `Finding` is the full matched text, while `Secret` is the specific part the rule extracted.
- `Fingerprint` is 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:

```bash
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`:

```bash
gitleaks dir -v .
```

```text
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:

```bash
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`:

```bash
echo "export GITHUB_TOKEN=ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo" | gitleaks stdin --no-banner --redact -v
```

```text
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:

```bash
gitleaks git -v --redact=20 .
```

```text
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:

```bash
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:

```json
{
  "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:

```bash
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](https://masterminds.github.io/sprig/) helper functions like `substr`.

Here's a minimal `report.html.tmpl`:

```html
<!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`:

```bash
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:

![An HTML gitleaks report listing three leaks: github-pat in .env line 1, aws-access-token in src/s3.js line 6 and generic-api-key in src/s3.js line 7, with commit hashes and messages](https://images.flaviocopes.com/gitleaks/html-report.webp?v=d46a2c0c)

## 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:

```bash
gitleaks git --no-banner . ; echo "exit: $?"
```

```text
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:

```text
9b83811fe42a601ec72dd63a9206a7221df037a0:.env:github-pat:1
```

The next scan skips it:

```bash
gitleaks git --no-banner .
```

```text
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):

```bash
gitleaks git -r baseline.json .
gitleaks git --baseline-path baseline.json .
```

```text
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:

```js
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:

```bash
curl -u inv_live_7Hq2Lx9PzR4mK8vT3nW6: https://api.invoicely.dev/v1/invoices
```

With the default config, gitleaks misses it completely:

```text
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:

```json
{
  "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:

```toml
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:

```bash
gitleaks dir -v .
```

```text
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.5` on a rule enables an entropy check, and `secretGroup` chooses 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`, and `commits`, and you can add `targetRules` to 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](https://github.com/gitleaks/gitleaks#configuration) for every config field, and the [default config](https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml) 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`:

```bash
#!/bin/sh
gitleaks git --pre-commit --staged --redact --no-banner -v
```

Make it executable:

```bash
chmod +x .git/hooks/pre-commit
```

Now let's try committing a file that contains a SendGrid key:

```bash
git add src/mailer.js
git commit -m "Send invoice emails"
```

```text
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](https://flaviocopes.com/git-hooks/).

### With the pre-commit framework

If you already use the [pre-commit](https://pre-commit.com) framework, gitleaks provides a ready-made hook. Add this entry to `.pre-commit-config.yaml`:

```yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.30.1
    hooks:
      - id: gitleaks
```

Then install the hook:

```bash
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:

```bash
#!/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`:

```bash
git push
```

```text
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:

```bash
git push --no-verify
```

```text
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`:

```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`:

```bash
#!/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:

```bash
echo '{"tool_name":"Bash","tool_input":{"command":"git push origin main"}}' | .claude/hooks/gitleaks.sh
```

```text
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`:

```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:

```mermaid steps
flowchart LR
  accTitle: The agent writes code
  accDescr: A coding agent writes code that contains an API key.
  A[Agent writes code]
%% step
flowchart LR
  accTitle: The pre-commit hook scans staged files
  accDescr: Before the commit is created, the pre-commit hook scans the staged files and can refuse the commit.
  A[Agent writes code] --> B[pre-commit: staged files]
%% step
flowchart LR
  accTitle: The pre-push hook scans new commits
  accDescr: Before the push, the pre-push hook scans every commit that is about to leave the machine.
  A[Agent writes code] --> B[pre-commit: staged files] --> C[pre-push: new commits]
%% step
flowchart LR
  accTitle: The agent hook catches bypasses
  accDescr: A Claude Code PreToolUse hook runs gitleaks before any git commit or git push command, even with no-verify, and permission rules deny no-verify.
  A[Agent writes code] --> D[Agent hook before git commands] --> B[pre-commit: staged files] --> C[pre-push: new commits]
%% step
flowchart LR
  accTitle: CI scans the full history
  accDescr: On GitHub, a CI job scans the whole history of every push and pull request and fails the check if anything slipped through.
  A[Agent writes code] --> D[Agent hook] --> B[pre-commit] --> C[pre-push] --> E[CI: full history on GitHub]
```

## Scan every push in GitHub Actions

The official [gitleaks-action](https://github.com/gitleaks/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`:

```yaml
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](https://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:

```yaml
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](https://flaviocopes.com/agent-deploy-secrets/).

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`) before `git commit` or `git 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:

```mermaid
flowchart TD
  accTitle: What to do when gitleaks finds a secret
  accDescr: If the finding is a real key, revoke and rotate it first. If the commit was never pushed, amend or rebase locally. If it was pushed, rewrite history with git filter-repo, force push and ask collaborators to re-clone. Fake keys go in an allowlist or the ignore file.
  A[gitleaks finding] --> B{Real key?}
  B -- no --> C[Allowlist, gitleaks:allow or .gitleaksignore]
  B -- yes --> D[Revoke and rotate the key]
  D --> E{Commit pushed?}
  E -- no --> F[Amend or rebase the local commits]
  E -- yes --> G[Rewrite history with git filter-repo]
  G --> H[Force push, re-clone everywhere]
  F --> I[Move the key to an env var or secret store]
  H --> I
```

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:

```js
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:

```bash
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](https://github.com/newren/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:

```bash
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 `==>`:

```text
AKIAZ4X7QF3NRT2LWVDK==>REDACTED
n8Vq2pXkT7mR4sLw9YbE1cHf6JdZ3aGu0oKiNyWe==>REDACTED
```

```bash
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:

```bash
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](https://flaviocopes.com/git-secrets/), 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](https://flaviocopes.com/agents-unattended/). With the pre-push hook and GitHub Actions job wired up, that same check runs automatically on every push instead of just once.
