Sub topic 12
Catching secrets before they are committed
This chapter covers secret scanning: tools that look for credentials in your code and history before they reach a shared repository. It assumes you can use Git and a command line, know what an API key is, and have used an AI coding assistant. Earlier chapters showed how to keep secrets out of source code. Scanning is the safety net for when that discipline fails.
Why scanning is needed even with good habits
AI assistants raise the odds of an accidental leak in three ways:
- An assistant that edits files may paste a real value from your environment or a log into a source file, a test fixture, or a config example.
- You may paste a stack trace into a prompt, and the assistant may copy a token from it into code.
- Generated code often includes placeholder strings that look like keys. Some of them turn out to be real.
A commit is the point where a secret stops being local. Before the commit, the value sits on your machine. After you push, it is on a server, in clones, in CI logs, and possibly in an AI tool that indexes the repository. Removing it from history later is hard, and you must treat it as exposed anyway. Scanning at commit time is the cheapest place to stop it.
How secret scanners work
A scanner reads text and flags strings that look like credentials. It uses three main techniques:
- Pattern matching. Many providers issue keys with a recognizable shape. AWS access key IDs start with
AKIAfollowed by 16 uppercase letters or digits. A regular expression finds these with few false alarms. - Entropy checks. Random-looking strings have high entropy, which is a measure of unpredictability. A 40-character string of mixed characters assigned to a variable named
secretis suspicious even without a known format. - Context rules. The scanner looks at nearby words such as
password,token, orAuthorization: Bearer, and at file names such as.envor*.pem.
Each technique has a failure mode. Patterns miss custom or internal token formats. Entropy checks flag hashes, UUIDs, and test data. Context rules miss secrets stored under unusual names. Expect both false positives (harmless strings flagged) and false negatives (real secrets missed). A scanner lowers risk and does not remove it.
Layer 1: a pre-commit hook
A Git hook is a script that Git runs at a set point in its workflow. A pre-commit hook runs before a commit is created, and if it exits with an error, the commit does not happen. The pre-commit framework manages hooks from a single config file, so every developer gets the same checks.
This configuration runs the Gitleaks scanner on staged changes:
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.4
hooks:
- id: gitleaksSave it as .pre-commit-config.yaml in the repository root. Pin rev to a release tag so everyone runs the same version, and check the project's releases page for a current tag before you copy this one.
Then install the framework and register the hook:
pip install pre-commit
pre-commit install
pre-commit run --all-filesThe three commands do different jobs:
pip install pre-commitinstalls the tool.pre-commit installwrites a script into.git/hooks/so the checks run on everygit commit.pre-commit run --all-filesscans every tracked file once. Use it right after setup, because a hook that only sees staged changes will not find secrets that were committed last month.
Commit .pre-commit-config.yaml so teammates get the same rules. Each person still has to run pre-commit install once in their own clone, because Git does not copy hooks when someone clones the repository.
What a blocked commit looks like
Suppose an assistant adds a test file containing a real-looking AWS key. When you commit, the hook prints the rule that matched, the file, the line, and a redacted preview. The commit stops. You then:
- Open the file and replace the value with a read from the environment, as in the earlier chapter on moving secrets out of code.
- Stage the file again and commit.
- If the value was a real credential and not a placeholder, rotate it. It was in your editor, and possibly in an AI tool's context, so treat it as exposed.
Layer 2: scanning in CI
Pre-commit hooks have one large gap: they run on the developer's machine, and they can be skipped. Anyone can run git commit --no-verify, forget to install the hook, or commit from a web editor. A scan in continuous integration (CI), the server-side automation that runs on every push or pull request, closes that gap because contributors cannot bypass it.
Here is a minimal GitHub Actions workflow:
name: secret-scan
on: [pull_request, push]
jobs:
gitleaks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}fetch-depth: 0 downloads the full history. Without it, the checkout is shallow and the scanner sees only the latest commit, so a secret added three commits ago passes. Check the action's current documentation, since some versions need a license key for organization repositories.
Some hosting platforms also offer built-in push protection, which rejects a push that contains a recognized secret. Where available, turn it on in addition to your own scan. The two catch different things.
Scanning history, not only new changes
A clean working tree does not mean a clean repository. Old commits keep deleted secrets. To scan the full history of a repository, run Gitleaks directly:
gitleaks detect --source . --verboseThis walks every commit reachable from your branches. If it finds a hit, deleting the line in a new commit does not help, because the old commit still contains the value. The fix is to revoke the credential first, then decide whether to rewrite history. The incident response chapter covers that order of work.
Tuning: false positives and allowlists
An overly noisy scanner trains people to ignore it or bypass it. Reduce noise on purpose:
- Keep example values obviously fake, such as
AKIAEXAMPLEEXAMPLE00is not valid butYOUR_API_KEY_HEREis clearly a placeholder and rarely matches any rule. - Use an allowlist for known harmless strings. Gitleaks reads a
.gitleaks.tomlfile in the repository root. - Allowlist narrowly, by rule and path, and never by turning a rule off for the whole project.
[allowlist]
description = "Test fixtures with fake values"
paths = [
'''tests/fixtures/.*''',
]Review allowlist changes in pull requests like any other security-relevant change. An allowlist is also a place where a real secret can hide, so a broad path rule such as .* defeats the scanner.
Scanning what you send to an AI tool
Commit-time scanning protects the repository. It does not protect a prompt, because a prompt never goes through Git. For text you paste into an assistant, use a redaction step before you send it. This helper replaces a few well-known credential shapes with placeholders:
import re
PATTERNS = [
(re.compile(r"AKIA[0-9A-Z]{16}"), "[REDACTED_AWS_KEY_ID]"),
(re.compile(r"(?i)(authorization:\s*bearer\s+)[^\s]+"), r"\1[REDACTED]"),
(re.compile(r"(?i)((?:password|secret|token|api[_-]?key)\s*[=:]\s*)\S+"), r"\1[REDACTED]"),
]
def redact(text: str) -> str:
for pattern, replacement in PATTERNS:
text = pattern.sub(replacement, text)
return text
print(redact("password=hunter2 Authorization: Bearer abc123"))The output is password=[REDACTED] Authorization: Bearer [REDACTED]. This is a best-effort filter. It misses secrets in formats it does not know, such as private key blocks or connection strings with embedded passwords. Treat it as a second check after you have read the text yourself.
Choosing and combining layers
| Layer | Runs where | Catches | Can be bypassed? | Main weakness |
|---|---|---|---|---|
| Pre-commit hook | Developer machine | New secrets before commit | Yes, with `--no-verify` or no install | Depends on each person |
| CI scan | Server | Secrets in pushed commits | No, if the check is required | Secret is already pushed |
| Platform push protection | Hosting service | Known provider key formats | Often with an override | Limited to known formats |
| History scan | Anywhere | Old, buried secrets | Not applicable | Finds problems after the fact |
No single layer is enough. The pre-commit hook gives the fastest feedback. CI makes the check mandatory. A periodic history scan finds what both missed. Mark the CI check as required in your branch protection settings, or developers can merge despite a failure.
Common mistakes
- Installing the hook config but not running
pre-commit install, so nothing runs. - Scanning only staged files and never the history.
- Using a shallow checkout in CI.
- Treating a passing scan as proof that no secret exists.
- Fixing a leak by deleting the line and skipping rotation.
- Allowlisting a whole directory to silence one warning.
Exercise
A teammate says, "We have a pre-commit hook, so we don't need a CI scan." Give two reasons this is wrong, and name one setting that makes the CI scan effective.
Show answer
First, a pre-commit hook runs only on the developer's machine, and it can be skipped with git commit --no-verify, never installed (hooks are not copied by git clone), or bypassed by committing through a web editor. Second, a CI scan runs on the server for every push or pull request, so it gives one consistent check for all contributors and can scan full history. To make it effective, mark the CI check as required in branch protection so a failing scan blocks merging. Using fetch-depth: 0 so the scanner sees the whole history also matters.
Exercise
You run pre-commit install and commit a file with a fake token, and the commit is blocked. Later you realize a real API key was committed two months ago, before the hook existed. Which command finds it, and what is the first action once it is found?
Show answer
Run pre-commit run --all-files to scan tracked files, or gitleaks detect --source . --verbose to scan the full commit history, since the key may exist only in an old commit. The first action is to revoke or rotate the credential at the provider. Removing it from the code or rewriting history comes after that, because the value must be treated as exposed.