TExcelTAD
Home › CI/CD Pipelines & Pipeline Security › Secret Detection with gitleaks

Secret Detection with gitleaks

A secret committed to Git is in the history forever, in every clone, fork and backup. Secret scanners look for credentials by pattern (the shape of an AWS key, a GitHub token, a Stripe key) and entropy (random-looking strings next to words such as key or token). gitleaks is the most widely used open-source one: a single Go binary with a few hundred built-in rules, configurable in TOML, fast enough for pre-commit hooks.

Command Scans
gitleaks git . every commit in the repository's history (or a range with --log-opts)
gitleaks dir . files on disk, ignoring Git (build outputs, container file systems)
gitleaks git --pre-commit --staged . the staged changes, for a pre-commit hook (the old protect command)
gitleaks stdin piped text (logs, environment dumps)

Finding a leak in history

A developer adds credentials, notices, and "removes" them in the next commit. The working tree is clean, the history is not:

bash · try it yourself
mkdir svc && cd svc && git init -q
cat > config.py <<'PY'
DB_HOST = "db.internal"
PY
git add . && git commit -qm "add config"
cat >> config.py <<'PY'
STRIPE_KEY = "sk_live_51HqLyjWDarjtT1zdp7dcXYZ8a2bR4kLm9nOp"
GITHUB_TOKEN = "ghp_4fT9kL2mQ8xR5vB7nC1zW3yH6jP0sD2gA9eK"
PY
git commit -qam "add keys"
git checkout -q HEAD~1 -- config.py && git commit -qm "remove keys"
echo "working tree: $(grep -c . config.py) line(s), no keys"
gitleaks dir . --no-banner > /dev/null 2>&1; echo "gitleaks dir: exit $?"
gitleaks git . --no-banner -r report.json
echo "gitleaks git: exit $?"
jq -r '.[] | "\(.RuleID)  \(.File):\(.StartLine)  commit \(.Commit[0:7])  \(.Match[0:24])..."' report.json | sort
working tree: 1 line(s), no keys
gitleaks dir: exit 0
8:09AM INF 3 commits scanned.
8:09AM INF scanned ~143 bytes (143 bytes) in 225ms
8:09AM WRN leaks found: 2
gitleaks git: exit 1
github-pat  config.py:3  commit be7f0e5  ghp_4fT9kL2mQ8xR5vB7nC1z...
stripe-access-token  config.py:2  commit be7f0e5  sk_live_51HqLyjWDarjtT1z...

gitleaks dir found nothing because the files are clean now; gitleaks git found both keys in the commit that added them. Exit code 1 means "leaks found", which is what makes it a gate. Never print secrets in CI logs: the jq above truncates the match, and --redact hides it in gitleaks' own output.

What to do with a real finding: revoke and rotate the credential first; then decide whether to rewrite history (git filter-repo), which helps only if nobody has cloned the repository yet. Assume a pushed secret is compromised.

Configuration: custom rules and allowlists

Built-in rules don't know your internal token formats, and test fixtures full of fake tokens create noise. A .gitleaks.toml at the repository root extends the defaults:

bash · try it yourself
mkdir svc && cd svc && git init -q
mkdir -p src tests
cat > src/settings.py <<'PY'
DB_URL = "postgres://shop:Pr0d-Passw0rd-x81@db.internal:5432/shop"
STRIPE_KEY = "sk_live_51HqLyjWDarjtT1zdp7dcXYZ8a2bR4kLm9nOp"
PY
cat > src/internal.py <<'PY'
ACME_TOKEN = "acme_live_7Hk29xLqP4mZ8vR2"
PY
cat > tests/fixtures.py <<'PY'
FAKE_TOKEN = "ghp_aaaaBBBBccccDDDDeeeeFFFFgggg01234567"
PY
git add . && git commit -qm "init"
echo "### default rules"
gitleaks git . --no-banner -r before.json 2> /dev/null
jq -r '.[] | "\(.RuleID) \(.File):\(.StartLine)"' before.json | sort

cat > .gitleaks.toml <<'TOML'
[extend]
useDefault = true

[[rules]]
id = "acme-api-token"
description = "ACME internal API token"
regex = '''acme_(live|test)_[A-Za-z0-9]{16}'''
keywords = ["acme_"]

[[allowlists]]
description = "test fixtures contain fake tokens"
paths = ['''^tests/''']
TOML
echo "### with .gitleaks.toml"
gitleaks git . --no-banner -r after.json 2> /dev/null
jq -r '.[] | "\(.RuleID) \(.File):\(.StartLine)"' after.json | sort
### default rules
generic-api-key src/internal.py:1
github-pat tests/fixtures.py:1
stripe-access-token src/settings.py:2
### with .gitleaks.toml
acme-api-token src/internal.py:1
generic-api-key src/internal.py:1
stripe-access-token src/settings.py:2

Three things to notice:

  • The custom rule now names the internal token precisely (acme-api-token), alongside the generic entropy rule that had caught it vaguely.
  • The fixture in tests/ is allowlisted by path. Allowlists can also match by regexes, stopwords or specific commits; a single line can be ignored with a gitleaks:allow comment.
  • The database password in DB_URL is not reported by either configuration. No scanner knows every format; the next lesson shows TruffleHog catching this one. Scanners reduce the risk, they don't remove it.

Baselines: adopt without blocking

On an old repository with known (already rotated) findings, record them once and report only new ones:

bash
gitleaks git . --report-path gitleaks-baseline.json          # once; commit the file after review
gitleaks git . --baseline-path gitleaks-baseline.json        # in CI: only findings not in the baseline

In a PR pipeline you can also limit the scan to the PR's commits: gitleaks git . --log-opts="origin/main..HEAD".

In the pipelines

yaml
# GitHub Actions (non-run): scan the commits of the push or PR
gitleaks:
  runs-on: ubuntu-24.04
  steps:
    - uses: actions/checkout@v7
      with:
        fetch-depth: 0                       # history is the point
    - name: gitleaks
      run: |
        ./ci/install-gitleaks.sh 8.30.1      # pinned binary, checksum verified
        gitleaks git . --no-banner --redact --report-format sarif --report-path gitleaks.sarif
yaml
# GitLab CI (non-run)
gitleaks:
  image: zricethezav/gitleaks:v8.30.1
  variables:
    GIT_DEPTH: "0"
  script:
    - gitleaks git . --no-banner --redact --log-opts="$CI_MERGE_REQUEST_DIFF_BASE_SHA..HEAD"
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

Plus the pre-commit hook from Linting & Formatting Gates, so most leaks never leave the laptop, and push protection on the server side (GitHub secret scanning push protection, GitLab secret push protection) to reject pushes that contain known token formats.

Test yourself

A key was committed and removed in the next commit. Which command finds it?

  1. gitleaks dir .
  2. gitleaks git .
  3. grep -r key .
  4. None

What is the right response to a real secret found in a pushed commit?

  1. Add it to the allowlist
  2. Revoke and rotate it, then clean up history if useful
  3. Make the repo private
  4. Delete the CI logs

What does --baseline-path do?

  1. Sets the scan root
  2. Ignores findings already recorded in a previous report, so only new leaks fail the scan
  3. Uploads results
  4. Scans only the last commit