← Back to Blog

Preventing API Key Leaks with Pre-Commit Secrets Scanning



Preventing API Key Leaks with Pre-Commit Secrets Scanning

Pushing API keys, AWS tokens, or private keys to Git is a developer nightmare automated scrapers index public repositories and exploit exposed credentials within minutes. Waiting for server-side scanners or CI/CD pipelines to catch them means the secret is already recorded in your commit history and requires immediate revocation.

Detecting credentials before they leave your local development environment is a much more effective approach. Here is how to configure TruffleHog as a pre-commit hook to catch secrets locally.

Pre-Commit Setup with TruffleHog

Add this hook definition to your .pre-commit-config.yaml:

repos:
 - repo: https://github.com/trufflesecurity/trufflehog
 rev: v3.63.7
 hooks:
 - id: trufflehog
 name: TruffleHog Secret Scanner
 description: Detects verified secrets in committed code.
 entry: bash -c 'trufflehog git file://. --since-commit HEAD --only-verified --fail'
 language: system
 stages: [commit]
 pass_filenames: false

How This Configuration Works

  • repo: Points to TruffleHog's official repository to fetch the hook definition.
  • entry: Overrides the default command to customize how TruffleHog scans staged local changes.
  • trufflehog git file://. --since-commit HEAD: Instead of scanning the entire Git history (which takes significant time), it only evaluates the diff of staged files against HEAD. This keeps commit check times under a few milliseconds.
  • --only-verified: TruffleHog attempts to authenticate any detected key against the provider API in real time. If validation fails, it ignores the match, eliminating false positives so developers do not contend with harmless alerts.
  • --fail: Exits with a non-zero status code if an active secret is found, causing pre-commit to block the Git commit.
  • pass_filenames: false: Prevents pre-commit from appending a list of modified files to the end of the entry string, as TruffleHog manages diff inspection directly.

Implementing this configuration across your team prevents credentials from entering commits initially, sparing your organization from complex credential rotation emergency procedures.