Important

Which is useful in the work of a software engineer. From good code practices to tips on how to work more efficiently.

Git

Gitleaks is a tool used for detecting and preventing sensitive information leaks in Git repositories.

Prevent sharing secrets in a project

Info

Secrets are a center part of every project. It can be an API key or the secret_code to decrypt a message. We don’t wan’t those secrets to be shared on the internet so it’s important to create some rules that helps prevent this.

GitLeaks

Install GitLeaks
brew install gitleaks
Set up gitleaks

Create this file at the root of the repo

touch .gitleaks.toml

with this inside (example to avoid sharing 11 digit number):

title = "My GitLeaks Config"
 
[[rules]]
description = "Detect 11-digit numeric strings"
regex = '''\b\d{11}\b'''
tags = ["numeric", "ID", "custom"]
Run in the CI (or manually)

Manually:

gitleaks detect --source .

Or add it in the GitHub actions CI by creating a file at .github/workflows/gitleaks.yml with the following content.

name: GitLeaks Scan
on: [push, pull_request]
jobs:
	gitleaks:
		runs-on: ubuntu-latest
		steps:
			- uses: actions/checkout@v2
			- name: Run GitLeaks
			uses: zricethezav/gitleaks-action@v1
			with:
				args: detect --source .

Pre-commit Hooks

It’s also possible to avoid commiting code containing secrets by creating a pre-commit hook that scan code diff to check a possible secret hidden in the code. hooks are in the .git/hooks folder of your repository and a note that a sample of a pre-commit is already there. Create your own hook: touch pre-commit and then edit it to add this:

#!/bin/sh
# Check for 11-digit numbers before committing
if git diff --cached | grep -E '\b[0-9]{11}\b'; then
	echo "Error: 11-digit number detected in the staged changes."
	exit 1
fi

then chmod +x .git/hooks/pre-commit and to verify that it is an executable ls -l .git/hooks/pre-commit should output something like this:

-rwxr-xr-x 1 user group ... .git/hooks/pre-commit

Now every time you’ll commit something, the hook will be triggered to check your commit content.