Pre-commit hooks
Pre-commit hooks are a useful way to prevent secrets in code from being pushed from a git repository. Preventing them from being leaked in the first place is always the best approach. If you run your own git server, consider the pre-receive hook option which can block commits with secrets from being accepted.
This guide covers how to set up TruffleHog as a pre-commit hook using two popular frameworks:
- Git's hooksPath feature - A built-in Git feature for managing hooks globally
- Using Pre-commit framework - A language-agnostic framework for managing pre-commit hooks
- Using Husky - A Git hooks manager for JavaScript/Node.js projects
All of the methods require TruffleHog to be installed.
- Install TruffleHog:
This approach uses Git's core.hooksPath to apply hooks to all repositories without requiring any per-repository setup:
- Create a global hooks directory:
- Create a pre-commit hook file:
- Add the following content to ~/.git-hooks/pre-commit:
- Configure Git to use this hooks directory globally:
Now all your repositories will automatically use this pre-commit hook without any additional setup.
The pre-commit framework is a powerful, language-agnostic tool for managing Git hooks.
- Install the pre-commit framework:
To set up TruffleHog as a pre-commit hook for a specific repository:
- Create a .pre-commit-config.yaml file in the root of your repository:
- Install the pre-commit hook:
Husky is a popular tool for managing Git hooks in JavaScript/Node.js projects.
- Install Husky in your project:
- Enable Git hooks:
- Add the following content to .husky/pre-commit:
For optimal hook efficacy:
- Execute git add followed by git commit separately. This ensures TruffleHog analyzes all intended changes.
- Avoid using git commit -am, as it might bypass pre-commit hook execution for unstaged modifications.
In rare cases, you may need to bypass pre-commit hooks:
If your pre-commit hook isn't running:
Ensure the hook is executable:
Check if hooks are enabled:
If you're getting false positives:
- Use the --results=verified flag to only show verified secrets
- Add trufflehog:ignore comments on lines with known false positives or risk-accepted findings
By integrating TruffleHog into your pre-commit workflow, you can prevent credential leaks before they happen. Choose the setup method that best fits your project's needs and development workflow.
For more information on TruffleHog's capabilities, refer to the main documentation.