Block Hardcoded Secrets in Commits using Pre-Commit
Pre-commit hooks allow you to run arbitrary code on your commit before it actually gets committed. 🤯
pre-commit is perfect for blocking yourself from committing hardcoded secrets.
I think even the biggest proponents of checking code for hardcoded secrets will still, every now and then, accidentally commit a hardcoded secret and push it up to GitHub. For most of us, it’s really not a matter of if, but when.
Even if it’s a private repo — who is going to see that code? If it’s a public repo, then you’d better rotate that key ASAP before the horde of GitHub scraper bots find your key.
Notice the three dots at the bottom of the code block. These are important for later.
As you can see from this PyCharm screenshot, the developer successfully committed the code, which we don’t want.
To demonstrate how pre-commit hooks would block this, first, we have to install the package. I’m going to install it using brew install pre-commit but there are several other ways.
Next, we have to create a YAML file that sits in the root directory of your repository. This file is called .pre-commit-config.yaml.
In the .pre-commit-config.yaml, we can add specific hooks from GitHub repositories or even write and store them locally.
In our specific YAML file, we are going to add ripsecrets, which blocks you from committing secrets, as well as black, which is a Python code formatter. I want to demonstrate both hooks, because pre-commit has an every day usefulness that goes far beyond just a “blocker of committing secrets”.
Here is what our .pre-commit-config.yaml should look like: