Never Commit Secrets to Git with Pre-Commit Hooks

by Yuval Oren, Co-Founder / CEO

1. Efficiency is Hard to Measure

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:

  1. Work to remove the secret from history.
  2. 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:

touch .git/hooks/pre-commit

Then edit the file and add our script:

#!/bin/bash
trivy --quiet fs --exit-code 1 --security-checks secret .

Then we will need to make it executable:

chmod +x .git/hooks/pre-commit

That’s it.

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: https://github.com/aquasecurity/fanal/blob/main/secret/builtin-rules.go

More articles

AWS Geo Blocking with CloudFront and WAF

_In this post, I will show you how to use CloudFront or AWS WAF to enable geo-blocking (blocking based on geographical location) for your website or APIs._

Read more

Our Approach to Onboarding New DevOps Hires

What's the best way to onboard a new DevOps hire? Instead of having them aimlessly go through Confluence we have a better approach.

Read more

Tell us about your project

Our offices

  • Israel
    5 Hatidhar St
    Ra'anana, Israel