git-security-checks

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git Security Checks

Git安全检查

Expert guidance for pre-commit security validation and secret detection using gitleaks and pre-commit hooks.
关于使用gitleaks和pre-commit钩子进行提交前安全验证与秘密检测的专业指导。

Core Expertise

核心能力

  • gitleaks: Scan for hardcoded secrets and credentials using regex + entropy analysis
  • Pre-commit Hooks: Automated security validation before commits
  • Declarative Allowlisting: Manage false positives via
    .gitleaks.toml
    configuration
  • Security-First Workflow: Prevent credential leaks before they happen
  • gitleaks: 使用正则表达式+熵分析扫描硬编码的秘密和凭证
  • Pre-commit Hooks: 提交前自动执行安全验证
  • 声明式白名单管理: 通过
    .gitleaks.toml
    配置管理误报
  • 安全优先工作流: 在凭证泄露发生前加以阻止

Quick Security Scan (Recommended)

快速安全扫描(推荐)

Run the comprehensive security scan pipeline in one command:
bash
undefined
通过一条命令运行全面的安全扫描流水线:
bash
undefined

Full scan: check all tracked files

完整扫描:检查所有已追踪文件

bash "${CLAUDE_PLUGIN_ROOT}/skills/git-security-checks/scripts/security-scan.sh"
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-security-checks/scripts/security-scan.sh"

Staged-only: check only files about to be committed

仅暂存文件扫描:仅检查即将提交的文件

bash "${CLAUDE_PLUGIN_ROOT}/skills/git-security-checks/scripts/security-scan.sh" --staged-only

The script checks: gitleaks scan, sensitive file patterns, .gitignore coverage, high-entropy strings in diffs, and pre-commit hook status. See [scripts/security-scan.sh](scripts/security-scan.sh) for details.
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-security-checks/scripts/security-scan.sh" --staged-only

该脚本会检查:gitleaks扫描、敏感文件模式、.gitignore覆盖范围、差异中的高熵字符串以及pre-commit钩子状态。详情请查看[scripts/security-scan.sh](scripts/security-scan.sh)。

Gitleaks Workflow

Gitleaks工作流

Initial Setup

初始设置

bash
undefined
bash
undefined

Install gitleaks (macOS)

安装gitleaks(macOS)

brew install gitleaks
brew install gitleaks

Install gitleaks (Go)

安装gitleaks(Go)

go install github.com/gitleaks/gitleaks/v8@latest
go install github.com/gitleaks/gitleaks/v8@latest

Install gitleaks (binary download)

安装gitleaks(二进制下载)

Scan repository

扫描仓库

gitleaks detect --source .
gitleaks detect --source .

Scan with verbose output

启用详细输出扫描

gitleaks detect --source . --verbose
undefined
gitleaks detect --source . --verbose
undefined

Configuration

配置

Create
.gitleaks.toml
for project-specific allowlists:
toml
title = "Gitleaks Configuration"

[extend]
useDefault = true

[allowlist]
description = "Project-wide allowlist for false positives"
paths = [
    '''test/fixtures/.*''',
    '''.*\.test\.(ts|js)$''',
]

regexes = [
    '''example\.com''',
    '''localhost''',
    '''fake-key-for-testing''',
]
创建
.gitleaks.toml
以实现项目特定的白名单:
toml
title = "Gitleaks Configuration"

[extend]
useDefault = true

[allowlist]
description = "Project-wide allowlist for false positives"
paths = [
    '''test/fixtures/.*''',
    '''.*\.test\.(ts|js)$''',
]

regexes = [
    '''example\.com''',
    '''localhost''',
    '''fake-key-for-testing''',
]

Pre-commit Scan Workflow

提交前扫描工作流

Run gitleaks before every commit:
bash
undefined
在每次提交前运行gitleaks:
bash
undefined

Scan for secrets in current state

扫描当前状态中的秘密

gitleaks detect --source .
gitleaks detect --source .

Scan only staged changes (pre-commit mode)

仅扫描暂存的变更(提交前模式)

gitleaks protect --staged
gitleaks protect --staged

Scan with specific config

使用特定配置扫描

gitleaks detect --source . --config .gitleaks.toml
undefined
gitleaks detect --source . --config .gitleaks.toml
undefined

Managing False Positives

管理误报

Gitleaks provides three declarative methods for handling false positives:
1. Inline comments — mark specific lines:
bash
undefined
Gitleaks提供三种声明式方法来处理误报:
1. 内联注释 — 标记特定行:
bash
undefined

This line is safe

此行安全

API_KEY = "fake-key-for-testing-only" # gitleaks:allow
API_KEY = "fake-key-for-testing-only" # gitleaks:allow

Works in any language

适用于任何语言

password = "test-fixture" # gitleaks:allow

**2. Path-based exclusions** — in `.gitleaks.toml`:

```toml
[allowlist]
paths = [
    '''test/fixtures/.*''',
    '''.*\.example$''',
    '''package-lock\.json$''',
]
3. Regex-based allowlists — for specific patterns:
toml
[allowlist]
regexes = [
    '''example\.com''',
    '''localhost''',
    '''PLACEHOLDER''',
]
4. Per-rule allowlists — target specific detection rules:
toml
[[rules]]
id = "generic-api-key"
description = "Generic API Key"

[rules.allowlist]
regexes = ['''test-api-key-.*''']
paths = ['''test/.*''']
password = "test-fixture" # gitleaks:allow

**2. 基于路径的排除** — 在`.gitleaks.toml`中配置:

```toml
[allowlist]
paths = [
    '''test/fixtures/.*''',
    '''.*\.example$''',
    '''package-lock\.json$''',
]
3. 基于正则的白名单 — 针对特定模式:
toml
[allowlist]
regexes = [
    '''example\.com''',
    '''localhost''',
    '''PLACEHOLDER''',
]
4. 按规则白名单 — 针对特定检测规则:
toml
[[rules]]
id = "generic-api-key"
description = "Generic API Key"

[rules.allowlist]
regexes = ['''test-api-key-.*''']
paths = ['''test/.*''']

Complete Pre-commit Security Flow

完整的提交前安全流程

bash
undefined
bash
undefined

1. Scan for secrets

1. 扫描秘密

gitleaks protect --staged
gitleaks protect --staged

2. Run all pre-commit hooks

2. 运行所有提交前钩子

pre-commit run --all-files --show-diff-on-failure
pre-commit run --all-files --show-diff-on-failure

3. Stage your actual changes

3. 暂存实际变更

git add src/file.ts
git add src/file.ts

4. Show what's staged

4. 查看暂存内容

git status git diff --cached --stat
git status git diff --cached --stat

5. Commit if everything passes

5. 所有检查通过后提交

git commit -m "feat(auth): add authentication module"
undefined
git commit -m "feat(auth): add authentication module"
undefined

Pre-commit Hook Integration

提交前钩子集成

.pre-commit-config.yaml

.pre-commit-config.yaml

Example configuration with gitleaks:
yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.22.1
    hooks:
      - id: gitleaks
包含gitleaks的示例配置:
yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.22.1
    hooks:
      - id: gitleaks

Running Pre-commit Hooks

运行提交前钩子

bash
undefined
bash
undefined

Run all hooks on all files

在所有文件上运行所有钩子

pre-commit run --all-files
pre-commit run --all-files

Run all hooks on staged files only

仅在暂存文件上运行所有钩子

pre-commit run
pre-commit run

Run specific hook

运行特定钩子

pre-commit run gitleaks
pre-commit run gitleaks

Show diff on failure for debugging

失败时显示差异以进行调试

pre-commit run --all-files --show-diff-on-failure
pre-commit run --all-files --show-diff-on-failure

Install hooks to run automatically on commit

安装钩子以在提交时自动运行

pre-commit install
undefined
pre-commit install
undefined

Common Secret Patterns

常见秘密模式

Gitleaks ships with 140+ built-in rules covering:
  • API Keys: AWS, GitHub, Stripe, Google, Azure, etc.
  • Authentication Tokens: JWT, OAuth tokens, session tokens
  • Passwords: Hardcoded passwords in config files
  • Private Keys: RSA, SSH, PGP private keys
  • Database Credentials: Connection strings with passwords
  • Generic Secrets: High-entropy strings that look like secrets
Gitleaks内置140+规则,涵盖:
  • API密钥: AWS、GitHub、Stripe、Google、Azure等
  • 认证令牌: JWT、OAuth令牌、会话令牌
  • 密码: 配置文件中的硬编码密码
  • 私钥: RSA、SSH、PGP私钥
  • 数据库凭证: 包含密码的连接字符串
  • 通用秘密: 看起来像秘密的高熵字符串

Examples of What Gets Detected

检测示例

bash
undefined
bash
undefined

Detected: Hardcoded API key

被检测:硬编码API密钥

API_KEY = "sk_live_abc123def456ghi789" # gitleaks:allow
API_KEY = "sk_live_abc123def456ghi789" # gitleaks:allow

Detected: AWS credentials

被检测:AWS凭证

aws_access_key_id = AKIAIOSFODNN7EXAMPLE # gitleaks:allow
aws_access_key_id = AKIAIOSFODNN7EXAMPLE # gitleaks:allow

Detected: Database password

被检测:数据库密码

DB_URL = "postgresql://user:Pa$$w0rd@localhost/db" # gitleaks:allow
DB_URL = "postgresql://user:Pa$$w0rd@localhost/db" # gitleaks:allow

Detected: Private key # gitleaks:allow

被检测:私钥 # gitleaks:allow

-----BEGIN RSA PRIVATE KEY----- # gitleaks:allow MIIEpAIBAAKCAQEA... # gitleaks:allow
undefined
-----BEGIN RSA PRIVATE KEY----- # gitleaks:allow MIIEpAIBAAKCAQEA... # gitleaks:allow
undefined

Managing False Positives

管理误报

Excluding Files

排除文件

In
.gitleaks.toml
:
toml
[allowlist]
paths = [
    '''package-lock\.json$''',
    '''.*\.lock$''',
    '''test/.*\.py$''',
]
.gitleaks.toml
中:
toml
[allowlist]
paths = [
    '''package-lock\.json$''',
    '''.*\.lock$''',
    '''test/.*\.py$''',
]

Inline Ignore Comments

内联忽略注释

python
undefined
python
undefined

In code, mark false positives

在代码中标记误报

api_key = "test-key-1234" # gitleaks:allow
api_key = "test-key-1234" # gitleaks:allow

Works in any language comment style

适用于任何语言的注释风格

password = "fake-password" # gitleaks:allow
undefined
password = "fake-password" # gitleaks:allow
undefined

Security Best Practices

安全最佳实践

Never Commit Secrets

切勿提交秘密

  • Use environment variables: Store secrets in .env files (gitignored)
  • Use secret managers: AWS Secrets Manager, HashiCorp Vault, etc.
  • Use CI/CD secrets: GitHub Secrets, GitLab CI/CD variables
  • Rotate leaked secrets: If accidentally committed, rotate immediately
  • 使用环境变量: 将秘密存储在.env文件中(加入.gitignore)
  • 使用秘密管理器: AWS Secrets Manager、HashiCorp Vault等
  • 使用CI/CD秘密: GitHub Secrets、GitLab CI/CD变量
  • 轮换泄露的秘密: 如果意外提交,立即轮换

Secrets File Management

秘密文件管理

bash
undefined
bash
undefined

Example .gitignore for secrets

示例.gitignore用于排除秘密文件

.env .env.local .env.*.local *.pem *.key credentials.json config/secrets.yml .api_tokens
undefined
.env .env.local .env.*.local *.pem *.key credentials.json config/secrets.yml .api_tokens
undefined

Handling Legitimate Secrets in Repo

在仓库中处理合法秘密

For test fixtures or examples:
bash
undefined
对于测试 fixture 或示例:
bash
undefined

1. Use obviously fake values

1. 使用明显的假值

API_KEY = "fake-key-for-testing-only" # gitleaks:allow
API_KEY = "fake-key-for-testing-only" # gitleaks:allow

2. Use placeholders

2. 使用占位符

API_KEY = "<your-api-key-here>" # gitleaks:allow
API_KEY = "<your-api-key-here>" # gitleaks:allow

3. Add path exclusion in .gitleaks.toml for test fixtures

3. 在.gitleaks.toml中为测试fixture添加路径排除

undefined
undefined

Emergency: Secret Leaked to Git History

紧急情况:秘密泄露到Git历史

If a secret is committed and pushed:
如果秘密已提交并推送:

Immediate Actions

立即行动

bash
undefined
bash
undefined

1. ROTATE THE SECRET IMMEDIATELY

1. 立即轮换秘密

- Change passwords, revoke API keys, regenerate tokens

- 修改密码、撤销API密钥、重新生成令牌

- Do this BEFORE cleaning git history

- 在清理Git历史之前执行此操作

2. Remove from current commit (if just committed)

2. 从当前提交中移除(如果刚提交)

git reset --soft HEAD~1
git reset --soft HEAD~1

Remove secret from files

从文件中移除秘密

git add . git commit -m "fix(security): remove leaked credentials"
git add . git commit -m "fix(security): remove leaked credentials"

3. Force push (if not shared widely)

3. 强制推送(如果未广泛共享)

git push --force-with-lease origin branch-name
undefined
git push --force-with-lease origin branch-name
undefined

Full History Cleanup

完整历史清理

bash
undefined
bash
undefined

Use git-filter-repo to remove from all history

使用git-filter-repo从所有历史中移除

pip install git-filter-repo
pip install git-filter-repo

Remove specific file from all history

从所有历史中移除特定文件

git filter-repo --path path/to/secret/file --invert-paths
git filter-repo --path path/to/secret/file --invert-paths

Remove specific string from all files

从所有文件中移除特定字符串

git filter-repo --replace-text <(echo "SECRET_KEY=abc123==>SECRET_KEY=REDACTED")
undefined
git filter-repo --replace-text <(echo "SECRET_KEY=abc123==>SECRET_KEY=REDACTED")
undefined

Prevention

预防措施

bash
undefined
bash
undefined

Always run security checks before committing

提交前始终运行安全检查

pre-commit run gitleaks
pre-commit run gitleaks

Check what's being committed

检查即将提交的内容

git diff --cached
git diff --cached

Use .gitignore for sensitive files

对敏感文件使用.gitignore

echo ".env" >> .gitignore echo ".api_tokens" >> .gitignore
undefined
echo ".env" >> .gitignore echo ".api_tokens" >> .gitignore
undefined

Workflow Integration

工作流集成

Daily Development Flow

日常开发流程

bash
undefined
bash
undefined

Before staging any files

暂存任何文件之前

gitleaks protect --staged pre-commit run --all-files
gitleaks protect --staged pre-commit run --all-files

Stage changes

暂存变更

git add src/feature.ts
git add src/feature.ts

Final check before commit

提交前最终检查

git diff --cached # Review changes gitleaks protect --staged # One more scan
git diff --cached # 查看变更 gitleaks protect --staged # 再次扫描

Commit

提交

git commit -m "feat(feature): add new capability"
undefined
git commit -m "feat(feature): add new capability"
undefined

CI/CD Integration

CI/CD集成

yaml
undefined
yaml
undefined

Example GitHub Actions workflow

示例GitHub Actions工作流

name: Security Checks
on: [push, pull_request]
jobs: security: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Gitleaks uses: gitleaks/gitleaks-action@v2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
undefined
name: Security Checks
on: [push, pull_request]
jobs: security: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Gitleaks uses: gitleaks/gitleaks-action@v2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
undefined

Troubleshooting

故障排除

Too Many False Positives

误报过多

bash
undefined
bash
undefined

Check what rules are triggering

检查触发的规则

gitleaks detect --source . --verbose 2>&1 | head -50
gitleaks detect --source . --verbose 2>&1 | head -50

Add targeted allowlists in .gitleaks.toml

在.gitleaks.toml中添加针对性白名单

Use path exclusions for test fixtures

对测试fixture使用路径排除

Use regex exclusions for known safe patterns

对已知安全模式使用正则排除

Use inline gitleaks:allow for individual lines

对单独行使用内联gitleaks:allow

undefined
undefined

Pre-commit Hook Failing

提交前钩子失败

bash
undefined
bash
undefined

Run pre-commit in verbose mode

以详细模式运行pre-commit

pre-commit run gitleaks --verbose
pre-commit run gitleaks --verbose

Check gitleaks config validity

检查gitleaks配置有效性

gitleaks detect --source . --config .gitleaks.toml --verbose
gitleaks detect --source . --config .gitleaks.toml --verbose

Update pre-commit hooks

更新pre-commit钩子

pre-commit autoupdate
undefined
pre-commit autoupdate
undefined

Scanning Git History

扫描Git历史

bash
undefined
bash
undefined

Scan entire git history for leaked secrets

扫描整个Git历史以查找泄露的秘密

gitleaks detect --source . --log-opts="--all"
gitleaks detect --source . --log-opts="--all"

Scan specific commit range

扫描特定提交范围

gitleaks detect --source . --log-opts="HEAD~10..HEAD"
gitleaks detect --source . --log-opts="HEAD~10..HEAD"

Generate JSON report

生成JSON报告

gitleaks detect --source . --report-format json --report-path gitleaks-report.json
undefined
gitleaks detect --source . --report-format json --report-path gitleaks-report.json
undefined

Tools Reference

工具参考

Gitleaks Commands

Gitleaks命令

bash
undefined
bash
undefined

Detect secrets in repository

检测仓库中的秘密

gitleaks detect --source .
gitleaks detect --source .

Protect staged changes (pre-commit mode)

保护暂存的变更(提交前模式)

gitleaks protect --staged
gitleaks protect --staged

Scan with custom config

使用自定义配置扫描

gitleaks detect --source . --config .gitleaks.toml
gitleaks detect --source . --config .gitleaks.toml

Verbose output

详细输出

gitleaks detect --source . --verbose
gitleaks detect --source . --verbose

JSON report

JSON报告

gitleaks detect --source . --report-format json --report-path report.json
gitleaks detect --source . --report-format json --report-path report.json

Scan git history

扫描Git历史

gitleaks detect --source . --log-opts="--all"
gitleaks detect --source . --log-opts="--all"

Scan specific commit range

扫描特定提交范围

gitleaks detect --source . --log-opts="main..HEAD"
undefined
gitleaks detect --source . --log-opts="main..HEAD"
undefined

pre-commit Commands

pre-commit命令

bash
undefined
bash
undefined

Install hooks

安装钩子

pre-commit install
pre-commit install

Run all hooks

运行所有钩子

pre-commit run --all-files
pre-commit run --all-files

Run specific hook

运行特定钩子

pre-commit run gitleaks
pre-commit run gitleaks

Update hook versions

更新钩子版本

pre-commit autoupdate
pre-commit autoupdate

Uninstall hooks

卸载钩子

pre-commit uninstall
undefined
pre-commit uninstall
undefined