redact-audit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- redact_audit/__init__.py +3 -0
- redact_audit/__main__.py +202 -0
- redact_audit/_synthetic.py +47 -0
- redact_audit/adapters/__init__.py +200 -0
- redact_audit/adapters/_presidio_nlp.py +89 -0
- redact_audit/adapters/_spans.py +147 -0
- redact_audit/adapters/base.py +182 -0
- redact_audit/adapters/cfproxy.py +194 -0
- redact_audit/adapters/cosy.py +166 -0
- redact_audit/adapters/detect_secrets.py +185 -0
- redact_audit/adapters/guard.py +268 -0
- redact_audit/adapters/llm_guard.py +141 -0
- redact_audit/adapters/mitm/__init__.py +28 -0
- redact_audit/adapters/mitm/ca.py +151 -0
- redact_audit/adapters/mitm/client.py +94 -0
- redact_audit/adapters/mitm/gateway.py +381 -0
- redact_audit/adapters/mitm/proxy.py +199 -0
- redact_audit/adapters/mitm/upstream.py +284 -0
- redact_audit/adapters/mitm_adapter.py +469 -0
- redact_audit/adapters/mitmproxy_adapter.py +666 -0
- redact_audit/adapters/presidio.py +232 -0
- redact_audit/adapters/scrubadub_adapter.py +150 -0
- redact_audit/bridge/__init__.py +170 -0
- redact_audit/bridge/cf_bridge.mjs +157 -0
- redact_audit/bridge/cosy_bridge.mjs +199 -0
- redact_audit/bridge/guard_bridge.mjs +135 -0
- redact_audit/data/baseline/cf-proxy-2026-12-01T170037.json +834 -0
- redact_audit/data/baseline/cosy-2026-12-01T165923.json +638 -0
- redact_audit/data/baseline/detect-secrets-2026-12-01T170035.json +820 -0
- redact_audit/data/baseline/guard-2026-12-01T191604.json +644 -0
- redact_audit/data/baseline/guard-all-2026-12-01T191605.json +621 -0
- redact_audit/data/baseline/llm-guard-2026-12-01T170038.json +15 -0
- redact_audit/data/baseline/mitm-2026-12-01T165923.json +726 -0
- redact_audit/data/baseline/mitmproxy-2026-12-01T165951.json +726 -0
- redact_audit/data/baseline/presidio-2026-12-01T170033.json +776 -0
- redact_audit/data/baseline/scrubadub-2026-12-01T170035.json +700 -0
- redact_audit/data/gen_vectors.py +276 -0
- redact_audit/report/__init__.py +313 -0
- redact_audit/report/compare.py +188 -0
- redact_audit/report/sanitize.py +97 -0
- redact_audit/runners/__init__.py +7 -0
- redact_audit/runners/audit.py +237 -0
- redact_audit/runners/egress.py +450 -0
- redact_audit/runners/frag.py +179 -0
- redact_audit/runners/rehydrate.py +163 -0
- redact_audit/runners/roundtrip.py +151 -0
- redact_audit/runners/roundtrip_cases.py +102 -0
- redact_audit/runners/vectors.py +106 -0
- redact_audit/scorers/__init__.py +8 -0
- redact_audit/scorers/detect.py +218 -0
- redact_audit/scorers/integrity.py +145 -0
- redact_audit/scorers/integrity_cases.py +100 -0
- redact_audit/vendor/cosy_worker.js +993 -0
- redact_audit/vendor/passthrough_worker.js +51 -0
- redact_audit-0.1.0.dist-info/METADATA +410 -0
- redact_audit-0.1.0.dist-info/RECORD +60 -0
- redact_audit-0.1.0.dist-info/WHEEL +5 -0
- redact_audit-0.1.0.dist-info/entry_points.txt +2 -0
- redact_audit-0.1.0.dist-info/licenses/LICENSE +21 -0
- redact_audit-0.1.0.dist-info/top_level.txt +1 -0
redact_audit/__init__.py
ADDED
redact_audit/__main__.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""``python -m redact_audit`` 入口。
|
|
2
|
+
|
|
3
|
+
用法::
|
|
4
|
+
|
|
5
|
+
python -m redact_audit --adapter cosy --vectors all
|
|
6
|
+
python -m redact_audit --adapter cosy --only detect,integrity
|
|
7
|
+
python -m redact_audit --list
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from . import __version__
|
|
17
|
+
from .adapters import available_adapters, make_adapter
|
|
18
|
+
from .report import render_markdown, write_reports
|
|
19
|
+
from .runners.audit import run_audit
|
|
20
|
+
|
|
21
|
+
ALL_TESTS = ["detect", "integrity", "roundtrip", "frag", "rehydrate", "egress"]
|
|
22
|
+
|
|
23
|
+
# 随包分发的基线结果。全新 clone 或刚 pip install 时 out/ 是空的,
|
|
24
|
+
# --compare 读这里而不是报错 —— 详见 compare 分支的注释。
|
|
25
|
+
# 放在包内(而不是仓库根的 docs/)是为了 pip 装出来的 wheel 也带着它。
|
|
26
|
+
_BASELINE_DIR = Path(__file__).resolve().parent / "data" / "baseline"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _ensure_utf8_stdio() -> None:
|
|
30
|
+
"""把 stdout/stderr 切到 UTF-8 —— 否则 Windows 上打中文直接崩。
|
|
31
|
+
|
|
32
|
+
控制台不是唯一出口:`redact-audit --list > out.txt`、CI 的日志采集、
|
|
33
|
+
subprocess 抓走 —— 这些情况下 stdout 的编码来自 locale(英文 Windows 上是
|
|
34
|
+
cp1252),而本工具的说明文字里有全角括号和中文,一写就 UnicodeEncodeError。
|
|
35
|
+
这是**崩溃**不是乱码:用户看到的是 traceback,不是适配器列表。真实案例:
|
|
36
|
+
GitHub Actions 的 windows-latest 上 `--list` 失败、ubuntu-latest 全绿。
|
|
37
|
+
|
|
38
|
+
被 pytest capsys 之类替换过的流没有 reconfigure,静默跳过 —— 那些环境本来
|
|
39
|
+
就能吃 str,硬改反而会打断捕获。
|
|
40
|
+
"""
|
|
41
|
+
for stream in (sys.stdout, sys.stderr):
|
|
42
|
+
reconf = getattr(stream, "reconfigure", None)
|
|
43
|
+
if reconf is None:
|
|
44
|
+
continue
|
|
45
|
+
try:
|
|
46
|
+
reconf(encoding="utf-8", errors="replace")
|
|
47
|
+
except (ValueError, OSError):
|
|
48
|
+
continue
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _parse_only(s: str | None) -> set[str] | None:
|
|
52
|
+
"""None 表示"由 run_audit 按 capabilities 决定"。
|
|
53
|
+
|
|
54
|
+
这里**不能**返回全集:`run_audit(adapter, include=全集)` 会让 include 非 None,
|
|
55
|
+
从而绕过 `if include is None:` 里的 `capabilities()["egress"]` 判断。结果是
|
|
56
|
+
纯函数式引擎(Cosy)也会被塞进 EGRESS-1,而那段用的是写死参考网关 ——
|
|
57
|
+
报告上那行分数属于参考网关,不属于被测引擎。踩过这个坑(见 README 踩坑 12)。
|
|
58
|
+
"""
|
|
59
|
+
if not s or s == "all":
|
|
60
|
+
return None
|
|
61
|
+
wanted = {x.strip() for x in s.split(",") if x.strip()}
|
|
62
|
+
unknown = wanted - set(ALL_TESTS)
|
|
63
|
+
if unknown:
|
|
64
|
+
raise SystemExit(f"unknown test(s): {', '.join(sorted(unknown))}\n"
|
|
65
|
+
f"available: {', '.join(ALL_TESTS)}")
|
|
66
|
+
return wanted
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _collect_results(outdir: Path, only: str | None = None) -> list[Path]:
|
|
70
|
+
"""挑每个引擎**最新**那份结果,供 compare 用。
|
|
71
|
+
|
|
72
|
+
为什么取最新而不是全取:同一引擎跑过多次时(改了向量集、升了依赖),
|
|
73
|
+
把旧结果也放进来会让同一行出现两次,排名看着像"这个引擎不稳定",
|
|
74
|
+
其实只是把不同时间的快照混在了一起。
|
|
75
|
+
"""
|
|
76
|
+
if not outdir.is_dir():
|
|
77
|
+
return []
|
|
78
|
+
wanted = (
|
|
79
|
+
{x.strip().lower() for x in only.split(",") if x.strip()} if only else None
|
|
80
|
+
)
|
|
81
|
+
latest: dict[str, tuple[str, Path]] = {}
|
|
82
|
+
for p in outdir.glob("*.json"):
|
|
83
|
+
if p.name == "compare.json":
|
|
84
|
+
continue
|
|
85
|
+
try:
|
|
86
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
87
|
+
except (json.JSONDecodeError, OSError):
|
|
88
|
+
# 半截文件(上次跑到一半被打断)不该让 compare 整体失败
|
|
89
|
+
continue
|
|
90
|
+
name = str(data.get("adapter") or "").lower()
|
|
91
|
+
if not name:
|
|
92
|
+
continue
|
|
93
|
+
if wanted and name not in wanted:
|
|
94
|
+
continue
|
|
95
|
+
started = str(data.get("started_at") or "")
|
|
96
|
+
prev = latest.get(name)
|
|
97
|
+
if prev is None or started > prev[0]:
|
|
98
|
+
latest[name] = (started, p)
|
|
99
|
+
return [p for _name, (_s, p) in sorted(latest.items())]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
103
|
+
p = argparse.ArgumentParser(
|
|
104
|
+
prog="python -m redact_audit",
|
|
105
|
+
description="审计脱敏网关:检测精度 / 完整性 / 往返 / 分片 / 改写韧性",
|
|
106
|
+
)
|
|
107
|
+
p.add_argument("--adapter", default="cosy",
|
|
108
|
+
help="被测适配器(默认 cosy)")
|
|
109
|
+
p.add_argument("--vectors", default="all",
|
|
110
|
+
help="向量集:all / positives / traps / 路径")
|
|
111
|
+
p.add_argument("--only", default=None,
|
|
112
|
+
help=f"只跑这些测试,逗号分隔:{','.join(ALL_TESTS)}")
|
|
113
|
+
p.add_argument("--out", default="out", help="输出目录(默认 ./out)")
|
|
114
|
+
p.add_argument("--json", action="store_true", help="把完整 JSON 打到 stdout")
|
|
115
|
+
p.add_argument("--quiet", action="store_true", help="只打印总体判定")
|
|
116
|
+
p.add_argument("--list", action="store_true", help="列出可用适配器")
|
|
117
|
+
p.add_argument("--compare", action="store_true",
|
|
118
|
+
help="从 --out 下的历史结果横向对比(不重新跑)")
|
|
119
|
+
p.add_argument("--adapters", default=None,
|
|
120
|
+
help="配合 --compare:只对比这些引擎,逗号分隔")
|
|
121
|
+
p.add_argument("--version", action="version", version=f"redact_audit {__version__}")
|
|
122
|
+
return p
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def main(argv: list[str] | None = None) -> int:
|
|
126
|
+
_ensure_utf8_stdio()
|
|
127
|
+
args = build_parser().parse_args(argv)
|
|
128
|
+
|
|
129
|
+
if args.list:
|
|
130
|
+
for name, desc in available_adapters().items():
|
|
131
|
+
print(f"{name:12s} {desc}")
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
# ── compare:从历史结果横向对比,不重新跑 ──────────────────
|
|
135
|
+
if args.compare:
|
|
136
|
+
from .report.compare import load_results, render_compare, write_compare
|
|
137
|
+
outdir = Path(args.out)
|
|
138
|
+
paths = _collect_results(outdir, args.adapters)
|
|
139
|
+
fallback = False
|
|
140
|
+
if not paths:
|
|
141
|
+
# 全新 clone / 刚 pip install 时 out/ 是空的。此时 --compare 直接
|
|
142
|
+
# 报错会让人以为装坏了,所以回退读随仓库分发的基线结果。
|
|
143
|
+
paths = _collect_results(_BASELINE_DIR, args.adapters)
|
|
144
|
+
fallback = bool(paths)
|
|
145
|
+
if not paths:
|
|
146
|
+
print(
|
|
147
|
+
f"error: {outdir} 下没有可用的结果 JSON,"
|
|
148
|
+
f"随仓库分发的基线({_BASELINE_DIR})也没有。\n"
|
|
149
|
+
f"先跑一次审计:redact-audit --adapter cosy",
|
|
150
|
+
file=sys.stderr,
|
|
151
|
+
)
|
|
152
|
+
return 2
|
|
153
|
+
results = load_results(paths)
|
|
154
|
+
out = write_compare(results, outdir)
|
|
155
|
+
print(render_compare(results))
|
|
156
|
+
print()
|
|
157
|
+
if fallback:
|
|
158
|
+
print(
|
|
159
|
+
f"[note] {outdir} 下没有结果,以上表格读的是随仓库分发的基线快照"
|
|
160
|
+
f"({_BASELINE_DIR.name}/)。跑一次审计即可换成你自己的数据。"
|
|
161
|
+
)
|
|
162
|
+
print(f"[written] {out['markdown']}")
|
|
163
|
+
print(f"[written] {out['json']}")
|
|
164
|
+
return 0
|
|
165
|
+
|
|
166
|
+
try:
|
|
167
|
+
adapter = make_adapter(args.adapter)
|
|
168
|
+
except KeyError as e:
|
|
169
|
+
print(f"error: {e}", file=sys.stderr)
|
|
170
|
+
return 2
|
|
171
|
+
|
|
172
|
+
only = _parse_only(args.only)
|
|
173
|
+
res = run_audit(adapter, include=only)
|
|
174
|
+
|
|
175
|
+
paths = write_reports(res, args.out)
|
|
176
|
+
|
|
177
|
+
if args.json:
|
|
178
|
+
print(json.dumps(res.as_dict(), ensure_ascii=False, indent=2))
|
|
179
|
+
return 0
|
|
180
|
+
|
|
181
|
+
h = res.headline()
|
|
182
|
+
if args.quiet:
|
|
183
|
+
print(json.dumps(h, ensure_ascii=False))
|
|
184
|
+
else:
|
|
185
|
+
print(render_markdown(res))
|
|
186
|
+
print()
|
|
187
|
+
print(f"[written] {paths['markdown']}")
|
|
188
|
+
print(f"[written] {paths['json']}")
|
|
189
|
+
|
|
190
|
+
# 退出码:有完整性泄漏 / 分片失败 / 静默失败 / 上游泄漏 → 非零,便于 CI 卡门
|
|
191
|
+
hard_fail = (
|
|
192
|
+
(h.get("integrity_leaked_chars") or 0) > 0
|
|
193
|
+
or h.get("frag_ok") is False
|
|
194
|
+
or (h.get("rehydrate_silent_failures") or 0) > 0
|
|
195
|
+
or h.get("egress_control_ok") is False
|
|
196
|
+
or (h.get("egress_leaked_chars") or 0) > 0
|
|
197
|
+
)
|
|
198
|
+
return 1 if hard_fail else 0
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
if __name__ == "__main__":
|
|
202
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""合成凭据样本 —— 为什么这个文件长得这么怪。
|
|
2
|
+
|
|
3
|
+
审计引擎需要"形似真实凭据"的输入,否则测不出识别率。但把这些字符串按原样写进
|
|
4
|
+
源码,会有两个直接后果:
|
|
5
|
+
|
|
6
|
+
1. **GitHub push protection 会拒收整个仓库。** 它扫描的是提交内容的字节流,
|
|
7
|
+
不看注释里有没有写"这是假的"。
|
|
8
|
+
2. **用户装完之后,任何密钥扫描器都会在自己的源码树里报警。** 一个号称能
|
|
9
|
+
找出泄露凭据的工具,不该自己先制造告警。
|
|
10
|
+
|
|
11
|
+
所以这里把每个样本切成 ≤8 字符的片段,在 import 时拼回完整形态。片段本身不构成
|
|
12
|
+
任何凭据格式(``sk-proj-`` 只是前缀,``AbCdEf12`` 只是随机串),扫描器不会命中;
|
|
13
|
+
拼出来的字符串只在进程内存里存在,落不到任何提交里。
|
|
14
|
+
|
|
15
|
+
这些字符串**全部是虚构的**:字符表固定、不含校验位、不对应任何真实账号。
|
|
16
|
+
``SECURITY.md`` 里对这一点有单独说明。
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _synth(*chunks: str) -> str:
|
|
22
|
+
"""把片段拼成完整样本。用函数而非 ``"".join(...)`` 是为了让调用点短一点。"""
|
|
23
|
+
return "".join(chunks)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# OpenAI 风格项目密钥:长度足够让"只遮前半段"这类错误显形
|
|
27
|
+
SK = _synth("sk-proj-", "AbCdEf12", "34567890", "XyZqWeRt",
|
|
28
|
+
"YuIoP123", "4567890A", "bCdEf")
|
|
29
|
+
# 同一格式的前缀单独导出:部分用例断言"上游只看到前缀、看不到密钥体"
|
|
30
|
+
SK_PREFIX = _synth("sk-proj-")
|
|
31
|
+
|
|
32
|
+
# GitHub PAT:换一个前缀,测"只遮第一个 token"这类错误
|
|
33
|
+
GHP = _synth("ghp_9fK2", "mQ7xR4tV", "1wZ8nB5c", "L3jH6dS0", "aE2uY7iO")
|
|
34
|
+
# 相邻两个 PAT:用来测"只报第一个"的行为
|
|
35
|
+
GHP_A = _synth("ghp_abcd", "efghijkl", "mnopqrst", "uvwxyz01", "23456789")
|
|
36
|
+
GHP_B = _synth("ghp_9876", "543210zy", "xwvutsrq", "ponmlkji", "hgfedcba")
|
|
37
|
+
|
|
38
|
+
# PEM 主体行:测"只遮 BEGIN/END、中间行原样发出去"这一类失败
|
|
39
|
+
PEM_BODY = _synth("MIIEowIB", "AAKCAQEA", "x7Vv2mKp", "9QrT4sLd",
|
|
40
|
+
"8nFgH3jW", "6yB1cX5a", "Z0eR7uI2", "oP9kM4nQ")
|
|
41
|
+
PEM_BEGIN = _synth("-----BEGIN RSA ", "PRIVATE KEY-----")
|
|
42
|
+
PEM_END = _synth("-----END RSA ", "PRIVATE KEY-----")
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"SK", "SK_PREFIX", "GHP", "GHP_A", "GHP_B",
|
|
46
|
+
"PEM_BODY", "PEM_BEGIN", "PEM_END",
|
|
47
|
+
]
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""适配器注册表。
|
|
2
|
+
|
|
3
|
+
新增引擎时只改这里:加一个 ``_SPECS`` 条目 + 在 ``_FACTORIES`` 里登记工厂。
|
|
4
|
+
runner / scorer / report 全部只依赖 ``Adapter`` 抽象,不需要改动。
|
|
5
|
+
|
|
6
|
+
三条设计约束,都是踩过坑才定下来的:
|
|
7
|
+
|
|
8
|
+
1. **缺依赖是 SKIP,不是 FAIL。** 八个引擎里有五个要装外部包(presidio 要
|
|
9
|
+
spacy 模型、llm-guard 要 torch、mitmproxy 要整包)。如果 ``make_adapter``
|
|
10
|
+
让 ``ImportError`` 直接冒出去,``compare`` 会在这里整段崩掉,一行结果都
|
|
11
|
+
拿不到;如果退而记成"引擎跑挂了",报告里会出现一排 0 分——那是在把
|
|
12
|
+
"我没装" 说成 "它不行"。所以统一抛 ``AdapterUnavailable``,带上补装提示。
|
|
13
|
+
2. **负对照必须能被识别。** ``cf-proxy`` 是确定不脱敏的网关,它的作用是
|
|
14
|
+
验证审计器自身:给它打非零分就说明审计器在骗自己。因此它带
|
|
15
|
+
``is_control=True``,报告与 compare 里单独标注、不参与排名。
|
|
16
|
+
3. **同一引擎可以有多个配置行。** ``guard`` 与 ``guard-all`` 是同一份代码、
|
|
17
|
+
不同的规则开关。把"默认配置"和"全开配置"并排放,才能把"能力不足"与
|
|
18
|
+
"默认没开"分开——这两件事在单行报告里长得一模一样。
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from .base import Adapter, DetectResult, EngineError, Span
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"Adapter", "DetectResult", "EngineError", "Span",
|
|
26
|
+
"AdapterUnavailable", "available_adapters", "make_adapter",
|
|
27
|
+
"adapter_is_control", "unavailable",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class AdapterUnavailable(RuntimeError):
|
|
32
|
+
"""依赖没装 / 被测模块找不到。
|
|
33
|
+
|
|
34
|
+
与 ``EngineError`` 的区别:``EngineError`` 是"引擎跑了但崩了"(算失败),
|
|
35
|
+
``AdapterUnavailable`` 是"根本没能开始跑"(算跳过)。混为一谈会让报告
|
|
36
|
+
里出现一排假 0 分。
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, name: str, hint: str, *, cause: str = "") -> None:
|
|
40
|
+
self.name = name
|
|
41
|
+
self.hint = hint
|
|
42
|
+
self.cause = cause
|
|
43
|
+
msg = f"{name} 不可用:{hint}"
|
|
44
|
+
if cause:
|
|
45
|
+
msg += f"({cause})"
|
|
46
|
+
super().__init__(msg)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# 名字 → (一行说明, 是否负对照)
|
|
50
|
+
_SPECS: dict[str, tuple[str, bool]] = {
|
|
51
|
+
"cosy": ("CosyRedactGateway(offline,Cloudflare Worker,可纯离线测)", False),
|
|
52
|
+
"mitm": ("MITM 网关(真实 TLS 链路,可测上游实际收到的字节)", False),
|
|
53
|
+
"guard": ("dsh-redact-guard(13/17 规则默认开启,无还原)", False),
|
|
54
|
+
"guard-all": ("dsh-redact-guard 全 17 条规则(对照行,看配置差异)", False),
|
|
55
|
+
"presidio": ("Microsoft Presidio(仅 pattern 类识别器,无 spaCy 模型)", False),
|
|
56
|
+
"detect-secrets": ("Yelp detect-secrets(扫描器语义,粒度粗、误报多)", False),
|
|
57
|
+
"scrubadub": ("scrubadub(原生 beg/end 区间,检测面窄)", False),
|
|
58
|
+
"llm-guard": ("LLM Guard Anonymize(只给 sanitized 文本,需 torch)", False),
|
|
59
|
+
"mitmproxy": ("mitmproxy addon(真实代理链路,需 mitmproxy)", False),
|
|
60
|
+
"cf-proxy": ("cf-proxy 纯透传网关(**负对照**,预期全零分)", True),
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def available_adapters() -> dict[str, str]:
|
|
65
|
+
"""名字 → 一行说明。保持旧签名(返回 dict[str, str])。"""
|
|
66
|
+
return {k: v[0] for k, v in _SPECS.items()}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def adapter_is_control(name: str) -> bool:
|
|
70
|
+
return _SPECS.get(name.lower().strip(), ("", False))[1]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _factory(name: str):
|
|
74
|
+
"""惰性 import:没装 presidio 不该导致连 cosy 都跑不了。
|
|
75
|
+
|
|
76
|
+
这也是为什么这里不写成模块顶部的 import —— 八个引擎的依赖加起来
|
|
77
|
+
好几 GB,全在 import 时加载会让 ``--list`` 慢到不可用。
|
|
78
|
+
"""
|
|
79
|
+
key = name.lower().strip()
|
|
80
|
+
|
|
81
|
+
if key == "cosy":
|
|
82
|
+
from .cosy import CosyAdapter
|
|
83
|
+
return CosyAdapter
|
|
84
|
+
if key == "mitm":
|
|
85
|
+
from .mitm_adapter import MitmAdapter
|
|
86
|
+
return MitmAdapter
|
|
87
|
+
if key == "guard":
|
|
88
|
+
from .guard import GuardAdapter
|
|
89
|
+
return GuardAdapter
|
|
90
|
+
if key == "guard-all":
|
|
91
|
+
from .guard import GuardAllAdapter
|
|
92
|
+
return GuardAllAdapter
|
|
93
|
+
if key == "cf-proxy":
|
|
94
|
+
from .cfproxy import CfProxyAdapter
|
|
95
|
+
return CfProxyAdapter
|
|
96
|
+
if key == "presidio":
|
|
97
|
+
from .presidio import PresidioAdapter
|
|
98
|
+
return PresidioAdapter
|
|
99
|
+
if key == "detect-secrets":
|
|
100
|
+
from .detect_secrets import DetectSecretsAdapter
|
|
101
|
+
return DetectSecretsAdapter
|
|
102
|
+
if key == "scrubadub":
|
|
103
|
+
from .scrubadub_adapter import ScrubadubAdapter
|
|
104
|
+
return ScrubadubAdapter
|
|
105
|
+
if key == "llm-guard":
|
|
106
|
+
from .llm_guard import LlmGuardAdapter
|
|
107
|
+
return LlmGuardAdapter
|
|
108
|
+
if key == "mitmproxy":
|
|
109
|
+
from .mitmproxy_adapter import MitmproxyAdapter
|
|
110
|
+
return MitmproxyAdapter
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def make_adapter(name: str, **kwargs) -> Adapter:
|
|
115
|
+
key = name.lower().strip()
|
|
116
|
+
cls = _factory(key)
|
|
117
|
+
if cls is None:
|
|
118
|
+
raise KeyError(
|
|
119
|
+
f"unknown adapter {name!r}; available: {', '.join(available_adapters())}"
|
|
120
|
+
)
|
|
121
|
+
try:
|
|
122
|
+
return cls(**kwargs)
|
|
123
|
+
except ImportError as e:
|
|
124
|
+
raise AdapterUnavailable(
|
|
125
|
+
key,
|
|
126
|
+
_hint_for(key),
|
|
127
|
+
cause=f"ImportError: {e}",
|
|
128
|
+
) from e
|
|
129
|
+
except FileNotFoundError as e:
|
|
130
|
+
# guard / cf-proxy 的被测模块不在包内(它们是**被审计的第三方代码**,
|
|
131
|
+
# 复制进来就分不清"我改过的版本"和"原版"了)。路径由环境变量或
|
|
132
|
+
# 仓库内 vendor/ samples/ 的约定位置给出,找不到时走这里。
|
|
133
|
+
raise AdapterUnavailable(
|
|
134
|
+
key,
|
|
135
|
+
_hint_for(key),
|
|
136
|
+
cause=f"FileNotFoundError: {e}",
|
|
137
|
+
) from e
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
_HINTS = {
|
|
141
|
+
"cosy": "需要 Node 可执行;redact_audit/vendor/cosy_worker.js 随包分发",
|
|
142
|
+
"mitm": "需要 cryptography(pip install cryptography)",
|
|
143
|
+
"guard": "需要 Node + 环境变量 REDACT_AUDIT_GUARD_MODULE 指向 dsh-redact-guard/lib/redactor.js",
|
|
144
|
+
"guard-all": "需要 Node + 环境变量 REDACT_AUDIT_GUARD_MODULE 指向 dsh-redact-guard/lib/redactor.js",
|
|
145
|
+
"cf-proxy": "需要 Node + 仓库内 samples/passthrough_worker.js(或用 REDACT_AUDIT_CF_MODULE 指定)",
|
|
146
|
+
"presidio": "pip install presidio-analyzer presidio-anonymizer(spaCy 模型不下载,见 _presidio_nlp.py)",
|
|
147
|
+
"detect-secrets": "pip install detect-secrets",
|
|
148
|
+
"scrubadub": "pip install scrubadub",
|
|
149
|
+
"llm-guard": "pip install llm-guard(拉 torch,约 2GB;未装时该行记为跳过)",
|
|
150
|
+
"mitmproxy": "pip install mitmproxy",
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _hint_for(name: str) -> str:
|
|
155
|
+
return _HINTS.get(name, "检查依赖与路径")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def unavailable(name: str, *, cause: str = "") -> AdapterUnavailable:
|
|
159
|
+
"""把**任意阶段**的依赖缺失统一转成 SKIP。
|
|
160
|
+
|
|
161
|
+
为什么需要这个而不是只靠 ``make_adapter`` 里的 try:不少适配器是在
|
|
162
|
+
``prepare()`` 里才 import 重依赖的(llm-guard 要 torch、mitmproxy 要整包)。
|
|
163
|
+
构造能成功、prepare 才炸 —— 只捕构造阶段的话,这些引擎会带着
|
|
164
|
+
``ModuleNotFoundError`` 一路冒到 CLI,整轮审计直接中止,一行结果都拿不到。
|
|
165
|
+
"""
|
|
166
|
+
key = name.lower().strip()
|
|
167
|
+
return AdapterUnavailable(key, _hint_for(key), cause=cause)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# ── 向后兼容的惰性再导出(PEP 562)─────────────────────────────
|
|
171
|
+
# `from redact_audit.adapters import CosyAdapter` 这类旧写法必须继续可用:
|
|
172
|
+
# tests/test_regression.py:15 就依赖它。但**不能在模块顶部 import**——
|
|
173
|
+
# 那样 `--list` 会连带加载 cryptography 等重依赖,而列个清单不该付这个代价。
|
|
174
|
+
# 模块级 __getattr__ 正好满足两者:名字被访问时才真的去 import。
|
|
175
|
+
_LAZY_EXPORTS = {
|
|
176
|
+
"CosyAdapter": (".cosy", "CosyAdapter"),
|
|
177
|
+
"MitmAdapter": (".mitm_adapter", "MitmAdapter"),
|
|
178
|
+
"GuardAdapter": (".guard", "GuardAdapter"),
|
|
179
|
+
"GuardAllAdapter": (".guard", "GuardAllAdapter"),
|
|
180
|
+
"CfProxyAdapter": (".cfproxy", "CfProxyAdapter"),
|
|
181
|
+
"PresidioAdapter": (".presidio", "PresidioAdapter"),
|
|
182
|
+
"DetectSecretsAdapter": (".detect_secrets", "DetectSecretsAdapter"),
|
|
183
|
+
"ScrubadubAdapter": (".scrubadub_adapter", "ScrubadubAdapter"),
|
|
184
|
+
"LlmGuardAdapter": (".llm_guard", "LlmGuardAdapter"),
|
|
185
|
+
"MitmproxyAdapter": (".mitmproxy_adapter", "MitmproxyAdapter"),
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def __getattr__(name: str):
|
|
190
|
+
target = _LAZY_EXPORTS.get(name)
|
|
191
|
+
if target is None:
|
|
192
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
193
|
+
from importlib import import_module
|
|
194
|
+
|
|
195
|
+
mod_name, attr = target
|
|
196
|
+
return getattr(import_module(mod_name, __name__), attr)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def __dir__() -> list[str]:
|
|
200
|
+
return sorted(list(globals()) + list(_LAZY_EXPORTS))
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
r"""presidio 的离线 NLP 引擎桩。
|
|
2
|
+
|
|
3
|
+
**为什么需要这个文件。** presidio 的 ``AnalyzerEngine()`` 默认构造
|
|
4
|
+
``NlpEngineProvider().create_engine()``,后者在 ``spacy_nlp_engine.py:74``
|
|
5
|
+
调 ``_download_spacy_model_if_needed()`` → ``spacy.cli.download()`` →
|
|
6
|
+
``requests.get(about.__compatibility__)``。本机到该地址的连接会被重置
|
|
7
|
+
(``ConnectionResetError 10054``),于是**整个引擎构造失败**。
|
|
8
|
+
|
|
9
|
+
后果不是"少了几个识别器",而是"一个识别器都没有"——审计器会把
|
|
10
|
+
``ImportError`` 之外的这条网络错误也当成"引擎不可用",而这台机器上
|
|
11
|
+
presidio 其实是装好的。一个因为拉不到模型就完全测不了的引擎,等于在
|
|
12
|
+
报告里留一行假的"不可用"。
|
|
13
|
+
|
|
14
|
+
所以这里用 ``spacy.blank("en")``(**纯本地,零下载**)提供分词骨架。
|
|
15
|
+
presidio 的 pattern 类识别器(EMAIL / CREDIT_CARD / PHONE / IBAN / IP …)
|
|
16
|
+
只依赖正则与 token 边界,不需要词向量;NLP 类识别器(PERSON / LOCATION /
|
|
17
|
+
NRP)依赖 ``doc.ents``,而 blank 模型产不出实体,因此**它们在本环境下
|
|
18
|
+
一条都不命中**。
|
|
19
|
+
|
|
20
|
+
这不是缺陷,是必须如实写进报告的口径:本行 presidio 的分数只代表
|
|
21
|
+
**pattern 类识别器**的能力,NLP 类识别器未参与。把这句话写进
|
|
22
|
+
``engine_meta()``,报告会原样带出去;不写就等于默认读者以为它测的是
|
|
23
|
+
完整 presidio。
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import spacy
|
|
28
|
+
from presidio_analyzer.nlp_engine import NlpArtifacts, NlpEngine
|
|
29
|
+
|
|
30
|
+
# blank 模型的分词器对停用词/标点没有词表,用一份极小的内联表顶上。
|
|
31
|
+
# 这两个方法只被 presidio 的 lemma/stopword 辅助逻辑调用,pattern 识别器
|
|
32
|
+
# 不依赖它们;给个合理近似即可,不必追求与 en_core_web_sm 一致。
|
|
33
|
+
_STOPWORDS = frozenset(
|
|
34
|
+
"a an the is are was were be been of to in on at for and or not "
|
|
35
|
+
"this that these those it its with as by from".split()
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class BlankNlpEngine(NlpEngine):
|
|
40
|
+
"""基于 ``spacy.blank`` 的 NLP 引擎:能分词,不产实体,永不联网。"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, languages: tuple[str, ...] = ("en",)) -> None:
|
|
43
|
+
self._langs = list(languages)
|
|
44
|
+
self._nlp = None
|
|
45
|
+
|
|
46
|
+
# ── 生命周期 ────────────────────────────────────────────────
|
|
47
|
+
def load(self) -> None:
|
|
48
|
+
# 只造 tokenizer。任何 ``spacy.load(...)`` 都会去磁盘找模型,
|
|
49
|
+
# 找不到就转去下载 —— 这正是要绕开的那条路径。
|
|
50
|
+
self._nlp = spacy.blank(self._langs[0])
|
|
51
|
+
|
|
52
|
+
def is_loaded(self) -> bool:
|
|
53
|
+
return self._nlp is not None
|
|
54
|
+
|
|
55
|
+
# ── 能力声明 ────────────────────────────────────────────────
|
|
56
|
+
def get_supported_languages(self) -> list[str]:
|
|
57
|
+
return list(self._langs)
|
|
58
|
+
|
|
59
|
+
def get_supported_entities(self) -> list[str]:
|
|
60
|
+
# 空列表是**诚实的**:blank 模型确实一个实体类型都不产。
|
|
61
|
+
# 返回 ["PERSON", ...] 会让 presidio 以为 NLP 识别器可用,
|
|
62
|
+
# 于是把它们挂上却永远返回空 —— 报告里就会出现"漏检"而非"未启用"。
|
|
63
|
+
return []
|
|
64
|
+
|
|
65
|
+
# ── 词性辅助 ────────────────────────────────────────────────
|
|
66
|
+
def is_stopword(self, word: str, language: str) -> bool:
|
|
67
|
+
return word.lower() in _STOPWORDS
|
|
68
|
+
|
|
69
|
+
def is_punct(self, word: str, language: str) -> bool:
|
|
70
|
+
return bool(word) and all(not c.isalnum() for c in word)
|
|
71
|
+
|
|
72
|
+
# ── 主流程 ──────────────────────────────────────────────────
|
|
73
|
+
def process_text(self, text: str, language: str) -> NlpArtifacts:
|
|
74
|
+
if self._nlp is None:
|
|
75
|
+
self.load()
|
|
76
|
+
doc = self._nlp.make_doc(text) # make_doc 只分词,不走 pipeline
|
|
77
|
+
return NlpArtifacts(
|
|
78
|
+
entities=[], # blank 模型没有 NER
|
|
79
|
+
tokens=doc,
|
|
80
|
+
tokens_indices=[t.idx for t in doc],
|
|
81
|
+
lemmas=[t.text.lower() for t in doc],
|
|
82
|
+
nlp_engine=self,
|
|
83
|
+
language=language,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def process_batch(self, texts, language: str, batch_size: int = 1,
|
|
87
|
+
n_process: int = 1, **kwargs):
|
|
88
|
+
for t in texts:
|
|
89
|
+
yield t, self.process_text(t, language)
|