Sub topic 12
Catching secrets before they are committed
A .gitignore entry keeps .env out of Git, but it does nothing about a key pasted into a source file, a test fixture, a notebook output, or a config file you forgot to ignore. This chapter adds automated checks that look at what you are about to commit and stop the commit if it contains a secret.
This chapter assumes you can run Git commands, have read the earlier chapters on .env files and .gitignore, and can install a command-line tool with pip or a package manager.
Why prevention beats cleanup
Once a key is pushed to a remote, you must treat it as exposed. Deleting it in a later commit does not help, because it stays in history. Automated bots scan public repositories continuously, and keys can be found and used within minutes of a push. Stopping the commit locally costs seconds. Responding to a pushed key costs a revocation, an audit of usage, and possibly a history rewrite.
Checks work best in layers, because each layer catches what the previous one missed.
What secret scanners look for
A scanner reads text and flags strings that look like credentials. It uses three main techniques.
- Known patterns. Many providers give keys a recognizable shape, such as a fixed prefix followed by a run of random characters. A regular expression can match these with few false alarms. Prefixes differ by provider, so check your provider's documentation.
- Entropy. Random strings contain a wider spread of characters than ordinary words. A scanner can flag long, high-entropy strings next to words like
key,token, orsecret. This catches unknown formats but produces more false positives, such as hashes and test IDs. - Keyword assignment. Lines such as
password = "..."orapi_key: ...with a literal value are suspicious whatever the value looks like.
None of these is complete. A scanner cannot know that a string is secret. It can only guess from shape and context. Treat a clean scan as "no obvious secrets", not "no secrets".
A simple hand-written hook
Git runs the file .git/hooks/pre-commit before each commit and cancels the commit if the script exits with a non-zero status. This script checks only the lines you have staged for commit.
#!/usr/bin/env bash
# Save as .git/hooks/pre-commit and run: chmod +x .git/hooks/pre-commit
# The pattern is an example. Adjust the prefix to match your provider's key format.
if git diff --cached -U0 | grep -qE '^\+.*sk-[A-Za-z0-9_-]{20,}'; then
echo "Possible API key in staged changes. Commit blocked." >&2
echo "Remove the key, then stage the file again." >&2
exit 1
fiThe script uses grep -q so a match produces no output. If it printed the matching line, the key would appear in your terminal and your scrollback.
This hook teaches the mechanism, but it has two weaknesses. It lives in .git/, which Git does not share, so teammates do not get it. It also knows only one pattern. For real projects, use a maintained tool.
Using the pre-commit framework with Gitleaks
The pre-commit framework manages hooks from a file in your repository, so everyone who clones the project can install the same checks. Gitleaks is an open-source scanner with a large set of built-in rules.
Create .pre-commit-config.yaml in the repository root:
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.4 # pin a release and update it deliberately
hooks:
- id: gitleaksInstall the framework, activate the hook, and run it once over every file:
pip install pre-commit
pre-commit install
pre-commit run --all-filespre-commit install writes the hook into .git/hooks/. Each teammate must run it once after cloning. From then on, git commit runs Gitleaks on the staged changes first.
Alternative: detect-secrets
detect-secrets takes a different approach. It records a baseline of secrets that already exist and then flags only new ones. This helps when you adopt scanning on a repository that already has questionable strings.
pip install detect-secrets
detect-secrets scan > .secrets.baseline
detect-secrets audit .secrets.baselineThe audit step lets you mark each finding as a real secret or a false positive. Commit the baseline file. Later scans compare against it.
| Tool | Strength | Trade-off |
|---|---|---|
| Hand-written hook | No dependencies, easy to read | One pattern, not shared with the team |
| Gitleaks | Many built-in rules, scans history | Needs allowlist tuning for false positives |
| detect-secrets | Baseline workflow for existing repositories | More setup, entropy checks are noisy |
| Provider or host push protection | No local setup, blocks at the server | Covers only the patterns the host supports |
Push protection and CI scanning
Local hooks run on your machine, so they only protect people who installed them. Two server-side layers cover the gap.
- Push protection. Some hosting services, including GitHub, can reject a push that contains a known secret format. They also run secret scanning on repositories and may notify the key's issuer, which can revoke the key automatically. Availability depends on your plan and repository visibility, so check your host's settings.
- CI scanning. Run the scanner as a job on every pull request. This catches commits made without the local hook, including
--no-verifybypasses.
A minimal GitHub Actions job using the Gitleaks action:
name: secret-scan
on: [pull_request, push]
jobs:
gitleaks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # fetch full history so earlier commits are scanned too
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}Without fetch-depth: 0, the checkout contains only the latest commit, and a secret added in an earlier commit of the same pull request is missed.
Handling false positives
A scanner that cries wolf gets disabled. Tune it early.
- Put placeholder values in
.env.example, such asLLM_API_KEY=your-key-here, and make sure the scanner accepts them. Do not weaken the rules to allow them. Add a narrow allowlist entry instead. - Allow specific files or fingerprints, not whole directories. An allowlist for
tests/can hide a real key pasted into a test. - Review every allowlist change in code review.
Gitleaks also supports an inline gitleaks:allow comment on a line, which is useful for a documented example value. Use it sparingly.
What to do when the scanner fires
When a hook blocks a commit, the key has not left your machine yet, so the situation is recoverable.
- Read which file and line the tool reported.
- Move the value to an environment variable or
.env, and read it withos.environorprocess.envas in the earlier chapters. - Stage the fixed file and commit again.
- If the key was ever pasted into a file that was already staged or saved, consider whether it appeared anywhere else, such as shell history, a chat message, or a screenshot. If so, revoke it anyway.
When a CI scan or push protection fires after the push, treat the key as leaked. Rotating it is covered in the next chapters.
Limits of scanning
- Unknown formats. A provider's new key format may not match any rule yet.
- Encoded values. A key that is base64-encoded, split across two variables, or stored inside a binary file or a Jupyter notebook output may slip past.
- Secrets outside the repository. Scanners do not see logs, chat messages, screenshots, or clipboards.
- Already-pushed secrets. A scanner can only report them. It cannot take them back.
Scanning reduces the chance of a mistake. Spend limits, scoped keys, and fast revocation reduce the damage when one gets through.
Exercise
You add Gitleaks as a pre-commit hook and run git commit. It passes. A teammate who cloned the repository last week commits a file containing a real key, and the commit is accepted. Give two likely reasons, and name one layer that would still catch the key.
Show answer
Likely reasons: the teammate never ran pre-commit install, so the hook is not active in their clone, or they used git commit --no-verify. A CI scan on pull requests (with fetch-depth: 0) or the host's push protection would still catch the key. Because the key was committed, the next step is to revoke it.
Exercise
Your CI job runs Gitleaks on pull requests but uses the default checkout. A developer adds a key in the first commit of a pull request and removes it in the second commit. Why might the scan pass, and how do you fix the workflow?
Show answer
The default checkout fetches only the latest commit, so the scanner never sees the first commit that contained the key. Even though the final files are clean, the key is in the branch history and must be treated as leaked. Fix the workflow by setting fetch-depth: 0 on actions/checkout so the full history is scanned, then revoke the key.