{"slug": "scan-your-repo-for-leaked-secrets-with-gitleaks-before-an-agent-pushes", "title": "Scan your repo for leaked secrets with gitleaks before an agent pushes", "summary": "Gitleaks 8.30.1, an open source secret scanner, ships with 222 built-in rules and can block coding agents from committing or pushing leaked API keys by wiring its non-zero exit code in front of git commit, git push and CI, according to a tutorial by Flavio. The tutorial notes that gitleaks v8.19.0 replaced the older `gitleaks detect` and `gitleaks protect` commands with `gitleaks git`, `gitleaks dir` and `gitleaks stdin`, and that the tool's `--max-decode-depth` defaults to 5 so base64-encoded tokens are still caught. The scanner relies on keyword pre-filtering and entropy checks, with the `generic-api-key` rule flagging random-looking strings that lack a known prefix.", "body_md": "# Scan your repo for leaked secrets with gitleaks before an agent pushes\n\nBy [Flavio](https://flaviocopes.com/about/)\n\nUse 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.\n\nA 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.\n\nAgents commit fast. Once a key lands in a commit, it stays in your Git history even if the very next commit deletes it.\n\n[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.\n\nThat 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.\n\nI’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`.\n\nThe old commands still work for now, though they’re hidden from `--help`.\n\n## How gitleaks finds a secret\n\nIn 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.\n\nKeywords act as a fast pre-filter. A rule only runs its regex when the content contains one of its keywords, which keeps scans fast.\n\nSome 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.\n\nThe `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:\n\n```\necho 'API_KEY=aaaaaaaaaaaaaaaaaaaaaaaa' | gitleaks stdin --no-banner\n3:08PM INF no leaks found\n```\n\nNow try the same variable with a random-looking value:\n\n```\necho 'API_KEY=Zq7vN2xR8kL4pT9wM3bC6hJ1' | gitleaks stdin --no-banner\n3:08PM WRN leaks found: 1\n```\n\nBefore 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:\n\ngitleaks 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:\n\n```\necho \"token: $(printf 'ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo' | base64)\" | gitleaks stdin --no-banner -v\nFinding:     token: Z2hwX1I3eDJLcTlMbVQ0dkI4blpwVzNjWTZkRjFzSDVqQTBnVWVYbw==\nSecret:      Z2hwX1I3eDJLcTlMbVQ0dkI4blpwVzNjWTZkRjFzSDVqQTBnVWVYbw==\nRuleID:      generic-api-key\nEntropy:     4.988171\n\nFinding:     ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo\nSecret:      ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo\nRuleID:      github-pat\nEntropy:     5.221928\n```\n\nEvery key in this post is fake. They match the rule patterns, but none of them belong to a real account.\n\n## Install gitleaks\n\nOn macOS, install gitleaks with Homebrew:\n\n```\nbrew install gitleaks\n```\n\nCheck the installed version next, since some flags changed across releases:\n\n```\ngitleaks version\n8.30.1\n```\n\nOn 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.\n\n## Plant some secrets in a test repo\n\nLet’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.\n\n```\nmkdir invoice-app && cd invoice-app\ngit init -b main\n```\n\nHere’s our S3 client in `src/s3.js`:\n\n``` js\nimport { S3Client } from '@aws-sdk/client-s3'\n\nexport const s3 = new S3Client({\n  region: 'eu-west-1',\n  credentials: {\n    accessKeyId: 'AKIAZ4X7QF3NRT2LWVDK',\n    secretAccessKey: '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'\n  }\n})\n```\n\nNext, 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:\n\n```\necho \"GITHUB_TOKEN=ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo\" > .env\ngit add -f .env\ngit commit -m \"Add env for local testing\"\n```\n\nA commit later, we notice the mistake and untrack the file:\n\n```\ngit rm --cached .env\necho .env > .gitignore\ngit add .gitignore\ngit commit -m \"Stop tracking .env\"\n```\n\n`.env` is gone from the latest commit, but the commit that added it is still sitting in the history:\n\n```\ngit log --oneline\n99c5dba Stop tracking .env\n9b83811 Add env for local testing\n2341b2f Upload invoices to S3\n5516d0b Initial server\n```\n\n## Scan the Git history with `gitleaks git`\n\n`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:\n\n```\ngitleaks git -v .\n○\n    │╲\n    │ ○\n    ○ ░\n    ░    gitleaks\n\nFinding:     ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo\nSecret:      ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo\nRuleID:      github-pat\nEntropy:     5.221928\nFile:        .env\nLine:        1\nCommit:      9b83811fe42a601ec72dd63a9206a7221df037a0\nAuthor:      Flavio Copes\nEmail:       flavio@flaviocopes.com\nDate:        2026-11-04T14:06:36Z\nFingerprint: 9b83811fe42a601ec72dd63a9206a7221df037a0:.env:github-pat:1\n\nFinding:     secretAccessKey: 'n8Vq2pXkT7mR4sLw9YbE1cHf6JdZ3aGu0oKiNyWe'\nSecret:      n8Vq2pXkT7mR4sLw9YbE1cHf6JdZ3aGu0oKiNyWe\nRuleID:      generic-api-key\nEntropy:     5.321928\nFile:        src/s3.js\nLine:        7\nCommit:      2341b2f6c2f5323b862d2ed9efc7f5ed1630b74d\nAuthor:      Flavio Copes\nEmail:       flavio@flaviocopes.com\nDate:        2026-11-04T14:06:31Z\nFingerprint: 2341b2f6c2f5323b862d2ed9efc7f5ed1630b74d:src/s3.js:generic-api-key:7\n\nFinding:     AKIAZ4X7QF3NRT2LWVDK\nSecret:      AKIAZ4X7QF3NRT2LWVDK\nRuleID:      aws-access-token\nEntropy:     4.121928\nFile:        src/s3.js\nLine:        6\nCommit:      2341b2f6c2f5323b862d2ed9efc7f5ed1630b74d\nAuthor:      Flavio Copes\nEmail:       flavio@flaviocopes.com\nDate:        2026-11-04T14:06:31Z\nFingerprint: 2341b2f6c2f5323b862d2ed9efc7f5ed1630b74d:src/s3.js:aws-access-token:6\n\n3:06PM INF 4 commits scanned.\n3:06PM INF scanned ~412 bytes (412 bytes) in 48ms\n3:06PM WRN leaks found: 3\n```\n\nWithout `-v`, gitleaks only prints the last three summary lines.\n\nEach finding gives you everything you need to track it down:\n\n- `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.\n- `File` ,`Line` , and`Commit` point straight to the patch. You can inspect it with`git show 9b83811` .\n- `Finding` is the full matched text, while`Secret` is the specific part the rule extracted.\n- `Fingerprint` is the unique id for this occurrence. We’ll use it later when we want to ignore a finding.\n\nLook 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.\n\nWhen 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:\n\n```\ngitleaks git --log-opts=\"HEAD~2..HEAD\" .\n```\n\nWe’ll use that same flag in our pre-push hook later.\n\n## Scan files on disk with `gitleaks dir`\n\n`gitleaks dir` scans files straight from disk without touching Git. It also has two aliases, `gitleaks file` and `gitleaks directory`:\n\n```\ngitleaks dir -v .\nFinding:     ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo\nSecret:      ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo\nRuleID:      github-pat\nEntropy:     5.221928\nFile:        .env\nLine:        1\nFingerprint: .env:github-pat:1\n\nFinding:     secretAccessKey: 'n8Vq2pXkT7mR4sLw9YbE1cHf6JdZ3aGu0oKiNyWe'\nSecret:      n8Vq2pXkT7mR4sLw9YbE1cHf6JdZ3aGu0oKiNyWe\nRuleID:      generic-api-key\nEntropy:     5.321928\nFile:        src/s3.js\nLine:        7\nFingerprint: src/s3.js:generic-api-key:7\n\nFinding:     AKIAZ4X7QF3NRT2LWVDK\nSecret:      AKIAZ4X7QF3NRT2LWVDK\nRuleID:      aws-access-token\nEntropy:     4.121928\nFile:        src/s3.js\nLine:        6\nFingerprint: src/s3.js:aws-access-token:6\n\n3:06PM INF scanned ~412 bytes (412 bytes) in 1.94ms\n3:06PM WRN leaks found: 3\n```\n\nNotice 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`.\n\nThat 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:\n\n```\ngitleaks dir --no-banner dist\n```\n\nIn 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.\n\n## Redact secrets in the output\n\nBy 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.\n\nAdd `--redact` to replace every secret with `REDACTED`:\n\n```\necho \"export GITHUB_TOKEN=ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo\" | gitleaks stdin --no-banner --redact -v\nFinding:     REDACTED\nSecret:      REDACTED\nRuleID:      github-pat\nEntropy:     5.221928\n\n3:06PM INF scanned ~61 bytes (61 bytes) in 12.3ms\n3:06PM WRN leaks found: 1\n```\n\nIf 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:\n\n```\ngitleaks git -v --redact=20 .\nFinding:     ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5...\nSecret:      ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5...\nRuleID:      github-pat\n```\n\nI recommend always passing `--redact` in hooks and CI. Remember that hook output goes straight into the agent’s context.\n\n## Write reports in JSON, SARIF, or your own format\n\nUse `--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:\n\n```\ngitleaks git --redact -f json -r gitleaks-report.json .\n```\n\nIn JSON, each finding is an object with extra metadata that the terminal doesn’t print, including the commit message:\n\n```\n{\n  \"RuleID\": \"github-pat\",\n  \"Description\": \"Uncovered a GitHub Personal Access Token, potentially leading to unauthorized repository access and sensitive content exposure.\",\n  \"StartLine\": 1,\n  \"EndLine\": 1,\n  \"StartColumn\": 14,\n  \"EndColumn\": 53,\n  \"Match\": \"REDACTED\",\n  \"Secret\": \"REDACTED\",\n  \"File\": \".env\",\n  \"SymlinkFile\": \"\",\n  \"Commit\": \"9b83811fe42a601ec72dd63a9206a7221df037a0\",\n  \"Entropy\": 5.221928,\n  \"Author\": \"Flavio Copes\",\n  \"Email\": \"flavio@flaviocopes.com\",\n  \"Date\": \"2026-11-04T14:06:36Z\",\n  \"Message\": \"Add env for local testing\",\n  \"Tags\": [],\n  \"Fingerprint\": \"9b83811fe42a601ec72dd63a9206a7221df037a0:.env:github-pat:1\"\n}\n```\n\nYou can also export SARIF, the standard security report format that GitHub code scanning and many code editors understand:\n\n```\ngitleaks git --redact -f sarif -r gitleaks.sarif .\n```\n\nFor 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`.\n\nHere’s a minimal `report.html.tmpl`:\n\n```\n<!doctype html>\n<meta charset=\"utf-8\">\n<title>gitleaks report</title>\n<h1>{{ len . }} leaks found</h1>\n<table>\n  <tr><th>Rule</th><th>File</th><th>Line</th><th>Commit</th><th>Message</th></tr>\n  {{- range . }}\n  <tr>\n    <td><code>{{ .RuleID }}</code></td>\n    <td><code>{{ .File }}</code></td>\n    <td>{{ .StartLine }}</td>\n    <td><code>{{ substr 0 7 .Commit }}</code></td>\n    <td>{{ .Message }}</td>\n  </tr>\n  {{- end }}\n</table>\n```\n\nThe `--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`:\n\n```\ngitleaks git --redact -f template --report-template report.html.tmpl -r report.html .\n```\n\nWith a few lines of CSS added, the generated page looks like this:\n\n## Use the exit code\n\ngitleaks exits with `0` when it finds nothing and `1` when it detects a leak. That exit code is the whole integration API:\n\n```\ngitleaks git --no-banner . ; echo \"exit: $?\"\n3:06PM INF 4 commits scanned.\n3:06PM INF scanned ~412 bytes (412 bytes) in 54.8ms\n3:06PM WRN leaks found: 3\nexit: 1\n```\n\nYou 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.\n\nDon’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.\n\n## Ignore a finding with `.gitleaksignore`\n\nSome findings don’t need a fix. Maybe the key was revoked years ago, and rewriting Git history isn’t worth the disruption.\n\nCopy the finding’s fingerprint into a `.gitleaksignore` file at your repo root:\n\n```\n9b83811fe42a601ec72dd63a9206a7221df037a0:.env:github-pat:1\n```\n\nThe next scan skips it:\n\n```\ngitleaks git --no-banner .\n3:07PM INF 4 commits scanned.\n3:07PM INF scanned ~412 bytes (412 bytes) in 38.1ms\n3:07PM WRN leaks found: 2\n```\n\nBecause the fingerprint includes the commit hash, it only silences that single occurrence. If someone commits the same key again later, gitleaks flags it again.\n\n### Using a baseline on an older repo\n\nIf 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.\n\nBy 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):\n\n```\ngitleaks git -r baseline.json .\ngitleaks git --baseline-path baseline.json .\n3:09PM INF 5 commits scanned.\n3:09PM INF scanned ~1093 bytes (1.09 KB) in 36.2ms\n3:09PM INF no leaks found\n```\n\nNotice 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.\n\nBecause that baseline file is unredacted, make sure you keep it out of your Git repository.\n\n## Allow one line with `gitleaks:allow`\n\nSometimes a test file needs a string that looks like a real token. Add a `gitleaks:allow` comment to that line:\n\n``` js\nconst key = 'ghp_Z9yX8wV7uT6sR5qP4oN3mL2kJ1iH0gFeDcBa' // gitleaks:allow\n```\n\ngitleaks skips that line in both `git` and `dir` scans.\n\nKeep 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.\n\n## Extend the default config with `.gitleaks.toml`\n\nPlace 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.\n\nIn most projects, we want to keep the 222 default rules and layer our own rules and exceptions on top.\n\nSuppose our app calls an internal API called Invoicely whose keys start with `inv_live_`. The built-in rules don’t know that prefix.\n\nHere’s a script that uses one of those keys:\n\n```\ncurl -u inv_live_7Hq2Lx9PzR4mK8vT3nW6: https://api.invoicely.dev/v1/invoices\n```\n\nWith the default config, gitleaks misses it completely:\n\n```\n3:07PM INF scanned ~77 bytes (77 bytes) in 854µs\n3:07PM INF no leaks found\n```\n\nTest fixtures have the opposite problem. `test/fixtures/webhook.json` contains a fake Stripe key, and gitleaks flags it on every run:\n\n```\n{\n  \"type\": \"invoice.paid\",\n  \"api_key\": \"sk_test_51Hx8QeLkd9TmP2vRw7YzBn4cFg6JsAq\"\n}\n```\n\nWe 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:\n\n```\ntitle = \"invoice-app\"\n\n[extend]\nuseDefault = true\n\n[[rules]]\nid = \"invoicely-live-key\"\ndescription = \"Invoicely live API key\"\nregex = '''inv_live_[A-Za-z0-9]{20}'''\nkeywords = [\"inv_live_\"]\n\n[[allowlists]]\ndescription = \"Fake keys in test fixtures\"\npaths = ['''^test/fixtures/''']\n```\n\nRun the scan again and gitleaks catches the Invoicely keys under the custom rule id while ignoring the Stripe test fixture:\n\n```\ngitleaks dir -v .\nFinding:     inv_live_7Hq2Lx9PzR4mK8vT3nW6\nSecret:      inv_live_7Hq2Lx9PzR4mK8vT3nW6\nRuleID:      invoicely-live-key\nEntropy:     4.487123\nFile:        scripts.sh\nLine:        1\nFingerprint: scripts.sh:invoicely-live-key:1\n\nFinding:     ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo\nSecret:      ghp_R7x2Kq9LmT4vB8nZpW3cY6dF1sH5jA0gUeXo\nRuleID:      github-pat\nEntropy:     5.221928\nFile:        .env\nLine:        1\nFingerprint: .env:github-pat:1\n\nFinding:     inv_live_7Hq2Lx9PzR4mK8vT3nW6\nSecret:      inv_live_7Hq2Lx9PzR4mK8vT3nW6\nRuleID:      invoicely-live-key\nEntropy:     4.487123\nFile:        src/billing.js\nLine:        2\nFingerprint: src/billing.js:invoicely-live-key:2\n\n3:07PM INF scanned ~700 bytes (700 bytes) in 1.8ms\n3:07PM WRN leaks found: 3\n```\n\nA few extra details about `.gitleaks.toml` that help when writing custom rules:\n\n- Rules use Go regular expressions, which don’t support lookaheads (like `(?=...)` ).\n- Setting `entropy = 3.5` on a rule enables an entropy check, and`secretGroup` chooses which regex capture group holds the secret.\n- Adding `disabledRules = [\"generic-api-key\"]` under`[extend]` turns off a default rule if it produces too much noise in your codebase.\n- Allowlists also support `regexes` ,`stopwords` , and`commits` , and you can add`targetRules` to scope an allowlist to specific rules.\n- Older configs use a single `[allowlist]` table, but since v8.25.0 the format uses`[[allowlists]]` as an array.\n\nYou 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.\n\n## Block commits with a pre-commit hook\n\nA history scan only tells you about a leak after it happened. A pre-commit hook stops the secret before the commit even exists.\n\nRunning `gitleaks git --pre-commit --staged` scans only your staged changes. Save this script as `.git/hooks/pre-commit`:\n\n``` bash\n#!/bin/sh\ngitleaks git --pre-commit --staged --redact --no-banner -v\n```\n\nMake it executable:\n\n```\nchmod +x .git/hooks/pre-commit\n```\n\nNow let’s try committing a file that contains a SendGrid key:\n\n```\ngit add src/mailer.js\ngit commit -m \"Send invoice emails\"\nFinding:     apiKey: 'REDACTED'\nSecret:      REDACTED\nRuleID:      sendgrid-api-token\nEntropy:     5.369111\nFile:        src/mailer.js\nLine:        2\nFingerprint: src/mailer.js:sendgrid-api-token:2\n\n3:07PM INF 0 commits scanned.\n3:07PM INF scanned ~124 bytes (124 bytes) in 17.8ms\n3:07PM WRN leaks found: 1\n```\n\nBecause the hook exited with `1`, Git blocked the commit and left the repo untouched.\n\nOne 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.\n\nI covered that shared-hooks setup in [Git hooks for AI engineering](https://flaviocopes.com/git-hooks/).\n\n### With the pre-commit framework\n\nIf 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`:\n\n```\nrepos:\n  - repo: https://github.com/gitleaks/gitleaks\n    rev: v8.30.1\n    hooks:\n      - id: gitleaks\n```\n\nThen install the hook:\n\n```\npre-commit install\n```\n\nRun `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.\n\n## Block pushes with a pre-push hook\n\nA 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.\n\nWhen 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.\n\nFor 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:\n\n``` bash\n#!/bin/sh\nzero=0000000000000000000000000000000000000000\n\nwhile read local_ref local_sha remote_ref remote_sha; do\n  [ \"$local_sha\" = \"$zero\" ] && continue\n\n  if [ \"$remote_sha\" = \"$zero\" ]; then\n    range=\"$local_sha\"\n  else\n    range=\"$remote_sha..$local_sha\"\n  fi\n\n  gitleaks git --log-opts=\"$range\" --redact --no-banner -v || {\n    echo \"gitleaks found secrets in $range, push blocked\"\n    exit 1\n  }\ndone\n```\n\nThe first line inside the loop skips branch deletions, since there are no commits to scan there.\n\nHere’s what happens on a repo after its initial push, once we add a new commit with a token in `deploy.js`:\n\n```\ngit push\n3:13PM INF Unknown SCM platform. Use --platform to include links in findings. host=\nFinding:     const token = 'REDACTED\nSecret:      REDACTED\nRuleID:      github-pat\nEntropy:     5.221928\nFile:        deploy.js\nLine:        1\nCommit:      871f239f633bff4cd69ad57177581b85cf19b558\nAuthor:      Flavio Copes\nEmail:       flavio@flaviocopes.com\nDate:        2026-11-04T14:13:33Z\nFingerprint: 871f239f633bff4cd69ad57177581b85cf19b558:deploy.js:github-pat:1\n\n3:13PM INF 1 commits scanned.\n3:13PM INF scanned ~57 bytes (57 bytes) in 21.7ms\n3:13PM WRN leaks found: 1\ngitleaks found secrets in 3592868135e4a808e004597699a1c98a7f24e2e3..871f239f633bff4cd69ad57177581b85cf19b558, push blocked\nerror: failed to push some refs to '../invoice-app.git'\n```\n\nThat 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.\n\nNotice that gitleaks only scanned the single new commit, which keeps pushes fast even on large repositories.\n\nWhen 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.\n\n## Make sure a coding agent can’t skip the check\n\nClaude 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.\n\nThere is one gap, though. Both `git commit` and `git push` accept `--no-verify`, which bypasses your hooks completely:\n\n```\ngit push --no-verify\nphp\nTo ../invoice-app.git\n   3592868..871f239  main -> main\n```\n\nThat 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.\n\nIn Claude Code, we can block those flags directly in `.claude/settings.json`:\n\n```\n{\n  \"permissions\": {\n    \"deny\": [\n      \"Bash(git push --no-verify:*)\",\n      \"Bash(git commit --no-verify:*)\"\n    ]\n  }\n}\n```\n\n### Running gitleaks in a Claude Code hook\n\nWe can also run gitleaks from an agent hook, which fires before the tool call runs regardless of which Git flags the agent passes.\n\nA 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.\n\nSave this script as `.claude/hooks/gitleaks.sh`:\n\n``` bash\n#!/bin/sh\ncmd=$(jq -r '.tool_input.command')\n\ncase \"$cmd\" in\n  *\"git push\"*|*\"git commit\"*)\n    gitleaks git --redact --no-banner >&2 || {\n      echo \"gitleaks found secrets in the Git history. Do not push. Tell the user.\" >&2\n      exit 2\n    }\n    ;;\nesac\n```\n\nWe can test it inside `invoice-app` by piping in the same JSON payload Claude Code sends:\n\n```\necho '{\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"git push origin main\"}}' | .claude/hooks/gitleaks.sh\n3:08PM INF Unknown SCM platform. Use --platform to include links in findings. host=\n3:08PM INF 5 commits scanned.\n3:08PM INF scanned ~1093 bytes (1.09 KB) in 39ms\n3:08PM WRN leaks found: 2\ngitleaks found secrets in the Git history. Do not push. Tell the user.\n```\n\nThat returned exit code `2`, while an unrelated command like `npm test` passes through with `0`. Register the hook in `.claude/settings.json`:\n\n```\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"${CLAUDE_PROJECT_DIR}/.claude/hooks/gitleaks.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\nThis 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.\n\nEven 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:\n\n## Scan every push in GitHub Actions\n\nThe 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`:\n\n```\nname: gitleaks\n\non:\n  pull_request:\n  push:\n\njobs:\n  scan:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v6\n        with:\n          fetch-depth: 0\n      - uses: gitleaks/gitleaks-action@v3\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n```\n\nDon’t skip `fetch-depth: 0`. By default, `actions/checkout` only fetches the latest commit, and gitleaks can’t scan history that wasn’t downloaded.\n\nThe action is free for personal repositories. On an organization repository, it requires a `GITLEAKS_LICENSE` secret from [gitleaks.io](https://gitleaks.io).\n\nIf you prefer not to depend on the action, you can download the binary directly and upload a SARIF report to GitHub code scanning instead:\n\n```\nname: gitleaks\n\non:\n  pull_request:\n  push:\n\njobs:\n  scan:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: read\n      security-events: write\n    steps:\n      - uses: actions/checkout@v6\n        with:\n          fetch-depth: 0\n      - name: Install gitleaks\n        run: |\n          curl -sSL https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz | tar -xz gitleaks\n          sudo mv gitleaks /usr/local/bin/\n      - name: Scan\n        run: gitleaks git --redact --no-banner --ignore-gitleaks-allow -f sarif -r gitleaks.sarif .\n      - uses: github/codeql-action/upload-sarif@v4\n        if: always()\n        with:\n          sarif_file: gitleaks.sarif\n```\n\nAdding `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.\n\nI 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/).\n\nFinally, 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:\n\n| Check | What it scans | Bypassed by `--no-verify` ? | Where it runs | \n|---|---|---|---|\n| `pre-commit` hook | Staged files before the commit is written | Yes | Local repo | \n| `pre-push` hook | New commits in `remote..local` (or full branch on first push) | Yes | Local repo | \n| Claude Code `PreToolUse` hook +`deny` rules | Full history (or `@{u}..HEAD` ) before`git commit` or`git push` | No | Inside Claude Code | \n| GitHub Actions CI | Full history ( `fetch-depth: 0` ) on pushes and pull requests | No | GitHub runner | \n\n## What to do when gitleaks finds a real secret\n\nRotate the key first, and rewrite Git history second.\n\nIf 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:\n\nRotating 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.\n\nWhile you’re in the provider dashboard, check the audit logs to see if anyone used the old key.\n\nNext, pull the secret out of the source code. The S3 client should read both values from environment variables instead:\n\n``` js\nimport { S3Client } from '@aws-sdk/client-s3'\n\nexport const s3 = new S3Client({\n  region: 'eu-west-1',\n  credentials: {\n    accessKeyId: process.env.AWS_ACCESS_KEY_ID,\n    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n  }\n})\n```\n\n### If the commit never left your machine\n\nWhen 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:\n\n```\ngit add src/s3.js\ngit commit --amend --no-edit\n```\n\nIf the secret is in an older local commit, run `git rebase -i` and edit that commit in place.\n\n### If the commit was already pushed\n\nOnce 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`).\n\nTo strip a file out of every commit:\n\n```\ngit filter-repo --invert-paths --path .env\n```\n\nTo scrub specific secret values everywhere they appear, list them one per line in a file outside the repo, with an optional replacement after `==>`:\n\n``` js\nAKIAZ4X7QF3NRT2LWVDK==>REDACTED\nn8Vq2pXkT7mR4sLw9YbE1cHf6JdZ3aGu0oKiNyWe==>REDACTED\ngit filter-repo --replace-text ../secrets.txt\n```\n\nAfter the rewrite, `git filter-repo` removes the `origin` remote as a safety measure. Add it back and force-push all branches and tags:\n\n```\ngit remote add origin git@github.com:flaviocopes/invoice-app.git\ngit push --force --all\ngit push --force --tags\n```\n\nRun `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.\n\nOn 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.\n\nI 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.\n\nBefore 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.\n\nWant me to talk about your product? You can [sponsor this site](https://flaviocopes.com/sponsor/).", "url": "https://wpnews.pro/news/scan-your-repo-for-leaked-secrets-with-gitleaks-before-an-agent-pushes", "canonical_source": "https://flaviocopes.com/gitleaks/", "published_at": "2026-12-01 14:00:00+00:00", "updated_at": "2026-12-01 14:45:17.488581+00:00", "lang": "en", "topics": ["ai-agents", "developer-tools", "ai-tools"], "entities": ["gitleaks", "Flavio", "GitHub", "Amazon S3", "Homebrew"], "also_reported_by": [], "takeaway": "Run gitleaks 8.30.1 in front of git commit, git push and CI so its non-zero exit code blocks leaked keys; its 222 rules use keyword pre-filtering plus entropy checks, and --max-decode-depth defaults to 5 to catch base64-encoded tokens.", "recommendation": {"advice": "Gate coding agents' git commit and git push with gitleaks 8.30.1 hooks and CI so a leaked key fails the build before it enters history.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/scan-your-repo-for-leaked-secrets-with-gitleaks-before-an-agent-pushes", "markdown": "https://wpnews.pro/news/scan-your-repo-for-leaked-secrets-with-gitleaks-before-an-agent-pushes.md", "text": "https://wpnews.pro/news/scan-your-repo-for-leaked-secrets-with-gitleaks-before-an-agent-pushes.txt", "jsonld": "https://wpnews.pro/news/scan-your-repo-for-leaked-secrets-with-gitleaks-before-an-agent-pushes.jsonld"}}