Moving on with our “Quick Wins / You’re Overthinking It” series, I wanted to share a very simple security practice you can implement in just a few minutes.
In my previous post about security scanning, we used Trivy to scan our git repo and container images. One of those scans would alert you if anyone committed secrets to git.
And by secrets, I mean things like API keys, credentials, private keys, etc.
The problem is that by the time you scan it on GitHub, it’s too late. The secret is already on git, and now you have to:
- Work to remove the secret from history.
- Revoke and replace the secret, which could be a hassle.
The solution for this is very simple – Add a pre-commit hook.
Git hooks allow you to run scripts at different points in the git lifecycle.
Pre-Commit hooks scripts run before code is committed, exactly where we want to run our scanner.
In this example, I’m going to use the Trivy scanner, but there are other tools out there that will do the same job.
Adding the pre-commit script
Git Hooks can be found in the .git/hooks folder. If you look at the contents of this folder, you will find sample scripts for each hook.
We are interested in the pre-commit hook, so we’ll create the file:
Then edit the file and add our script:
#!/bin/sh trivy --quiet fs --exit-code 1 --security-checks secret .
Then we will need to make it executable:
chmod +x .git/hooks/pre-commit
To test it, I added AWS credentials to one of my files, and here is the result:
You can find a list of built-in rules here: