Secret Detection with Gitleaks
Introduction: Why Secrets in Code Are Dangerous
In our previous lessons, we used tools like Semgrep and ESLint to find logic errors in our code, such as unsafe database queries or missing authentication checks. These tools analyze the structure of the application. However, even perfectly written logic can be compromised if the "keys to the castle" are left under the doormat. In software development, these keys are secrets — API keys, database passwords, and encryption tokens.
Leaving secrets inside your source code is one of the most common and critical security mistakes. If a repository is public, or if an attacker gains access to your private source code, hardcoded credentials allow them to immediately impersonate your application, steal data, or incur massive cloud computing costs. In this lesson, we will use Gitleaks, a specialized SAST tool designed to scan git repositories for these accidentally committed secrets, and learn how to remove them safely.
Understanding What Gitleaks Detects
Gitleaks is a tool that scans your codebase for sensitive information that should never be committed to version control. While standard linters look for syntax errors, Gitleaks looks for data patterns that resemble credentials. It supports detecting specific formats (like Amazon Web Services keys or Facebook tokens) and high-entropy strings, which are strings of characters that look suspiciously random (like a8f391...), often indicating a password or key.
To understand what we are looking for, let's examine a typical configuration file that a developer might create while rushing to get a feature working. This file contains several hardcoded values that pose a security risk.
In the snippet above, the password field is explicitly visible. Anyone with read access to this file can access the pastebin_db.
Here is another section of that same file showing cloud credentials:
These patterns are exactly what Gitleaks is trained to spot. The AWS_CONFIG block contains keys that follow a very specific format defined by Amazon. Gitleaks uses Regular Expressions to identify the AKIA... prefix of the access key, instantly flagging this as a high-severity finding.
