HackBlue

Tools · Python and Bash for security automation · 18 / 20

Stopping secrets before they reach Git: gitleaks, pre-commit hooks, and history scans

Scan a repository’s history for leaked credentials with gitleaks, block new leaks with a pre-commit hook and CI, and respond correctly when a real secret is found.

10 min read · practice only with authorization

Why scan

API keys, tokens, and passwords end up in Git through test files, configuration, and notebooks. Once pushed, they are in history and clones, and public repositories are scanned by attackers within minutes. Scanning catches them early; push protection features on hosting platforms add another layer.

gitleaks

gitleaks detects secrets with regex rules and entropy checks. It can scan full history, staged changes, or a directory, and outputs JSON or SARIF for CI. Allowlists suppress test fixtures with a clear comment.

Snippet
gitleaks git -v .                        # scan full history
gitleaks git --staged                    # only what you are about to commit
gitleaks dir ./config                    # files without Git context
gitleaks git --report-format json --report-path leaks.json .

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.21.2
    hooks:
      - id: gitleaks

Lab: catch a fake key

In a scratch repository, commit a file containing a fake AWS-style access key from AWS documentation examples (AKIAIOSFODNN7EXAMPLE) and a fake private key header. Run gitleaks on history and see both findings with commit and line. Install pre-commit, add the hook, and try committing another fake key: the commit is blocked. Delete the scratch repository afterwards.

Snippet
git init leak-lab && cd leak-lab
echo 'aws_access_key_id = AKIAIOSFODNN7EXAMPLE' > settings.ini && git add . && git commit -qm 'lab'
gitleaks git -v .
pip install pre-commit && pre-commit install
echo 'token = ghp_000000000000000000000000000000000000' > t.txt && git add t.txt && git commit -m 'should be blocked'

When a real secret is found

Revoke or rotate the secret first; removing it from history does not undo exposure. Check the provider’s logs for use of the secret. Then decide whether to rewrite history with git filter-repo, which is disruptive for collaborators, or simply document that the secret is revoked. Finally, move the value to a secret manager and add a scanner to CI so it does not happen again.

Diagram

Secret leak prevention and response

  1. Prevent

    pre-commit hook blocks secrets before commit.

  2. Detect

    CI and full-history scans catch what slipped through.

  3. Respond

    Revoke or rotate immediately; check usage logs.

  4. Fix the cause

    Secret manager, environment variables, and scanning in CI.

Check yourself

1. Which gitleaks command scans the full Git history?

2. A real API key was pushed. What is the first action?

3. Where does a pre-commit hook run?