DEV Community
Follow
Building a Secrets Detection Pre-Commit Hook in 50 Lines
Secrets exposed in Git repositories are a major cause of security breaches, with AWS keys scraped by bots rapidly. The most effective defense is a pre-commit hook, which detects secrets before they are committed, preventing the need for complex history scrubbing and secret rotation. Traditional CI/CD scanners are reactive, catching leaks after they are already in the repository history, leaving a window for compromise.A lightweight, customizable Python pre-commit hook, approximately 50 lines long, offers an efficient local solution. This hook targets common secret types using regex patterns, including AWS access keys, generic API keys, private keys, passwords in configuration files, and platform-specific tokens. It runs in milliseconds and requires no external dependencies beyond Python's standard library.The script involves creating a pre-commit file in .git/hooks/, making it executable, and defining regex patterns for various secrets. It parses only added lines in staged changes, specifically looking for new leaks rather than existing ones or deletions. For legitimate false positives, an inline # nosecret comment can be implemented as an escape hatch.To distribute the hook, it can be stored in a committed directory and copied via a Makefile setup, or more cleanly, Git can be configured to use a shared hooks directory using git config core.hooksPath. This approach integrates the hook seamlessly into team workflows. Teams can extend the hook by adding patterns for internal token formats, but precision is crucial to avoid false positives that diminish trust in the system.This pre-commit hook complements broader security strategies, such as CI-level scanners like truffleHog or gitleaks, offering a crucial first line of defense. It prevents accidental staging of sensitive data, which is a common failure mode in development. This low-effort, high-impact security control enhances overall security posture significantly without requiring extensive setup or architectural changes.