一个小巧、无依赖的密钥扫描器,适用于源代码和 git 历史,并附带可直接使用的 GitLab CI 任务。
它能在泄露的 API 密钥、令牌、私钥和密码进入生产环境之前将其发现,包括那些曾被提交过一次、后来被“删除”但仍留在历史记录中的密钥。
$ secretscan scan . --history
[HIGH ] url-credentials deploy.sh:1 (commit 79831acaf3, Dev <[email protected]>)
Credentials embedded in a URL: Fake********
[HIGH ] aws-access-key-id settings.py:1 (commit 79831acaf3, Dev <[email protected]>)
AWS access key ID: AKIA************
2 potential secret(s) found.
在该演示中,AWS 密钥在后续提交中从 settings.py 里被删除。普通文件扫描会显示仓库是干净的,但该密钥仍可通过 git log -p 恢复,因此它仍然处于泄露状态。
password = "..." 规则。changeme、${API_KEY}、{{ vault_token }} 和 <your-password> 等值。--rev-range base..HEAD 仅扫描新提交。.secretscanignore(gitignore 风格的通配符)和内联 # secretscan:ignore。--fail-on 严重性阈值。pip install git+https://gitlab.com/DaveyD347/secrets-scanner.git
# or, from a clone
pip install -e ".[dev]"
secretscan scan # scan the current directory's files
secretscan scan path/to/repo --history # files + entire git history
secretscan scan . --history-only # history only
secretscan scan . --rev-range origin/main..HEAD # only commits not yet on main
secretscan scan . --format json -o findings.json
secretscan scan . --fail-on high # only fail on high/critical
secretscan rules # list rules
| 退出码 | 含义 |
|---|---|
| 0 | 没有达到或超过 --fail-on 阈值的发现项 |
| 1 | 存在达到或超过 --fail-on 阈值的发现项 |
| 2 | 用法错误(路径错误、不是 git 仓库等) |
添加一个内联标记:
EXAMPLE_KEY = "..." # secretscan:ignore
或在仓库根目录创建 .secretscanignore:
# test fixtures
tests/fixtures/
*.lock
将可复用作业添加到任意项目:
include:
- remote: "https://gitlab.com/DaveyD347/secrets-scanner/-/raw/main/templates/secretscan.gitlab-ci.yml"
该任务会克隆完整历史(GIT_DEPTH: 0),在合并请求流水线上仅扫描新增提交,在其他情况下扫描整个历史,发现结果时使流水线失败,并将 gl-secret-detection-report.json 作为 secret_detection 报告上传。在 GitLab Ultimate 上,这些发现会显示在合并请求安全小组件和漏洞报告中;在其他版本中,该报告仍会作为可下载的产物保留。设置 SECRETSCAN_FAIL_ON 以调整阈值。
本仓库自身的 .gitlab-ci.yml 会进行代码检查、在 Python 3.10 至 3.13 上运行带覆盖率的测试,并针对自身历史运行扫描器。
src/secretscan/rules.py)是正则表达式。第一个捕获组即为密钥。
通用规则还设置了最小熵值,因此 password = "aaaaaaaaaaaa" 不会触发。.git、node_modules、虚拟环境、二进制文件(NUL 字节嗅探)、
超过 2 MB 的文件以及 .secretscanignore 中的任何内容。git log --all --reverse -p --unified=0 并解析差异流,从每个 @@ 块头中跟踪
当前提交、文件和新侧行号。仅检查 + 行,因此密钥只会在引入它的提交处报告一次,
而不是在之后的每个提交中都报告一次。pip install -e ".[dev]"
pytest
ruff check . && ruff format --check .
测试夹具从不包含真实凭据。tests/fakes.py 中的假令牌在运行时由片段拼接而成,因此仓库本身不包含任何完整的令牌形状字符串。这使 CI 自扫描保持干净,并避免触发 GitLab 推送保护。
MIT