# https://github.com/Yelp/detect-secrets 项目说明书

生成时间：2026-06-19 17:07:09 UTC

## 目录

- [Overview and Getting Started](#page-1)
- [Plugin System and Detection Strategies](#page-2)
- [CLI Tools, Baselines, and Audit Workflows](#page-3)
- [Filters, Customization, and Advanced Configuration](#page-4)

<a id='page-1'></a>

## Overview and Getting Started

### 相关页面

相关主题：[Plugin System and Detection Strategies](#page-2), [CLI Tools, Baselines, and Audit Workflows](#page-3), [Filters, Customization, and Advanced Configuration](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/Yelp/detect-secrets/blob/main/README.md)
- [setup.py](https://github.com/Yelp/detect-secrets/blob/main/setup.py)
- [CONTRIBUTING.md](https://github.com/Yelp/detect-secrets/blob/main/CONTRIBUTING.md)
- [requirements-dev.txt](https://github.com/Yelp/detect-secrets/blob/main/requirements-dev.txt)
- [detect_secrets/core/plugins/util.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/plugins/util.py)
- [detect_secrets/plugins/private_key.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/plugins/private_key.py)
- [detect_secrets/plugins/keyword.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/plugins/keyword.py)
- [detect_secrets/transformers/yaml.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/transformers/yaml.py)
- [detect_secrets/transformers/config.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/transformers/config.py)
- [detect_secrets/util/filetype.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/util/filetype.py)
- [detect_secrets/core/potential_secret.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/potential_secret.py)
- [detect_secrets/types.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/types.py)
</details>

# 概述与快速上手 (Overview and Getting Started)

## 项目定位与设计目标

`detect-secrets` 是由 Yelp 维护的一款用于在代码库中**检测密钥(secret)** 的 Python 工具。其核心定位并非简单地"找密钥"，而是面向企业级用户提供一套**向后兼容、可系统化运营**的密钥治理方案。资料来源：[README.md:1-15]() 指出，工具围绕三个目标设计：

1. **阻止新密钥进入代码库**（通过 pre-commit 钩子在提交时拦截）；
2. **检测这些预防机制是否被显式绕过**（通过 baseline diff 机制）；
3. **提供统一的管理接口**，供审计与合规流程使用。

与 truffleHog 等工具相比，`detect-secrets` 强调 **baseline（基线）概念**——首次扫描会生成一份"已存在"的密钥清单，后续扫描只报告新增的密钥项，从而避免历史告警噪音。社区曾在 [#75](https://github.com/Yelp/detect-secrets/issues/75) 中讨论过引入 truffleHogRegexes 的可能性，但项目最终维持了自身可插拔的正则体系。

## 系统架构总览

工具的整体结构可以分为三个层次：**入口层（Entry）**、**插件/转换器层（Plugins & Transformers）**、**基线与潜在密钥模型（Baseline & PotentialSecret）**。

```mermaid
graph TD
    A[CLI 入口<br/>detect-secrets] --> B[Pre-commit Hook<br/>detect-secrets-hook]
    A --> C[Scan 流程]
    C --> D[Transformers<br/>yaml / config / ini]
    C --> E[Plugins<br/>keyword / private_key / entropy]
    D --> F[PotentialSecret 模型]
    E --> F
    F --> G[Baseline JSON]
    B --> G
    G --> H[Diff 报告]
```

- **入口层**：通过 `setup.py:43-46` 中声明的 `console_scripts`，注册了两个命令行工具——`detect-secrets`（主命令）和 `detect-secrets-hook`（pre-commit 钩子专用）。资料来源：[setup.py:43-46]()
- **转换器层**：负责把非纯文本文件（如 YAML、INI、properties）拆解为可被逐行扫描的字符串序列。`yaml.py` 使用 PyYAML 节点操作保留原始行号，`config.py` 通过 `configparser` 解析 INI 文件。资料来源：[detect_secrets/transformers/yaml.py:1-40]()，[detect_secrets/transformers/config.py:14-32]()
- **插件层**：每个插件实现 `BasePlugin` 或 `RegexBasedDetector` 接口。`keyword.py` 通过 `DENYLIST` 关键字（如 `password`、`api_key`、`contraseña`）结合后随冒号或等号的形式匹配；`private_key.py` 则直接检查 PEM 私钥头。资料来源：[detect_secrets/plugins/keyword.py:42-58]()，[detect_secrets/plugins/private_key.py:36-44]()
- **数据模型**：`PotentialSecret`（定义于 `core/potential_secret.py`）使用 SHA1 哈希保存密钥原文，避免基线文件中泄露明文；`SecretContext` 命名元组（位于 `types.py`）则将密钥与代码片段、错误信息绑定。资料来源：[detect_secrets/core/potential_secret.py:1-30]()，[detect_secrets/types.py:21-32]()

## 安装与依赖

项目通过 `setup.py` 进行标准的 PyPI 发布。其 `install_requires` 仅包含 `pyyaml` 与 `requests` 两个轻量依赖，确保基础扫描可在大多数环境中运行。资料来源：[setup.py:33-37]()

| 依赖类别 | 包名 | 用途 |
| --- | --- | --- |
| 必装 (`install_requires`) | `pyyaml`, `requests` | YAML 解析、HTTP 配置加载 |
| 可选：词表 (`word_list`) | `pyahocorasick` | Aho-Corasick 字典树加速高频词过滤 |
| 可选：乱码检测 (`gibberish`) | `gibberish-detector` | 检测随机生成字符串 |
| 开发依赖 (`requirements-dev.txt`) | `pytest`, `tox`, `mypy`, `flake8`, `pre-commit` 等 | 测试与静态检查 |

开发者可通过 `pip install -r requirements-dev.txt` 一次性安装所有开发依赖。资料来源：[requirements-dev.txt:1-21]()

> **社区提示**：v1.1.0 版本曾因 `entry_points` 加载方式变更，在 Python 3.8 环境下出现"无法加载任何插件"的回归（参见 Issue [#452](https://github.com/Yelp/detect-secrets/issues/452)）。如果遇到 `[scan] ERROR` 且 `--list-all-plugins` 输出为空，建议回退到 1.0.3 或升级到 v1.5.0（后者已支持 Python 3.10/3.11/3.12，并修复了 OS 无关的基线文件路径问题）。

## 快速上手

### 1. 初始化基线

在仓库根目录执行首次扫描会生成 `.secrets.baseline`：

```bash
detect-secrets scan > .secrets.baseline
```

### 2. 在 pre-commit 中使用

将以下片段加入 `.pre-commit-config.yaml`：

```yaml
repos:
  - repo: https://github.com/Yelp/detect-secrets
    rev: v1.5.0
    hooks:
      - id: detect-secrets-hook
        args: ['--baseline', '.secrets.baseline']
```

`detect-secrets-hook` 入口会在 `pre-commit` 阶段读取基线并对比改动文件，仅报告新增密钥。资料来源：[setup.py:43-46]()

### 3. 自定义插件加载

插件既可来自包内置模块，也可通过 `settings` 中的 `plugins` 配置按 `file://` 路径加载外部类。`get_mapping_from_secret_type_to_class()` 使用 `@lru_cache(maxsize=1)` 缓存映射结果。资料来源：[detect_secrets/core/plugins/util.py:25-50]()

## 开发者上手路径

`CONTRIBUTING.md` 建议贡献者先阅读 `docs/design.md` 了解整体设计，然后通过 `tox -e venv` 或 `python3 -m venv venv` 搭建开发环境。测试使用 `pytest`，例如：

```bash
pytest tests/core/baseline_test.py::TestCreate
```

如果新增插件或误报过滤器，需同时为 `tests/plugins/` 添加对应的根级测试函数。资料来源：[CONTRIBUTING.md:1-50]()

## 已知限制与社区诉求

- **SARIF 输出**：社区在 Issue [#488](https://github.com/Yelp/detect-secrets/issues/488) 中提出增加 SARIF 格式的扫描结果导出，以便与 GitHub Code Scanning 等平台集成，但截至 v1.5.0 仍仅提供 JSON 输出。
- **基线精简**：Issue [#92](https://github.com/Yelp/detect-secrets/issues/92) 建议引入 `--no-line-numbers`、`--no-generated-at` 等选项以减少基线 diff 噪音；该需求在 [#586](https://github.com/Yelp/detect-secrets/pull/586) 中部分通过"OS 无关基线路径"得到缓解。
- **Python 版本支持**：v1.5.0 起正式支持 3.10/3.11/3.12，弃用 3.6/3.7，并预告将在下个版本移除对 3.8 的支持。

## See Also

- 插件开发指南：`docs/plugins.md`
- 设计总览：`docs/design.md`
- 误报过滤器：`docs/filters.md`
- 基线文件格式规范：`detect_secrets/core/baseline.py`

---

<a id='page-2'></a>

## Plugin System and Detection Strategies

### 相关页面

相关主题：[Overview and Getting Started](#page-1), [Filters, Customization, and Advanced Configuration](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [detect_secrets/plugins/base.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/plugins/base.py)
- [detect_secrets/plugins/private_key.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/plugins/private_key.py)
- [detect_secrets/plugins/keyword.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/plugins/keyword.py)
- [detect_secrets/plugins/slack.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/plugins/slack.py)
- [detect_secrets/plugins/github_token.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/plugins/github_token.py)
- [detect_secrets/plugins/gitlab_token.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/plugins/gitlab_token.py)
- [detect_secrets/plugins/pypi_token.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/plugins/pypi_token.py)
- [detect_secrets/plugins/jwt.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/plugins/jwt.py)
- [detect_secrets/core/plugins/util.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/plugins/util.py)
- [detect_secrets/core/plugins/initialize.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/plugins/initialize.py)
- [detect_secrets/audit/analytics.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/audit/analytics.py)
- [testing/plugins.py](https://github.com/Yelp/detect-secrets/blob/main/testing/plugins.py)
- [testing/mocks.py](https://github.com/Yelp/detect-secrets/blob/main/testing/mocks.py)

</details>

# 插件系统与检测策略 (Plugin System and Detection Strategies)

## 概述与设计目标

`detect-secrets` 是一款面向企业级代码库的密钥检测工具，其核心理念并不止于"匹配出可能的字符串"，而是构建一套可扩展、可审计、可向后兼容的检测框架。整套工具围绕三条命令展开：`detect-secrets scan`（生成基线）、`detect-secrets-hook`（增量比对）、`detect-secrets audit`（人工审计），而贯穿其中的是统一的插件注册与发现机制 资料来源：[README.md:1-30]()。

插件系统将"如何检测"与"如何扫描"解耦：基类 `BasePlugin` 规定了 `secret_type`、`analyze_string`、`verify` 等标准接口，开发者只需声明 `secret_type` 与 `denylist` 等属性即可完成一个最小可用的检测器 资料来源：[detect_secrets/plugins/private_key.py:31-50]()。这种设计使新增检测规则或接入企业内部自定义密钥格式时，无需修改核心引擎。

## 插件架构与基类

### 抽象基类与正则检测器家族

所有检测器均继承自 `BasePlugin`，其下又派生出 `RegexBasedDetector`、`KeywordDetector`、`HighEntropyStrings` 等具体基类。下表汇总了仓库内置的几款典型检测器及其策略要点：

| 检测器 | secret_type | 关键检测策略 |
|---|---|---|
| `GitHubTokenDetector` | GitHub Token | 支持 `ghp/gho/ghu/ghs/ghr` 五种新格式前缀 资料来源：[detect_secrets/plugins/github_token.py:10-16]() |
| `GitLabTokenDetector` | GitLab Token | 覆盖 PAT/Deploy/Feed/OAuth/Runner 五类前缀与 20-50 字符 token 体 资料来源：[detect_secrets/plugins/gitlab_token.py:25-50]() |
| `PypiTokenDetector` | PyPI Token | 分别匹配 pypi.org 与 test.pypi.org 两种 base64 头 资料来源：[detect_secrets/plugins/pypi_token.py:9-16]() |
| `JwtTokenDetector` | JSON Web Token | 通过 base64 填充校验过滤形式无效的 JWT 资料来源：[detect_secrets/plugins/jwt.py:10-30]() |
| `PrivateKeyDetector` | Private Key | 借鉴 pre-commit-hooks 的 PEM 头启发式 资料来源：[detect_secrets/plugins/private_key.py:38-50]() |
| `SlackDetector` | Slack Token | 同时支持 token 与 webhook，并具备网络验证能力 资料来源：[detect_secrets/plugins/slack.py:9-30]() |

### 关键字与熵值检测策略

`KeywordDetector` 继承自 `BasePlugin`，其注释明确指出启发式逻辑借鉴自 PyCQA 的 `bandit` 项目。它结合 `PotentialSecret` 与 `FileType` 在源代码上下文中识别"赋值即密钥"的模式 资料来源：[detect_secrets/plugins/keyword.py:30-55]()。该类检测器通过 `analyze_string(string: str) -> Generator[str, None, None]` 流式产出候选字符串，便于与 Aho-Corasick 等多模式匹配引擎配合 资料来源：[detect_secrets/plugins/keyword.py:60-80]()。

`HighEntropyStrings` 家族（`Base64HighEntropyString`、`HexHighEntropyString`）则使用 `pyahocorasick` 高效多模式匹配，再以 Shannon 熵作为筛选条件，可在不依赖具体服务前缀的前提下捕获未知格式的密钥候选项。`requirements-dev.txt` 中明确列出 `pyahocorasick==2.1.0`，可作为部署时的依赖参考 资料来源：[requirements-dev.txt:13-25]()。

## 插件发现与初始化流程

`detect_secrets.core.plugins.util` 模块通过 `get_mapping_from_secret_type_to_class()` 一次性扫描 `detect_secrets.plugins` 包，构建 `secret_type → Plugin 类` 的字典映射 资料来源：[detect_secrets/core/plugins/util.py:20-40]()。该函数同时读取基线配置里 `plugins_used[*].path` 字段，将外部自定义插件通过 `import_file_as_module` 动态导入并合并进映射；为避免重复导入开销，结果通过 `@lru_cache(maxsize=1)` 缓存 资料来源：[detect_secrets/core/plugins/util.py:30-60]()。

初始化阶段由 `detect_secrets/core/plugins/initialize.py` 提供两个关键入口：

- `from_secret_type(secret_type)`：通过人类可读类型查找对应插件；
- `from_plugin_classname(classname)`：通过类名查找，用于兼容旧版本基线 资料来源：[detect_secrets/core/plugins/initialize.py:10-30]()。

当基线引用了不可用的插件（例如跨版本差异）时，日志会提示运行 `pre-commit autoupdate`，并在异常信息中提示"基线由更高版本的 detect-secrets 创建" 资料来源：[detect_secrets/core/plugins/initialize.py:25-45]()。

## 验证、统计与社区反馈

部分插件实现了 `verify()` 方法，以便对候选 token 做二次校验。`SlackDetector` 通过向 `https://slack.com/api/auth.test` 发起请求并解析返回的 `ok` 字段来判断 token 是否真实可用 资料来源：[detect_secrets/plugins/slack.py:25-45]()。验证结果会写入 `PotentialSecret.is_verified`，进而影响 [`detect_secrets/audit/analytics.py`](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/audit/analytics.py) 中的 `StatisticsAggregator` 输出 资料来源：[detect_secrets/audit/analytics.py:30-55]()。

社区中几个高频问题也与插件机制相关：

- **Issue #452 插件加载失败**：在 macOS (Big Sur) + Python 3.8 环境下，`detect-secrets==1.1.0` 因 `pyahocorasick` 等 C 扩展编译失败导致 `scan` 直接报 `ERROR`。规避方式包括降级到 `1.0.3` 或在系统补齐编译依赖。
- **Issue #75 truffleHogRegexes 复用讨论**：社区曾提议把启发式正则统一托管到 [`truffleHogRegexes`](https://github.com/dxa4481/truffleHogRegexes) 等独立仓库，便于协同维护；当前实现仍以内置插件为主。
- **Issue #488 SARIF 输出**：希望在保留 JSON 基线的前提下新增 SARIF 兼容格式，这与插件层解耦，依赖于输出格式化模块后续扩展。

## 自定义插件与测试辅助

开发者可以通过基线文件中的 `plugins` 字段加载外部插件，典型配置示例：

```yaml
plugins_used:
  - path: file:///abs/path/to/my_plugin.py
```

加载逻辑在 `get_mapping_from_secret_type_to_class` 中完成，它只支持 `file://` schema，并通过 `get_plugins_from_file` 动态导入模块内所有继承自 `BasePlugin` 的类 资料来源：[detect_secrets/core/plugins/util.py:40-65]()。

测试侧提供了便利工具：`testing/plugins.py::register_plugin` 是一个上下文管理器，可在用例范围内临时挂载自定义插件（例如 `HippoDetector`），退出时再调用 `cache_clear()` 重置映射 资料来源：[testing/plugins.py:9-30]()。`testing/mocks.py` 中的 `PrinterShim` 与 `mock_printer` 则用于捕获 `log` 模块的输出，便于断言错误信息 资料来源：[testing/mocks.py:18-40]()。

## 参见

- [README.md](https://github.com/Yelp/detect-secrets/blob/main/README.md)
- [docs/design.md](https://github.com/Yelp/detect-secrets/blob/main/docs/design.md)
- [detect_secrets/core/plugins/util.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/plugins/util.py)
- [detect_secrets/core/plugins/initialize.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/plugins/initialize.py)
- [CHANGELOG.md](https://github.com/Yelp/detect-secrets/blob/main/CHANGELOG.md)

---

<a id='page-3'></a>

## CLI Tools, Baselines, and Audit Workflows

### 相关页面

相关主题：[Overview and Getting Started](#page-1), [Plugin System and Detection Strategies](#page-2), [Filters, Customization, and Advanced Configuration](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [detect_secrets/main.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/main.py)
- [detect_secrets/pre_commit_hook.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/pre_commit_hook.py)
- [detect_secrets/core/baseline.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/baseline.py)
- [detect_secrets/core/secrets_collection.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/secrets_collection.py)
- [detect_secrets/core/potential_secret.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/potential_secret.py)
- [detect_secrets/core/scan.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/scan.py)
- [detect_secrets/audit/analytics.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/audit/analytics.py)
- [detect_secrets/audit/report.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/audit/report.py)
- [detect_secrets/core/plugins/initialize.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/plugins/initialize.py)
- [detect_secrets/core/plugins/util.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/plugins/util.py)
- [setup.py](https://github.com/Yelp/detect-secrets/blob/main/setup.py)
- [README.md](https://github.com/Yelp/detect-secrets/blob/main/README.md)
</details>

# CLI 工具、基线与审计工作流

## 1. 概述与设计目标

`detect-secrets` 是一套面向企业级代码库的秘密检测工具集，其核心思想是**关注点分离**——承认历史代码中可能已存在敏感信息（建立"基线 baseline"），并通过持续集成流程阻止新的秘密进入仓库。CLI 工具承担三项职责：生成基线、扫描变更、对历史发现进行审计。

两个控制台入口点由 `setup.py` 的 `entry_points` 注册：`detect-secrets`（主 CLI）和 `detect-secrets-hook`（pre-commit 钩子）。资料来源：[setup.py]() 资料来源：[README.md]()

## 2. CLI 入口点与命令

主入口 `detect_secrets/main.py` 暴露了 `scan`、`audit` 等子命令，扫描流程通过 `core/scan.py` 中的 `scan_file` 与 `get_files_to_scan` 完成文件枚举与过滤。`get_files_to_scan` 在未指定 `--all-files` 时会优先调用 `git.get_tracked_files` 获取版本控制跟踪的文件；若目录非 git 仓库则回退到全部文件。资料来源：[detect_secrets/core/scan.py]()

基线文件由 `core/baseline.py` 负责持久化为 JSON 格式，结构为 `{ "version": ..., "plugins_used": [...], "filters_used": [...], "results": { "filename": [secret_hash, ...] } }`。`secrets_collection.py` 中的 `SecretsCollection` 将扫描结果以哈希形式聚合到该结构，并支持与历史基线合并——这正是 v1.5.0 引入的"OS-agnostic baseline"特性的实现基础。资料来源：[detect_secrets/core/baseline.py]() 资料来源：[detect_secrets/core/secrets_collection.py]()

## 3. 基线工作流

```mermaid
flowchart LR
    A[git 仓库] --> B[detect-secrets scan]
    B --> C[.secrets.baseline]
    C --> D{PR / 提交}
    D --> E[detect-secrets-hook]
    E --> F{新增 secret?}
    F -->|是| G[阻断提交]
    F -->|否| H[通过]
    C --> I[detect-secrets audit]
    I --> J[人工审核<br/>标记真/假阳性]
```

生成基线后，可通过 `detect-secrets scan --baseline .secrets.baseline` 进行增量更新：旧条目自动升级，消失的条目被移除，已标注的 secret 标签得以保留。资料来源：[README.md]()

社区曾要求支持 `--no-line-numbers`、`--no-generated-at` 等差异最小化选项（issue #92），并希望以 SARIF 标准格式输出扫描结果（issue #488）——这些是当前 CLI 尚未原生覆盖的扩展点。

## 4. 审计工作流

`detect_secrets/audit/` 子包提供两套能力：

- `analytics.py` 中的 `StatisticsAggregator` 按插件类型聚合已标记 secret 的真阳性、假阳性与未审核计数，输出机器可读的统计字典。资料来源：[detect_secrets/audit/analytics.py]()
- `report.py` 中的 `generate_report` 读取基线后按 `SecretClassToPrint`（`REAL_SECRET` / `FALSE_POSITIVE`）分类，重新定位文件中所有出现位置并生成报告。资料来源：[detect_secrets/audit/report.py]()

`PotentialSecret` 对象承载 `is_secret` 字段（`True` / `False` / `None`），是审计标注的最小数据单元。`audit` 命令依赖此结构判断每个命中是否需要人工介入。资料来源：[detect_secrets/core/potential_secret.py]()

## 5. 插件初始化与常见故障

插件通过 `core/plugins/util.py` 的 `get_mapping_from_secret_type_to_class` 懒加载：内置插件从 `detect_secrets.plugins` 包中按 `secret_type` 自动发现，自定义插件则从 `settings.yaml` 中 `path` 字段指定的 Python 文件加载。资料来源：[detect_secrets/core/plugins/util.py]()

issue #452 报告 v1.1.0 在 Python 3.8 下"无插件可加载"，根因通常是 `import_types_from_package` 过滤条件或自定义插件路径在新解释器上抛错；当 `from_secret_type` 抛出 `TypeError` 时，CLI 会在 stderr 输出 "No such plugin" 提示，提示用户运行 `pre-commit autoupdate` 升级 baseline。资料来源：[detect_secrets/core/plugins/initialize.py]()

## 6. pre-commit 钩子

`detect_secrets/pre_commit_hook.py` 是 Git pre-commit 阶段执行的轻量扫描器。典型用法通过 `git diff --staged --name-only -z | xargs -0 detect-secrets-hook --baseline .secrets.baseline` 仅对暂存文件运行，避免全量扫描。资料来源：[detect_secrets/pre_commit_hook.py]()

## See Also

- [插件系统与自定义检测器](./plugins.md)
- [过滤器与白名单机制](./filters.md)
- [配置参考：settings.yaml](./configuration.md)

---

<a id='page-4'></a>

## Filters, Customization, and Advanced Configuration

### 相关页面

相关主题：[Overview and Getting Started](#page-1), [Plugin System and Detection Strategies](#page-2), [CLI Tools, Baselines, and Audit Workflows](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [detect_secrets/settings.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/settings.py)
- [detect_secrets/filters/allowlist.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/filters/allowlist.py)
- [detect_secrets/filters/common.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/filters/common.py)
- [detect_secrets/filters/heuristic.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/filters/heuristic.py)
- [detect_secrets/filters/regex.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/filters/regex.py)
- [detect_secrets/filters/wordlist.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/filters/wordlist.py)
- [detect_secrets/core/plugins/util.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/plugins/util.py)
- [detect_secrets/core/potential_secret.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/potential_secret.py)
- [detect_secrets/util/semver.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/util/semver.py)
</details>

# 过滤器、自定义与高级配置

## 一、概述与设计目标

`detect-secrets` 的核心理念并非"一锤子找出所有密钥"，而是**通过基线（baseline）建立职责分离**：先承认仓库中可能已经存在历史密钥（由基线固化），再通过预提交钩子与 CI 比对机制，**阻止新密钥进入代码库**（参见 [README.md](https://github.com/Yelp/detect-secrets/blob/main/README.md)）。

为了在"低误报"与"高召回"之间取得平衡，工具提供了**多层过滤器（filters）**与**可扩展的配置体系**。任何被插件识别出的潜在密钥，在写入基线或阻断提交之前，都会先经过这些过滤器的裁剪，从而削减噪声并提升真实密钥的识别质量。资料来源：[detect_secrets/settings.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/settings.py)

## 二、过滤器体系架构

`detect-secrets` 在 `detect_secrets/filters/` 目录下按照**职责维度**组织了若干过滤器实现。它们通常以**可调用对象**的形式被插件链式调用，亦可在基线审计阶段手工调用。

### 2.1 通用过滤器（common）

`common.py` 定义了跨插件复用的工具，例如对字符串相似度、字符构成、长度阈值等的统一封装。它为其他过滤器提供基础判断能力，避免重复实现。资料来源：[detect_secrets/filters/common.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/filters/common.py)

### 2.2 启发式过滤器（heuristic）

`heuristic.py` 实现基于规则的"经验式"过滤。例如，要求密钥字符串中至少包含一定比例的不同字符、排除明显的占位符（如 `xxxxxxxx`、`example`、`changeme`）等。这类过滤器无需依赖外部数据，是**降低误报的第一道闸口**。资料来源：[detect_secrets/filters/heuristic.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/filters/heuristic.py)

### 2.3 正则表达式过滤器（regex）

`regex.py` 通过 `RegexBasedDetector` 与 `denylist` 模式，对匹配到的字符串施加更精细的正则裁剪。它既可被插件内置使用，也允许用户在配置中**追加自定义正则**进行二次过滤。社区问题 [#92](https://github.com/Yelp/detect-secrets/issues/92) 中提到的"基线 diff 最小化"诉求，部分思路就是借助正则过滤器**隐藏易变字段（如行号、生成时间）**，以减少基线噪声。资料来源：[detect_secrets/filters/regex.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/filters/regex.py)

### 2.4 白名单过滤器（allowlist）

`allowlist.py` 中的 `get_allowlist_regexes()` 用于加载"显式豁免"的正则集合。常用于将已知安全的占位 token、测试夹具等排除在扫描结果之外。值得注意的是，**白名单是以源码注释 `pragma: allowlist secret` 等机制**与代码深度耦合的，能够在文件被改写后仍保留追溯能力。资料来源：[detect_secrets/filters/allowlist.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/filters/allowlist.py)

### 2.5 词表过滤器（wordlist）

`wordlist.py` 通过加载外部词表（如常见字典词、英文单词）来**抑制熵检测器的误报**——因为随机生成的高熵字符串通常不会落入词表。这一机制对 `Base64HighEntropyString` 与 `HexHighEntropyString` 等插件尤为关键。资料来源：[detect_secrets/filters/wordlist.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/filters/wordlist.py)

## 三、配置模型与数据流

`detect_secrets.settings` 模块维护了全局配置状态，包括：

- **插件开关**：启用/禁用具体的检测器；
- **过滤器参数**：调整熵阈值、白名单路径、自定义正则等；
- **自定义插件路径**：通过 `file://` 协议加载外部检测器。

```mermaid
flowchart LR
    A[源码文件] --> B[Transformers<br/>解析为行]
    B --> C[Plugins<br/>检测潜在密钥]
    C --> D[Filters<br/>allowlist / heuristic /<br/>regex / wordlist]
    D --> E{是否通过}
    E -- 是 --> F[PotentialSecret<br/>存入基线]
    E -- 否 --> G[丢弃]
    F --> H[基线比对<br/>预提交钩子]
```

在数据模型层面，`PotentialSecret` 通过 `set_secret()` 计算 `secret_hash`，并支持 `is_secret` 与 `is_verified` 两个手动标记字段，便于审计人员对历史告警进行真假阳性标注。资料来源：[detect_secrets/core/potential_secret.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/potential_secret.py)

## 四、常见配置场景与高级用法

### 4.1 自定义插件的加载

`core/plugins/util.py` 中的 `get_mapping_from_secret_type_to_class()` 会通过 `import_file_as_module()` 从用户指定的 `file://` 路径**动态导入自定义插件**。这是企业用户在不修改源码的前提下扩展检测能力（如纳入内部服务 token 格式）的标准做法。资料来源：[detect_secrets/core/plugins/util.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/plugins/util.py)

### 4.2 版本兼容与基线升级

基线文件中嵌入的版本号由 `util/semver.py` 中的简易 `Version` 类解析。该模块刻意避免引入 `python-semver` 等第三方依赖，以保证在受限环境下也能工作——这是当社区报告 [#452 "v1.1.0 fails to load any plugins on py38"](https://github.com/Yelp/detect-secrets/issues/452) 时排错路径中的关键一环（版本与插件加载器耦合）。资料来源：[detect_secrets/util/semver.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/util/semver.py)

### 4.3 OS-无关基线文件

v1.5.0 的发布说明中特别提到了 **OS-agnostic baseline files** 的支持（[#586]）。配合 `PotentialSecret.json()` 的标准化输出字段（`type`、`filename`、`hashed_secret`、`is_verified`），基线可以在 Windows、Linux、macOS 之间共享而不会因路径分隔符产生误报。资料来源：[detect_secrets/core/potential_secret.py](https://github.com/Yelp/detect-secrets/blob/main/detect_secrets/core/potential_secret.py)

### 4.4 输出格式扩展

社区多次提出 **SARIF 输出**（[#488](https://github.com/Yelp/detect-secrets/issues/488)）的诉求。当前的 `json()` 方法已经为结构化输出奠定了基础，未来若加入 SARIF 适配器，可直接复用 `hashed_secret` 与 `line_number` 等字段，避免重复计算。

## 五、常见失败模式

| 现象 | 根因 | 处理建议 |
| --- | --- | --- |
| 升级后插件全部失效 | 插件加载器对 Python 版本敏感（参见 #452） | 检查 `setup.cfg` 中的 `python_requires`，并核对 `entry_points` 注册 |
| 基线文件在不同 OS 下产生大量 diff | 路径分隔符未标准化 | 升级至 v1.5.0+，启用 OS-agnostic baseline |
| 自定义插件未生效 | `settings.plugins` 中缺少 `path` 字段 | 在配置中显式添加 `"path": "file:///abs/path.py"` |
| 启发式过滤器把真实密钥也排除 | entropy/字符多样性阈值设置过严 | 通过 `settings.default` 调低阈值或单独禁用特定过滤器 |

## 六、See Also

- [Architecture and Core Concepts](architecture-and-core-concepts.md)
- [Plugins and Detectors](plugins-and-detectors.md)
- [Baseline Workflow](baseline-workflow.md)
- [Pre-commit Integration](pre-commit-integration.md)

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：Yelp/detect-secrets

摘要：发现 11 个潜在踩坑项，其中 3 个为 high/blocking；最高优先级：安装坑 - 来源证据：Extend keyword false positives for yaml/helm template syntax。

## 1. 安装坑 · 来源证据：Extend keyword false positives for yaml/helm template syntax

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Extend keyword false positives for yaml/helm template syntax
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/Yelp/detect-secrets/issues/360 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 2. 安全/权限坑 · 来源证据：detect-secrets not identifying all Github token occurrences in a file

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：detect-secrets not identifying all Github token occurrences in a file
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 证据：community_evidence:github | https://github.com/Yelp/detect-secrets/issues/858 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 3. 安全/权限坑 · 涉及密钥、隐私或敏感领域

- 严重度：high
- 证据强度：source_linked
- 发现：项目文本出现 secret/private key/privacy/trading/finance 等敏感关键词。
- 对用户的影响：金融、交易、隐私和密钥场景必须比普通工具更保守。
- 证据：packet_text.keyword_scan | https://github.com/Yelp/detect-secrets | matched secret / private key / privacy / trading / finance keyword

## 4. 安装坑 · 来源证据：py.typed is in the published wheel but missing from the sdist — source installs lose PEP 561 typing

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：py.typed is in the published wheel but missing from the sdist — source installs lose PEP 561 typing
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/Yelp/detect-secrets/issues/968 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 5. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 证据：capability.assumptions | https://github.com/Yelp/detect-secrets | README/documentation is current enough for a first validation pass.

## 6. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 证据：evidence.maintainer_signals | https://github.com/Yelp/detect-secrets | last_activity_observed missing

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 证据：downstream_validation.risk_items | https://github.com/Yelp/detect-secrets | no_demo; severity=medium

## 8. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 证据：risks.scoring_risks | https://github.com/Yelp/detect-secrets | no_demo; severity=medium

## 9. 安全/权限坑 · 来源证据：GitHubTokenDetector misses new GitHub App installation token format (ghs_APPID_JWT, ~520 chars) — false negative during…

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：GitHubTokenDetector misses new GitHub App installation token format (ghs_APPID_JWT, ~520 chars) — false negative during active rollout
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 证据：community_evidence:github | https://github.com/Yelp/detect-secrets/issues/958 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 10. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 证据：evidence.maintainer_signals | https://github.com/Yelp/detect-secrets | issue_or_pr_quality=unknown

## 11. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 证据：evidence.maintainer_signals | https://github.com/Yelp/detect-secrets | release_recency=unknown

<!-- canonical_name: Yelp/detect-secrets; human_manual_source: deepwiki_human_wiki -->
