目录

Git 提交安全:gitleaks + GitGuardian 实战

背景

在 commit 之前检测代码中是否包含密钥、密码、Token 等敏感信息,防止泄露到远程仓库。

方案选型

工具 层级 速度 检测能力 是否本地
gitleaks pre-commit ~50ms 60+ 规则,覆盖主流云服务 完全本地
ggshield (GitGuardian) pre-push ~1-3s 350+ 规则,最强覆盖 部分需 SaaS 通信

选择 gitleaks + ggshield 组合

  • 日常 commit:gitleaks 快速拦截,几乎无感
  • push 前:ggshield 深度扫描兜底

安装

# gitleaks(macOS)
brew install gitleaks

# ggshield(macOS)
brew install pipx
pipx install ggshield

# 授权 GitGuardian
ggshield auth login

全局 Git Hooks 配置

# 创建全局 hooks 目录
mkdir -p ~/.git-hooks

# 告诉 Git 所有仓库使用这个目录的 hooks
git config --global core.hooksPath ~/.git-hooks

pre-commit hook(gitleaks)

文件路径:~/.git-hooks/pre-commit

#!/bin/sh
# pre-commit: gitleaks 快速拦截密钥泄露
echo "Running gitleaks secret scan..."
gitleaks protect --staged --source . --no-banner 2>/dev/null
RESULT=$?
if [ $RESULT -ne 0 ]; then
    echo ""
    echo "gitleaks 检测到敏感信息,commit 已拒绝。"
    echo "   请移除密钥后再提交,或用 --no-verify 跳过(不推荐)。"
    exit 1
fi
echo "gitleaks scan passed"
exit 0

pre-push hook(ggshield)

文件路径:~/.git-hooks/pre-push

#!/bin/sh
# pre-push: ggshield 深度扫描(GitGuardian)
echo "Running GitGuardian deep scan..."
ggshield secret scan pre-push
RESULT=$?
if [ $RESULT -ne 0 ]; then
    echo ""
    echo "GitGuardian 检测到敏感信息,push 已拒绝。"
    echo "   请作废已泄露的密钥并清理提交历史。"
    exit 1
fi
echo "GitGuardian scan passed"
exit 0

安装完成后需要赋予执行权限:

chmod +x ~/.git-hooks/pre-commit ~/.git-hooks/pre-push

工作流程

git commit
  → pre-commit: gitleaks protect --staged
    → 发现密钥 → 拒绝 commit
    → 通过 → commit 成功

git push origin main
  → pre-push: ggshield secret scan pre-push
    → 发现密钥 → 拒绝 push
    → 通过 → push 成功

防护范围

  • 全局生效core.hooksPath--global 配置,所有仓库自动生效
  • 新仓库:无需额外配置
  • 已有仓库:同样生效

注意事项

  • git commit --no-verify 可以跳过 hooks,需自律使用
  • 已提交到历史中的密钥需要手动跑 gitleaks detect 全量扫描
  • ggshield 的 pre-push hook 需要先 ggshield auth login 授权
  • 如果某个项目需要项目级别的 hook,需在 ~/.git-hooks/ 中手动处理转发