Git Secrets Management and Pre-commit Hooks
Preventing secrets from entering repositories using pre-commit hooks, secret scanning tools, and automated detection. Protect API keys, tokens, and credentials from accidental commits.
Pre-commit hooks and server-side scanners can catch many credential leaks, but their detectors cover different formats and can raise false positives. If a credential is exposed, revoke or rotate it first, assess the incident, and notify the provider when appropriate. Then decide whether history cleanup is warranted and check forks, clones, caches, artifacts, and logs. Rewriting commits does not invalidate an active credential.
Introduction
Every day, developers accidentally commit secrets to Git repositories. API keys, database passwords, private certificates, and authentication tokens end up in version control, where they’re instantly exposed to anyone with repository access — and potentially to the entire internet if the repository is public.
Deleting a credential in a later commit does not remove it from earlier Git objects, and it may already have been copied. Treat exposure as an incident: revoke or rotate the credential first, assess what it could access and whether it was used, then notify the provider or your security team when appropriate. Decide separately whether to clean the repository history. Rewriting commits does not invalidate a credential that is still active, and it cannot remove copies in forks, clones, caches, build artifacts, or logs. GitHub’s sensitive-data removal guidance also puts revocation or rotation first and describes when repository cleanup may be needed.
This guide covers pre-commit hooks, repository scanners, and practices for responding when a credential slips through. Hooks reduce mistakes, but they cannot control every commit path or remove a credential that has already been exposed.
When to Use / When Not to Use
When to implement secret prevention:
- Every repository — without exception
- Especially public/open-source repositories
- Before onboarding new developers
- After any secret leak incident
- As part of CI/CD pipeline security
When not to rely solely on prevention:
- For a credential already exposed — revoke or rotate it, assess its scope and use, and notify the provider when appropriate. Decide whether history cleanup is warranted, then check forks, clones, caches, artifacts, and logs.
- As a replacement for credential revocation or rotation — rewritten history does not make an active credential safe
- For encrypted secrets — use proper secret management systems
Core Concepts
Secret prevention operates at multiple layers:
graph TD
DEV["Developer"] -->|commits| HOOK["Pre-commit Hook\nlocal detection"]
HOOK -->|blocks| SECRET["Secret Detected"]
HOOK -->|allows| CLEAN["Clean Commit"]
CLEAN -->|pushes to| REMOTE["Remote Repository"]
REMOTE -->|scans with| SERVER["Server-side Scanning\nGitHub/GitLab secret detection"]
SERVER -->|alerts| ALERT["Security Alert"]
SECRET -->|rotates| ROTATE["Rotate Credential"]
ALERT -->|rotates| ROTATE
Local hooks give quick feedback, while CI or platform scanning can catch some commits that get past them. Coverage depends on the scanner, its configuration, and where it runs; monitoring can reveal suspicious use after exposure.
Architecture or Flow Diagram
flowchart LR
CODE["Code Change"] -->|git add| STAGED["Staged Files"]
STAGED -->|git commit| PRE_COMMIT["Pre-commit Hook"]
PRE_COMMIT -->|scans with| DETECT["Secret Detection Engine"]
DETECT -->|regex patterns| PATTERNS["Pattern Matching\nAWS keys, tokens, passwords"]
DETECT -->|entropy analysis| ENTROPY["High Entropy Detection\nrandom-looking strings"]
PATTERNS --> RESULT{"Secret found?"}
ENTROPY --> RESULT
RESULT -->|yes| BLOCK["Block Commit\nshow file:line"]
RESULT -->|no| COMMIT["Create Commit"]
BLOCK -->|developer fixes| CODE
COMMIT -->|pushes to| REPO["Repository"]
Step-by-Step Guide / Deep Dive
Pre-commit Framework
The pre-commit framework is one option for configuring hooks across repositories:
# Install pre-commit
pip install pre-commit
# Create configuration
cat > .pre-commit-config.yaml << 'EOF'
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
EOF
# Install the hooks
pre-commit install
# Run manually on all files
pre-commit run --all-files
Gitleaks
Gitleaks scans with built-in rules and supports custom rules, entropy thresholds, and allowlists. Rule coverage depends on the version and configuration; broad patterns can also match example credentials or test fixtures. See the Gitleaks project documentation before changing rule syntax or configuration.
# Install
brew install gitleaks
# Scan current repository
gitleaks detect
# Scan with verbose output
gitleaks detect -v
# Scan specific commit range
gitleaks detect --log-opts="main..HEAD"
# Generate a baseline (allowlist known false positives)
gitleaks detect --baseline .gitleaks-baseline.json
# Custom configuration
cat > .gitleaks.toml << 'EOF'
title = "Custom Gitleaks Config"
[extend]
useDefault = true
[[rules]]
id = "custom-api-key"
description = "Custom API Key"
regex = '''CUSTOM_API_KEY\s*=\s*['"]?[a-zA-Z0-9]{32,}['"]?'''
tags = ["custom", "api-key"]
EOF
Detect-secrets
detect-secrets uses plugins for known credential formats, keyword checks, and high-entropy strings. Entropy and keyword checks can find less structured values but need tuning; its baseline audit helps distinguish real secrets from false positives. Review baseline changes instead of broadly allowlisting paths. See the detect-secrets documentation.
# Install
pip install detect-secrets
# Create initial baseline
detect-secrets scan > .secrets.baseline
# Audit the baseline (review each finding)
detect-secrets audit .secrets.baseline
# Check against baseline in pre-commit
detect-secrets-hook --baseline .secrets.baseline $(git diff --cached --name-only)
# Update baseline after adding allowlisted secrets
detect-secrets scan --baseline .secrets.baseline
Git-secrets (AWS)
git-secrets registers AWS credential patterns and lets you add custom regular expressions. Its AWS focus can make it a useful targeted check, but the project notes that the patterns do not catch every possible credential. Allowed patterns can suppress false positives, so keep them narrow. See the git-secrets documentation.
# Install
brew install git-secrets
# Install hooks in repository
git secrets --install
# Add AWS patterns
git secrets --register-aws
# Add custom patterns
git secrets --add 'password\s*=\s*.+'
# Scan entire history
git secrets --scan-history
# Scan staged changes
git secrets --scan
Environment Variable Patterns
Never commit secrets — use environment variables and .env files:
# .env (NEVER commit this)
DATABASE_URL=postgresql://user:password@localhost/db
API_KEY=sk-1234567890abcdef
SECRET_KEY=your-secret-key-here
# .env.example (SAFE to commit - template only)
DATABASE_URL=postgresql://user:password@localhost/db
API_KEY=your-api-key-here
SECRET_KEY=your-secret-key-here
# .gitignore
.env
.env.local
.env.*.local
!.env.example
Choosing a Scanner
Scanners recognize different credential formats, and each trades coverage against noise. Check the current detector list and configuration for the version you install, then test it against representative secrets and harmless examples from your own codebase.
| Tool | Detection approach | Coverage and false-positive tradeoff |
|---|---|---|
| Gitleaks | Built-in and custom rules, with optional entropy checks and allowlists | Useful for known formats and organization-specific rules; broad patterns may match fixtures or examples. |
detect-secrets |
Plugins for provider formats, keyword checks, and entropy heuristics; audited baselines | Can catch less structured values, but heuristic findings need review and an overly broad baseline can hide later leaks. |
git-secrets |
AWS patterns plus configured regular expressions | Focused on configured patterns; the project warns that its AWS rules are not exhaustive. |
| TruffleHog | Provider-specific detectors with optional credential verification | Verification can raise confidence for supported providers; unverified or unsupported formats still need another detection path. See the TruffleHog documentation. |
| GitHub Secret Scanning | Supported partner/provider patterns plus optional generic and custom patterns | Coverage and features depend on repository type and plan. See supported secret scanning capabilities. |
No scanner covers every credential format. Local hooks give fast feedback; CI and platform scanning cover paths that local hooks can miss. Configure their scan range and enforcement separately, and review findings rather than treating a clean scan as proof that no secret was exposed.
Production Failure Scenarios
| Scenario | Symptoms | Mitigation |
|---|---|---|
| Secret committed | Credential exposed in history | Revoke or rotate first; assess scope and use, notify the provider when appropriate, decide whether history cleanup is needed, and review forks, clones, caches, artifacts, and logs. |
| False positives block commits | Legitimate code blocked | Add to baseline/allowlist; refine patterns |
| Pre-commit hook bypassed | git commit --no-verify |
Server-side scanning as backup |
| Secret in CI/CD logs | Logs contain credentials | Use secret masking; rotate exposed secrets |
| Shared development credentials | Multiple devs using same key | Use per-developer credentials; vault systems |
Trade-off Analysis
| Aspect | Advantage | Disadvantage |
|---|---|---|
| Pre-commit hooks | Catches secrets before commit | Can be bypassed with --no-verify |
| Server-side scanning | Central policy can block pushes or merges when configured to do so | Detection may happen after a push; coverage and enforcement vary |
| Entropy detection | Finds unknown secret types | Higher false positive rate |
| Pattern matching | Often precise for known formats when rules are tuned | Misses formats its rules do not recognize; broad rules can flag examples |
| Baseline files | Reduces noise over time | Requires maintenance |
Implementation Snippets
# Custom pre-commit hook for secret detection
cat > .git/hooks/pre-commit << 'HOOK'
#!/bin/bash
# Check for common secret patterns
if git diff --cached -U0 | grep -E \
'(password|api_key|secret|token)\s*[:=]\s*["\x27][^"\x27]{8,}'; then
echo "ERROR: Potential secret detected in staged changes."
echo "Use environment variables or a secrets manager instead."
exit 1
fi
HOOK
chmod +x .git/hooks/pre-commit
# Scan for specific secret types
grep -rn "AKIA[0-9A-Z]{16}" . # AWS Access Keys
grep -rn "ghp_[a-zA-Z0-9]{36}" . # GitHub Personal Access Tokens
grep -rn "sk-[a-zA-Z0-9]{48}" . # OpenAI API Keys
# Respond to an exposed credential
# 1. Revoke or rotate it in the issuing service, then update its users.
# 2. Assess its permissions, access logs, and potential use; notify the
# provider or security team when appropriate.
# 3. Decide whether repository history cleanup is warranted. Rewriting history
# does not invalidate the credential. Coordinate before updating shared refs.
# 4. Review forks, clones, caches, CI logs, build artifacts, and other copies.
# Contact the hosting provider about cached views or refs where needed.
# See Removing Sensitive Data from History for a cleanup procedure.
Observability Checklist
- Monitor: Secret detection alerts from pre-commit and server-side scanners
- Track: Number of false positives (tune patterns to reduce)
- Alert: Any secret detected in repository history
- Verify: All team members have pre-commit hooks installed
- Audit: Periodic full-history scans with gitleaks
Security & Compliance Considerations
- Pre-commit hooks are local — each developer must install them
- Server-side scanning (GitHub Secret Scanning, GitLab Secret Detection) provides backup
- Revoke or rotate exposed credentials first; assess scope and copies before deciding whether to rewrite history
- Use secret management systems (HashiCorp Vault, AWS Secrets Manager) for production
- See Removing Sensitive Data from History for cleanup
Common Pitfalls / Anti-Patterns
- Relying only on
.gitignore— it’s not a security control - Not rotating leaked secrets — removing from history doesn’t invalidate them
- Ignoring false positives — leads to hook fatigue and bypassing
- Committing
.envfiles — even with fake values, the pattern encourages mistakes - Not scanning history — old commits may contain secrets added before hooks were installed
Quick Recap Checklist
- Install pre-commit hooks with gitleaks or detect-secrets
- Configure server-side secret scanning on your Git platform
- Use
.env.exampletemplates, never commit.envfiles - Revoke or rotate exposed credentials first; assess scope, provider notification, and any needed history cleanup
- Maintain baseline files to reduce false positives
- Scan full history periodically, not just new commits
- Use secret management systems for production credentials
Production Failure: Secret in History + Hook Bypass
Scenario: Secret leaked, developer bypassed hook
# What happened:
# 1. Developer ran: git commit --no-verify -m "Add config"
# 2. Committed .env file with AWS credentials
# 3. Pushed to public repository
# 4. Secret was scanned by bots within minutes
# Symptoms (detected later):
$ gitleaks detect --log-opts="--all"
Found 3 leaks
File: .env, Rule: AWS Access Key, Commit: abc123
# Immediate response:
# 1. Revoke the exposed AWS access key, issue a replacement if needed, and
# update services that used it.
# 2. Review key permissions and AWS access logs to determine what it could
# access and whether it was used. Notify AWS or your security contacts when
# the incident process calls for it.
# 3. Decide whether history cleanup is needed to reduce continued discovery.
# Rewriting history does not revoke the key. Follow the repository host's
# sensitive-data process and coordinate before updating shared refs.
# 4. Check forks, clones, CI logs, build artifacts, caches, and other copies.
# Ask the hosting provider about cached views or refs that need cleanup.
# 4. Prevent recurrence — enforce hooks on CI
# Add to CI pipeline:
# - name: Secret scan
# run: gitleaks detect --log-opts="--all"
# === Hook Bypass Prevention ===
# Developers can bypass local hooks with --no-verify
# Defense in depth:
# Layer 1: Local pre-commit hooks (convenience)
pre-commit install
# Layer 2: CI secret scanning (enforcement)
# GitHub Secret Scanning, GitLab Secret Detection
# Layer 3: Server-side pre-receive hooks (hard block)
# Requires self-hosted Git server
# Layer 4: Monitoring (detection)
# Cloud provider alerts for unusual API usage
Trade-offs: Pre-commit vs CI Scanning
| Aspect | Pre-commit Hooks | CI Scanning |
|---|---|---|
| Speed | Instant (local, < 1s) | Minutes (pipeline queue + run) |
| Coverage | Staged files only | Depends on scanner configuration; may scan a change, selected history, or the full repository |
| Enforcement | Can be bypassed (--no-verify) |
Can fail CI or block merges when configured as a required check |
| Feedback | Immediate, before commit | After push, during PR |
| Setup | Per-developer (each must install) | Central (configured once) |
| False positives | Can interrupt a local commit | Can fail CI or block a merge, depending on policy |
| Secret types | Depends on installed hook and rules | Depends on the scanner, configured rules, and any provider verification |
| Best for | Catching mistakes early | Catching what slips through |
Use both where practical. Pre-commit hooks give developers fast feedback. CI and platform scans can cover commits or paths that local hooks miss, but their history range, patterns, and enforcement depend on configuration.
Implementation: Secret Detection Tool Configuration
# === Gitleaks Configuration ===
# .gitleaks.toml
title = "Gitleaks Custom Config"
[extend]
useDefault = true # Use built-in rules
# Custom rules for your organization
[[rules]]
id = "company-api-key"
description = "Company API Key"
regex = '''COMPANY_API_KEY\s*=\s*['"]?[a-zA-Z0-9]{32,}['"]?'''
tags = ["company", "api-key"]
keywords = ["COMPANY_API_KEY"]
# Allowlist known false positives
[allowlist]
paths = ['''test/fixtures/''', '''mocks/''']
regexes = ['''example\.com''', '''placeholder''']
# === Detect-secrets Configuration ===
# Create baseline
detect-secrets scan > .secrets.baseline
# Audit each finding (mark real secrets vs false positives)
detect-secrets audit .secrets.baseline
# Interactive: mark each finding as "Secret" or "False Positive"
# .secrets.baseline format (auto-generated):
# {
# "generated_at": "2026-03-31T12:00:00Z",
# "results": {
# "config.py": [
# {
# "type": "Secret Keyword",
# "hashed_secret": "abc123...",
# "is_verified": false,
# "line_number": 5
# }
# ]
# }
# }
# === TruffleHog Configuration ===
# Install
# brew install trufflehog
# Scan repository
trufflehog git file://. --only-verified
# Scan with custom rules
# .trufflehog.yaml
rules:
company_secret:
description: "Company Secret Pattern"
regex: 'COMPANY_SECRET_[A-Z0-9]{20,}'
keywords:
- "COMPANY_SECRET_"
# Scan specific branch range
trufflehog git https://github.com/user/repo.git \
--branch=main \
--since-commit=HEAD~50 \
--only-verified
# === Pre-commit Integration ===
# .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
args: ["--baseline", ".gitleaks-baseline.json"]
- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets
args: ["--baseline", ".secrets.baseline"]
- repo: local
hooks:
- id: trufflehog
name: TruffleHog
entry: trufflehog filesystem --only-verified
language: system
pass_filenames: true
Interview Questions
Deleting a secret in a new commit does not remove it from earlier commits. Revoke or rotate the credential first, then assess whether repository history cleanup is warranted. A rewrite can reduce continued discovery, but it does not invalidate the credential or remove copies in clones, forks, caches, artifacts, or logs. If you rewrite shared history, coordinate with collaborators and the hosting provider before updating remote refs.
Pattern-based detection checks configured rules for known formats or keywords. It can be precise when rules are well matched to your credentials, but misses formats the rules do not recognize. Entropy-based detection flags random-looking strings without needing a known format; it can find less structured values but needs tuning to avoid noisy results. Compare scanners against representative credentials and harmless fixtures before choosing rules.
Use baseline files (detect-secrets) or allowlists (gitleaks) to mark known false positives. For example, test fixtures containing fake API keys should be allowlisted. The key is to review each finding initially, then maintain the baseline as code evolves. Never disable scanning entirely.
No. Developers can bypass local hooks with git commit --no-verify, and a server-side scan only covers the content and paths it is configured to scan. Use hooks for fast feedback and CI or platform scanning for additional coverage. Keep monitoring and an incident response process for credentials that still get exposed.
Gitleaks uses configurable rules, including built-in and custom patterns, and supports entropy thresholds and allowlists. git-secrets registers AWS credential patterns and accepts custom regular expressions. Their coverage depends on configured rules and scan scope; either can flag harmless examples or miss an unsupported format. Pick and tune them against the credential types your organization uses, and verify the commands for the installed version.
A root-level .gitallowed file is an allowlist used by git-secrets. Gitleaks has its own allowlist configuration. Keep exceptions narrow and review them: a broad exception can suppress a real credential along with a harmless test value. See the git-secrets documentation and Gitleaks documentation for their current formats.
First revoke or rotate the credential, then assess its permissions, use, and exposure window. Notify the provider or security contacts when the incident process requires it. Decide whether history cleanup would reduce continued exposure, and follow the hosting provider's process; rewriting is not a substitute for revocation and may not remove cached or copied data. If you do rewrite shared history, coordinate the remote update and tell collaborators how to replace their old clones. Check forks, CI logs, artifacts, caches, and other copies, then add a detection rule only if it is specific enough to avoid masking unrelated values.
.gitignore can prevent .env files from being tracked, but it only works for untracked files. If a .env file was ever committed and tracked, .gitignore will not stop it from appearing in status — you must use git rm --cached .env to untrack it. The best practice is to commit a .env.example file with placeholder values and document required variables, while adding .env to .gitignore before the first commit.
Scanning staged changes can stop a credential before it is committed. A history scan can find earlier exposures, including ones from before hooks were installed. Check each tool's scan mode and configured range; a command that scans a working tree or a limited commit range does not necessarily cover every ref. Use local hooks and repository or CI scans for different parts of the workflow.
TruffleHog uses provider-specific detectors and can verify some findings with the issuing service. Verification can raise confidence for supported providers, but it does not cover every secret type; unverified findings still need review. Gitleaks uses configurable built-in and custom rules, with optional entropy checks. Compare their supported detectors and run scope for your installed versions, then tune allowlists or rules against known test values.
Key signals include: unexpected API calls from unknown IPs, billing anomalies in cloud provider accounts, 403/401 error spikes from invalidated credentials, new commits in private repos from unexpected collaborators, and GitHub secret scanning alerts for repos with public access. Organizations should set up automated alerts for these signals and have a runbook for each scenario that covers immediate rotation, history remediation, and post-mortem analysis.
Monorepos require per-team scanning configuration using tool-specific allowlists and path filters. Each team should have its own .gitleaks.toml or equivalent at the team directory level. Use path exclusions to avoid cross-team false positives. Consider sparse checkout and path-based access controls to limit which teams can see which directories. Centralize secret scanning at the CI level with per-team reporting so each team only sees alerts for their code.
History cleanup can reduce later discovery through repository access, but it cannot pull back a copy someone already made. Check forks, clones, caches, CI logs, build artifacts, and third-party systems. Revoke or rotate the credential to stop use of the exposed value; that remains necessary even if the repository history is rewritten.
Secrets managers (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager) provide centralized access control, audit logging, and automatic rotation. Environment variables are simpler but lack audit trails and make rotation harder. Secrets managers add latency (network calls to fetch secrets) and operational complexity. For CI/CD pipelines, a hybrid approach works best: reference secrets via environment variables that are populated by the secrets manager at runtime, never storing actual values in repository configuration files.
Do not treat a commit-message acknowledgment as remediation for a secret alert. If a deployment must proceed while a finding is unresolved, follow a documented exception process with an authorized reviewer, a recorded risk decision, and a time-bound follow-up. Revoke or rotate any exposed credential immediately. CI can warn or block according to the team's policy, but neither response removes an exposed value from repository history or other copies.
SOC 2 and PCI-DSS both require access control and monitoring of sensitive data. Secrets committed to Git represent an access control failure because anyone with repository access — including contractors, CI systems, and former employees with stale access — could view the secret. PCI-DSS Requirement 7 explicitly mandates need-to-know access. Git secret scanning with blocked commits, combined with automated history audits, helps demonstrate compliance. Most auditors will flag any committed secrets in findings if scanning wasn't in place.
Git-crypt is a transparent encryption tool for specific files in a Git repository, while secret scanning tools detect secrets that have already been committed. Git-crypt encrypts files based on .gitattributes rules and decrypts them only for authorized GPG key holders. Scanning tools are detective controls; git-crypt is a preventive control. They complement each other: git-crypt prevents secrets from being stored in plaintext, while scanning catches misconfigured files that git-crypt didn't protect.
Key practices include: developer training on secret hygiene, automated scanning at multiple stages (pre-commit, pre-receive, CI), regular audits of existing repositories using Gitleaks or truffleHog, secret-free templates that scaffold projects with proper .gitignore and .env.example files, pair programming during sensitive changes, and incident response drills for secret leak scenarios. A blameless culture where developers report accidental commits immediately (rather than trying to hide them) significantly reduces overall risk.
Use only synthetic test strings or provider-issued test credentials in an isolated repository to confirm that each configured scan path detects them. Do not seed a live credential as a test. Track how long alerts take, review false positives, and confirm which branches, files, and history ranges each scanner covers.
The future includes server-side Git hooks (pre-receive) as the default in code hosting platforms, AI-powered detection that learns project-specific patterns rather than relying on generic regex, native secret scanning built into GitHub/GitLab (already available as a feature), push-based secret masking that automatically redacts secrets in CI logs, and SOPS/age-based encryption becoming the standard for storing encrypted secrets in repos. The trend is shifting from detection-only toward prevention-through-encryption.
Further Reading
- Gitleaks documentation — Built-in and custom rules, entropy settings, and allowlists
- pre-commit framework — Configuration for running hooks before commits
- detect-secrets documentation — Detector plugins, baselines, and audits
- TruffleHog documentation — Provider detectors and credential verification
- git-secrets documentation — AWS patterns, custom rules, and allowed patterns
- GitHub secret scanning — Supported scanning features and repository availability
Conclusion
Pre-commit hooks can stop some mistakes before a commit, while CI and repository scanners add coverage at later stages. If a credential is exposed, revoke or rotate it first, assess the incident, and then decide whether history cleanup is needed. Check the repository host’s remediation process and look for copies in forks, clones, caches, artifacts, and logs; a clean history does not revoke a credential or erase those copies.
Category
Related Posts
Removing Sensitive Data from Git History
Using git filter-repo, BFG Repo-Cleaner, and git filter-branch to scrub secrets, passwords, and credentials from Git history. Step-by-step remediation guide.
Signed Commits (GPG/SSH)
Learn to sign Git commits with GPG or SSH keys, verify the signed object locally, and understand how hosting platforms decide whether to show a verification status.
Centralized vs Distributed VCS: Team Trade-offs
Compare centralized and distributed version control by offline work, repository size, access control, branching, review, and migration effort.