Prevention guide

How to prevent committing secrets with pre-commit hooks

A pre-commit hook runs before git records a commit. If it exits non-zero, the commit is rejected — the secret never enters history. This guide covers three setup approaches: the pre-commit framework (best for teams), Husky (best for Node.js projects), and a raw shell hook (no dependencies, works in any repo).

How pre-commit hooks work

Git hooks are scripts that git runs at specific points in the workflow. The pre-commit hook runs after you type git commit but before git records the commit object. If the hook script exits with a non-zero status, git aborts the commit and the developer sees the hook’s output explaining what failed.

The key limitation: hooks live in .git/hooks/, which is not committed to the repository. If a new developer clones the repo, they do not automatically get the hooks. Both the pre-commit framework and Husky solve this by storing the hook configuration in committed files and running a setup step that installs the hooks into the local .git/ directory.

A second limitation: git commit --no-verify skips all hooks. Pre-commit hooks are a first line of defense, not the only one. The CI layer (below) is what closes that bypass.

Approach A: pre-commit framework + gitleaks

The pre-commit framework manages hook installation and tool versions. It fetches the exact version of each hook tool specified in .pre-commit-config.yaml into an isolated virtualenv, so every developer on the team gets identical behavior without manual tool installation. This is the recommended approach for any project with more than one contributor.

  1. Install the pre-commit CLI
    # macOS
    brew install pre-commit
    
    # Python / pip
    pip install pre-commit
    
    # Verify
    pre-commit --version
  2. Add a .pre-commit-config.yaml to the repository root
    repos:
      - repo: https://github.com/gitleaks/gitleaks
        rev: v8.27.2          # pin to a specific release
        hooks:
          - id: gitleaks

    The rev field pins the exact version of gitleaks that will be used. Update it by running pre-commit autoupdate.

  3. Install the hooks into .git/hooks/
    pre-commit install

    This writes a .git/hooks/pre-commit script that delegates to the pre-commit framework. Every developer who clones the repo must also run pre-commit install after cloning — add it to your project README or Makefile.

  4. Test it
    # Stage a file with a fake secret
    echo 'const key = "AKIAIOSFODNN7EXAMPLE"' > test-secret.js
    git add test-secret.js
    git commit -m "test"
    # Expected: commit rejected with a gitleaks finding
    
    # Clean up
    git restore --staged test-secret.js
    rm test-secret.js

Approach B: Husky (Node.js projects)

Husky is the standard hook manager for Node.js projects. It stores hooks in a .husky/ directory that is committed to the repository, and wires them up via the prepare npm script so they are installed automatically on npm install. This approach requires gitleaks to be installed separately on each developer’s machine.

  1. Install Husky
    npm install --save-dev husky
    npx husky init

    husky init creates the .husky/ directory and adds a prepare script to package.json that runs husky after every npm install.

  2. Create the pre-commit hook file
    # .husky/pre-commit
    #!/usr/bin/env sh
    
    # Scan the staged diff for secrets
    if command -v gitleaks &> /dev/null; then
      gitleaks protect --staged --redact --exit-code 1
    else
      echo "WARNING: gitleaks not installed. Skipping secret scan."
      echo "Install: brew install gitleaks"
    fi
    chmod +x .husky/pre-commit
  3. Install gitleaks on each developer machine
    # macOS
    brew install gitleaks
    
    # Linux (download from GitHub releases)
    curl -sSL https://github.com/gitleaks/gitleaks/releases/download/v8.27.2/gitleaks_8.27.2_linux_x64.tar.gz | tar -xz
    sudo mv gitleaks /usr/local/bin/

    Add this step to your project setup docs. Without gitleaks, the hook falls back to a warning rather than a hard block — remove the else branch if you want a hard failure when gitleaks is missing.

Approach C: raw shell hook (no dependencies)

For a single-developer project or a repo where you cannot add external dependencies, a raw shell hook requires only git and gitleaks. Write the hook directly into .git/hooks/ — no framework needed.

  1. Write the hook
    cat > .git/hooks/pre-commit << 'EOF'
    #!/usr/bin/env sh
    if command -v gitleaks &> /dev/null; then
      gitleaks protect --staged --redact --exit-code 1
      if [ $? -ne 0 ]; then
        echo ""
        echo "Secret detected in staged files. Commit rejected."
        echo "If this is a false positive, see: your-repo/README.md#secret-allowlist"
        exit 1
      fi
    else
      echo "gitleaks not found. Skipping pre-commit secret scan."
      echo "Install it: brew install gitleaks"
    fi
    EOF
    chmod +x .git/hooks/pre-commit
  2. Test it
    echo 'STRIPE_KEY="sk_live_abc123xyz"' > /tmp/test-leak.txt
    git add /tmp/test-leak.txt
    git commit -m "test"
    # Should reject the commit
    git restore --staged /tmp/test-leak.txt
Raw hooks are not shared. .git/hooks/ is not committed to the repository. Anyone who clones the repo starts without the hook. If you want to share the hook across the team, commit the hook script to a scripts/ or .hooks/ directory in the repository and document the one-time cp scripts/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit step in your README.

Allowlist: handling false positives

gitleaks will occasionally flag legitimate strings that match a credential pattern — a test fixture with a fake key, an example in documentation, or a known-public API key for a sandbox environment. An allowlist in .gitleaks.toml at the repository root tells gitleaks to skip specific matches.

# .gitleaks.toml
[allowlist]
  description = "Project-level allowlist for known false positives"

  # Skip a specific file entirely
  paths = [
    '''tests/fixtures/sample-response.json''',
    '''docs/examples/'''
  ]

  # Skip a specific regex match
  regexes = [
    # Stripe publishable key (intentionally public)
    '''pk_test_51[a-zA-Z0-9]{20,}''',
    # Known dummy key used in test suite
    '''AKIAIOSFODNN7EXAMPLE'''
  ]

  # Skip commits by a specific commit SHA (use sparingly)
  commits = [
    "abc123def456"
  ]

Commit .gitleaks.toml to the repository so the allowlist is shared with the team and applies to the CI scan as well as the local pre-commit hook.

Add CI enforcement (close the --no-verify bypass)

Pre-commit hooks can be skipped with git commit --no-verify. The CI layer closes this gap: a branch protection rule that requires a secret-scanning check to pass means that even a commit that bypassed the local hook cannot be merged without passing the CI scan.

# .github/workflows/secret-scan.yml
name: Secret scan

on:
  push:
    branches: ["**"]
  pull_request:

jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # full history for gitleaks
      - uses: gitleaks/gitleaks-action@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          args: detect --redact --no-banner

After adding this workflow, go to repository Settings → Branches → Branch protection rules and add a rule for your main branch that requires the Secret scan / scan status check to pass before merging.

Frequently asked questions

Can I bypass a pre-commit hook?

Yes: git commit --no-verify skips all hooks. Pre-commit hooks are a developer convenience and early warning, not a hard security boundary. The CI pipeline closes this gap — a branch protection rule that requires the CI secret scan to pass means a bypassed local hook cannot reach the main branch without being caught.

What happens to files committed before I set up the hook?

Nothing — hooks only intercept future commits. If a secret was committed before the hook was installed, it remains in git history until you rewrite history with git filter-repo or BFG Repo-Cleaner. See the history rewrite guide. And rotate the key first.

Will the hook slow down every commit?

gitleaks protect --staged scans only the staged diff, not the full repository. On a typical commit, it completes in under a second. On a large staged diff, two to three seconds. The scan time grows with the staged content size, not the total repository size.

How do I handle a false positive blocking a legitimate commit?

Two options. For a one-time exception: git commit --no-verify (use sparingly). For a recurring pattern: add an allowlist rule to .gitleaks.toml as described in the allowlist section above. The allowlist approach is better for the team because the rule is committed and shared, so every developer and the CI pipeline benefit from it.

Do I need this if I already have a .gitignore for .env files?

.gitignore prevents the .env file itself from being committed. It does not prevent hardcoded API keys in source files, keys pasted into config files, or accidentally committed dotfiles that are not in .gitignore. The two are complementary: .gitignore keeps secrets files out of the repository; pre-commit hooks catch secrets that end up inline in committed code.

Does gitleaks protect --staged work if gitleaks is not in PATH?

No — the hook script needs to find the binary. If it is not in PATH, the hook fails with command not found. The pre-commit framework avoids this by managing the binary itself. For Husky and raw hooks, add a graceful fallback: if ! command -v gitleaks > /dev/null; then echo 'Warning: gitleaks not installed'; exit 0; fi. This turns a missing binary into a warning rather than a hard block for the developer who forgot to install it, while the CI pipeline still enforces the check.

Can I use this in a monorepo?

Yes. Pre-commit hooks operate at the repository level. A single hook in the repository root intercepts commits across all packages. gitleaks protect --staged scans only the staged files regardless of which subdirectory they are in. For the pre-commit framework, install it once in the repository root and it covers the whole monorepo.

Also in the Copper Bay Labs ship-safety suite