BAder82t/regaudit-fhe

GitHub: BAder82t/regaudit-fhe

一个基于全同态加密的隐私保护 AI 审计原语库,为受监管行业提供可签名验证的合规审计信封。

Stars: 3 | Forks: 0

# regaudit-fhe 用于隐私保护 AI 审计的深度跟踪监管审计原语。 `regaudit-fhe` 提供了明文槽向量参考模型、TenSEAL CKKS 后端支持、签名审计信封、schema 验证以及 监管审计证据辅助工具。 默认执行路径为明文。安装 `[fhe]` 额外依赖以 在支持的平台上启用 TenSEAL CKKS 后端。本仓库不 包含 OpenFHE。 [![ci](https://static.pigsec.cn/wp-content/uploads/repos/2026/06/fc24e64a86153527.svg)](https://github.com/BAder82t/regaudit-fhe/actions/workflows/ci.yml) [![PyPI](https://img.shields.io/pypi/v/regaudit-fhe.svg)](https://pypi.org/project/regaudit-fhe/) [![Python](https://img.shields.io/pypi/pyversions/regaudit-fhe.svg)](https://pypi.org/project/regaudit-fhe/) [![License: AGPL v3](https://img.shields.io/badge/License-AGPL_v3-blue.svg)](LICENSE) ## 用途 ``` ┌──────────────┐ encrypted inputs ┌────────────────┐ │ Regulated │ ──────────────────────────► │ regaudit-fhe │ │ AI vendor │ (labels, preds, PHI, │ d=6 CKKS audit │ │ (the client) │ protected attrs) │ primitives │ └──────────────┘ └──────┬─────────┘ ▲ │ │ │ encrypted │ sealed envelope │ aggregate │ (JSON + receipt) │ scalars only │ ▼ │ ┌────────────────┐ └───────────────────────────────────► │ Regulator / │ │ external │ decrypt + verify receipt │ auditor │ └────────────────┘ ``` 相同的接口服务于两类受众: | 受众 | 角色 | 运行内容 | | -------------- | ----------------------------------- | ----------------------------------------------------------------- | | **Client(客户端)** | 受审实体(供应商 / 运营商)。 | `audit_*` 原语,`regaudit-fhe audit ...`。 | | **Regulator(监管方)** | 外部或内部审计员。 | 针对 `TrustStore` 使用 `verify_envelope_or_raise(env, trust_store=...)`;`regaudit-fhe verify --trusted-keys ...`。 | 运行会生成一个带有 SHA-256 回执的审计信封 (JSON)。 客户端可以将其归档、发送给监管方,或两者兼顾。监管方 会重新计算该回执,以检测签发与审查之间是否存在篡改。 ## 六大原语 | 模块 | API | 深度 | 用例(提供技术证据支持…) | | ------------- | ------------------------- | ----- | ------------------------------------------------------------------------ | | `egf_imss` | `audit_fairness` | 4 | NYC LL144、EU AI Act §10/§15、Colorado AI Act、CFPB 工作流。 | | `etk_fpa_hbc` | `audit_provenance` | 3 | EU AI Act §10、21 CFR Part 11、GDPR §22、HIPAA 工作流。 | | `esc_cia` | `audit_concordance` | 4 | FDA SaMD 肿瘤学 PCCP、EU AI Act §15、EMA 工作流。 | | `ecp_qssp` | `audit_calibration` | 3 | FDA SaMD UQ、EU AI Act §15、ISO/IEC 23053、UNECE WP.29 工作流。 | | `ew1_cdsf` | `audit_drift` | 3 | EU AI Act §15、FDA SaMD PCCP、Basel III 工作流。 | | `ecmd_jps` | `audit_disagreement` | 5 | OCC SR 11-7、EU AI Act §15、FDA SaMD PCCP 工作流。 | 上表显示了每个原语的深度预算——即它在 d=6 CKKS 电路内消耗的 乘法层级数。在 TenSEAL 后端上,这六个原语的深度均保持在 6 以内,为下游的 提交与验证链接留出了余量。以下数值是在真实 CKKS 执行路径上的运行时观测值;权威数据来源是 `benchmarks/results/SUMMARY.md` 以及 `regaudit_fhe.fhe.primitives` 中的 `last_depth(name)` / `last_depths()` 访问器(底层状态保存在 `ContextVar` 中,因此并发的加密 调用不会在深度记录上发生竞态)。 ``` Depth budget visualisation (each ▮ = 1 consumed level; observed on TenSEAL) primitive 1 2 3 4 5 6 ─────────────────────────────────── audit_fairness ▮ ▮ . . . . 2 of 6 (encrypt + mul_pt + mul_scalar) audit_provenance ▮ ▮ . . . . 2 of 6 (encrypt + mul_pt fold per bucket) audit_drift ▮ ▮ ▮ . . . 3 of 6 (mm_pt CDF + ct×ct square) audit_calibration ▮ ▮ ▮ ▮ . . 4 of 6 (mul_pt scale + sign_poly_d3) audit_disagreement ▮ ▮ ▮ ▮ ▮ . 5 of 6 (deg-3 poly + pairwise sq + scale) audit_concordance ▮ ▮ ▮ ▮ ▮ ▮ 6 of 6 (rotate via mm_pt + sign_poly_d3 + ct×ct event mask) ``` 每个原语的完整规范(包括其算法、深度 分解和安全分析)位于 [`docs/specs/`](docs/specs/)。 ## 安装 ``` pip install regaudit-fhe ``` 运行深度预算槽向量电路的明文模型 (用于测试、oracle 和 CI)仅需 `numpy>=1.26`。加密 执行路径包含在可选的 `[fhe]` 额外依赖中: ``` pip install regaudit-fhe[fhe] # adds the TenSEAL CKKS backend ``` ## 快速开始 ### 客户端侧 — 生成审计信封 ``` import numpy as np import regaudit_fhe as rf y_true = np.array([1, 0, 1, 1, 0, 1, 0, 0], dtype=float) y_pred = np.array([1, 0, 1, 0, 0, 1, 1, 0], dtype=float) group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0], dtype=float) group_b = 1.0 - group_a report = rf.audit_fairness(y_true, y_pred, group_a, group_b, threshold=0.1) print(report.demographic_parity_diff, report.threshold_breached) # 生产环境中使用长期 issuer key;演示中使用临时 key。 signer = rf.Signer.generate(issuer="acme-bank", key_id="acme-2026-04") envelope = rf.envelope("fairness", report, signer=signer) print(envelope.to_json()) # ship this to the regulator ``` ### 监管方侧 — 针对 trust store 进行验证(推荐) ``` import regaudit_fhe as rf # trust_store.json 将 key_id 映射到 PEM 编码的 Ed25519 公钥。 # 可选字段:"revoked": [...],"parameter_set_pins": {key_id: hex}。 trust_store = rf.TrustStore.from_json("trust_store.json") env = rf.AuditEnvelope.from_dict(received_payload) try: outcome = rf.verify_envelope_or_raise(env, trust_store=trust_store) except rf.UntrustedIssuer: # key_id unknown OR embedded PEM mismatch ... except rf.RevokedIssuer: # key_id is in trust_store.revoked ... except rf.WrongParameterSet: # parameter_set_hash != pinned value ... except rf.HashMismatch: # body changed since signing ... except rf.InvalidSignature: # Ed25519 verify failed ... # 所有五个子类都继承自 rf.EnvelopeVerificationError。 ``` 成功时,`verify_envelope_or_raise` 会返回底层的 `VerificationOutcome`。 只要您需要针对不同的失败原因 做出不同反应,就应使用此方法,而不是旧版返回布尔值的流程。 ### 相同的流程,命令行方式 ``` # Client echo '{"y_true":[1,0,1,1],"y_pred":[1,0,0,0],"group_a":[1,1,0,0],"group_b":[0,0,1,1]}' \ > input.json regaudit-fhe audit fairness -i input.json -o envelope.json # Regulator regaudit-fhe verify -i envelope.json --trusted-keys trust_store.json --strict ``` 监管方命令在成功时退出码为 0,在类型化验证 失败时退出码为 1(并附带指明 `reason` 的 JSON 主体), 在 CLI 输入错误时退出码为 2。 不带 `--trusted-keys` 的 `--strict` 是一个严重错误:严格路径 要求显式的 trust store。 `regaudit-fhe audit --schema` 会打印每个 原语所期望的 JSON 结构。 ## 审计信封 每次 `audit_*` 调用都可以通过 `regaudit_fhe.envelope(...)` 封装为 面向监管方的 JSON 信封: ``` { "schema": "regaudit-fhe.report.v1", "library_version": "current release", "primitive": "fairness", "backend": "plaintext-slotvec", "parameter_set_hash": "sha256:6b8aedc173e2c94e…", "input_commitments": { "y_true": "sha256:a5c4…", "y_pred": "sha256:7e91…" }, "result": { "max_gap": 0.0312, "threshold_breached": false }, "receipt": { "sha256": "sha256:9f3c…b4a7", "signature_alg": "Ed25519", "signature": "base64:MEUCIQDX…", "key_id": "auditor-key-2026-04" } } ``` `schema`、`parameter_set_hash` 和 `input_commitments` 为 监管方提供了他们所需的确切引用、参数绑定和输入指纹。 未签名的 SHA-256 回执仅用作篡改证据; 签名回执(自 `regaudit-fhe` v0.0.2 起为默认项) 在验证者信任签名密钥时,可提供签发方的真实性。 ## 示例 [`examples/`](examples/) 文件夹提供了四个端到端流程: | 文件 | 流程 | | --------------------------------------- | ------------------------------------------------------------------------------------------------- | | `01_client_local_audit.py` | 对合成数据进行内部审计;在本地归档 JSON。 | | `02_client_to_regulator.py` | 构建监管方提交包。 | | `03_regulator_verify.py` | 针对 `TrustStore` 验证包中的每个信封;显示类型化的失败原因。 | | `04_cli_roundtrip.sh` | 纯 CLI:输入 → 审计 → 验证,无需 Python 知识。 | 在 `pip install -e .[dev]` 之后运行其中任何一个即可。 ## 布局 ``` src/regaudit_fhe/ _slot.py plaintext SlotVec model with depth-budget enforcement _validation.py finite/binary/length input guards cli.py regaudit-fhe CLI entrypoint reports.py audit envelope: canonical JSON, parameter-set hash, input commitments, Ed25519 signing, verify_envelope_or_raise() schemas.py JSON Schema loader + validator trust.py TrustStore + typed verification exceptions (UntrustedIssuer, RevokedIssuer, WrongParameterSet, HashMismatch, InvalidSignature, TimestampInvalid) schemas/ bundled Draft-2020-12 schemas (one per input/output + envelope) server.py hardened FastAPI HTTP audit server egf_imss.py fairness primitive etk_fpa_hbc.py provenance primitive esc_cia.py concordance primitive ecp_qssp.py calibration primitive ew1_cdsf.py drift primitive ecmd_jps.py disagreement primitive fhe/ TenSEAL CKKS encrypted backend (optional [fhe] extra): context.py build_d6_context, CKKSContext params.py validated CKKSParams slot_vec.py EncryptedSlotVec mirroring the plaintext SlotVec API primitives.py encrypted variants of every audit primitive docs/specs/ per-primitive technical specifications docs/THREAT_MODEL.md roles, key custody, per-primitive public-surface tables docs/COMPLIANCE.md regulator-facing scope statement and disclaimers docs/DEPLOYMENT.md server hardening guide + production checklist docs/SUPPLY_CHAIN.md Sigstore verification, SBOM, reproducible build notes docs/roadmap/ design notes for non-shipping work schemas/ source-of-truth JSON Schemas tests/ unit, integration, edge-case, property-based, schema, security examples/ client + regulator end-to-end flows benchmarks/ d=6 CKKS wall-clock + memory benchmarks ``` ## JSON schemas 每个原语输入、原语输出以及审计信封本身 都附带了位于 [`schemas/`](schemas/) 下的 Draft-2020-12 JSON Schema。 审计员和集成商可以固定特定的 schema 版本,并拒绝 不符合规范的 payload。 ``` regaudit-fhe schema --list regaudit-fhe schema fairness.input regaudit-fhe schema envelope ``` CLI 和 HTTP 服务器在调用审计原语之前,会根据 匹配的 schema 验证每个请求体;失败会返回 HTTP 422 / CLI 退出码 2,并带有指向出错 字段的结构化指针。编程方式访问: ``` import regaudit_fhe as rf rf.list_schemas() # all 13 names rf.load_schema("fairness.input") # raw schema dict rf.validate_input("fairness", payload) # raises rf.SchemaError on bad input rf.validate_envelope(env_dict) # check a regulator-side envelope ``` ## 真实 CKKS 基准测试 `[fhe]` 额外依赖提供了真实的 TenSEAL CKKS 后端;其测量结果 转载自 `benchmarks/results/SUMMARY.md`(机器可读的 JSON 位于 `benchmarks/results/bench_fhe_.json`)。 | 原语 | N | 插槽 | 观测/声明深度 | 旋转 | ct×ct | ct×pt | 运行时间 | RAM | 最大绝对误差 | 阈值翻转 | |--------------|-----:|-------:|----------------|----------:|------:|------:|--------:|--------:|-------------|----------------| | fairness | 2^14 | 8 192 | 1/4 | 36 | 0 | 6 | 0.33 s | 887 MB | 4.8 × 10⁻⁷ | 0.00% | | provenance | 2^14 | 8 192 | 1/3 | 96 | 0 | 16 | 0.90 s | 896 MB | 1.1 × 10⁻⁵ | 0.00% | | concordance | 2^14 | 8 192 | 5/5 | 36 | 8 | 3 | 5.26 s | 2.3 GB | 1.5 × 10⁻⁶ | 0.00% | | calibration | 2^14 | 8 192 | 3/4 | 0 | 2 | 1 | 0.03 s | 2.3 GB | 0 | 0.00% | | drift | 2^14 | 8 192 | 2/2 | 12 | 1 | 2 | 0.27 s | 2.3 GB | 2.2 × 10⁻⁶ | 0.00% | | disagreement | 2^14 | 8 192 | 3/5 | 0 | 12 | 0 | 0.31 s | 2.3 GB | 1.2 × 10⁻⁸ | 0.00% | | fairness | 2^15 | 16 384 | 1/4 | 36 | 0 | 6 | 0.74 s | 4.0 GB | 9.6 × 10⁻⁷ | 0.00% | | provenance | 2^15 | 16 384 | 1/3 | 96 | 0 | 16 | 2.04 s | 4.1 GB | 5.2 × 10⁻⁶ | 0.00% | | concordance | 2^15 | 16 384 | 5/5 | 36 | 8 | 3 | 13.91 s | 6.9 GB | 3.0 × 10⁻⁷ | 0.00% | | calibration | 2^15 | 16 384 | 3/4 | 0 | 2 | 1 | 0.08 s | 6.9 GB | 0 | 0.00% | | drift | 2^15 | 16 384 | 2/2 | 12 | 1 | 2 | 0.64 s | 6.9 GB | 7.1 × 10⁻⁶ | 0.00% | | disagreement | 2^15 | 16 384 | 3/5 | 0 | 12 | 0 | 0.64 s | 6.6 GB | 1.3 × 10⁻⁸ | 0.00% | 自己运行: ``` pip install regaudit-fhe[fhe] python benchmarks/bench_fhe.py --rings 14 15 --reps 3 ``` 添加 `--rings 16` 以使用 `N = 2^16`(较慢;会消耗数 GB 的 RAM)。 “阈值翻转”列是指,在针对违规 边界附近采样的输入进行 10–20 次试验中,CKKS 噪声导致加密电路在 布尔违规决策上与明文电路产生分歧的比率。 两个环上均无翻转意味着,在审计精度目标下,CKKS 噪声不会 改变监管阈值决策。 ## 验证全新克隆 发布关卡是一个 shell 代码块。任何未通过此代码块的 问题都是发布阻塞项: ``` git clone https://github.com/BAder82t/regaudit-fhe.git cd regaudit-fhe python -m venv .venv && source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" python -m py_compile src/regaudit_fhe/*.py src/regaudit_fhe/fhe/*.py tests/*.py python -c "import regaudit_fhe; print(regaudit_fhe.__version__)" regaudit-fhe --help regaudit-fhe schema --list pytest -q ``` CI 在每次推送时都会运行等效的矩阵(参见 [.github/workflows/ci.yml](.github/workflows/ci.yml)),并且此 README 顶部的徽章反映了最新结果。 ## 生产 / 监管就绪 — 已验证与未验证的内容 | 属性 | 状态 | | --------------------------------------- | ----------------------------------------------------------------------------------- | | Python 语法 + 导入 | 由 CI 在每次推送时验证。 | | 309 项测试的 pytest 套件 | 由 CI 在每次推送时验证(Linux py3.10–3.13 + macOS py3.12 / 3.13)。 | | 覆盖率门槛 | CI 中强制执行 `--cov-fail-under=80`;基线为 84%。 | | 类型检查 | `mypy` 为 CI 把关:19 个源文件中零错误。 | | 静态安全 | `bandit`(中危及以上)为 CI 把关;CodeQL(安全与质量在推送和每周定时运行。 | | Lint | `ruff check` 使用 E/F/W/B/S/UP/I/SIM/RUF/A 规则集为 CI 把关。 | | 真实 CKKS 加密后端 (TenSEAL) | 在 `[fhe]` 下提供;已进行等效性测试。 | | OpenFHE CKKS 后端(实验性) | 在 `[openfhe]` 下提供;可通过 registry 选择;已对 5/6 进行等效性测试 | | | 原语(concordance 待定矩形 `mm_pt`)。并非已验证的参考。 | | 外部密钥托管 (KMS / HSM) | `CallableKeyProvider` 将签名密钥保存在主机外;签名错误时 fails closed。 | | 差分隐私输出噪声 | 可选的 `regaudit_fhe.dp`(Laplace / Gaussian);已签名的 `dp` 块。敏感度为 | | | 部署者的责任——库负责校准,但不负责设限。 | | 生成的 API 参考 | `pdoc` HTML 在 CI 中构建(`docs.yml`);参见 [docs/API.md](docs/API.md)。 | | 签名审计信封 (Ed25519) | 已提供;canonical-JSON + 篡改测试。 | | Trust store + 类型化验证器失败 | `TrustStore` + 六个 `EnvelopeVerificationError` 子类;CLI `--trusted-keys`。 | | JSON Schemas | 已提供;在每个 CLI / API 请求时验证。 | | 加固的 HTTP 服务器 | 恒定时间 bearer 比较、日志中的不透明 key_id、`DEV_MODE` 拒绝非环回绑定 | | |、作用域、速率限制、CORS、审计日志。 | | 并发安全的深度状态 | 基于 `ContextVar` 的 `last_depth` / `last_depths`;跨线程 / asyncio 隔离。 | | 可重现的 wheel | CI 使用固定的 `SOURCE_DATE_EPOCH` 构建两次,断言 SHA-256 稳定。 | | Sigstore 签名的 wheel + sdist | 无密钥 OIDC bundle 附加到每个 GitHub Release。 | | N=2^14, N=2^15 下的真实基准测试 | 已提供;可从 `benchmarks/bench_fhe.py` 重现。 | `regaudit-fhe` 是您今天就可以引入合规 工作流的依赖项;但它本身并不是一个完整的合规产品。 [COMPLIANCE.md](COMPLIANCE.md) 逐条法规列出了每个原语无法 证明的内容。 ## 成熟度与状态 当前版本包含: - 具有严格深度预算强制执行的明文 SlotVec 模型, - 镜像 SlotVec 代数并通过 端到端密文 / 明文等效性测试的 TenSEAL CKKS 后端, - 一个带有实验性 OpenFHE CKKS 后端的 可插拔 backend registry(`regaudit_fhe.fhe.get_backend` / `available_backends`),该后端 通过 Halevi–Shoup 对角线方法运行相同的电路, - 带有 canonical-JSON 规则、 parameter-set hashing 和 input commitments 的 Ed25519 签名审计信封, - 一个类型化的验证器接口——`TrustStore`(key_id → PEM,可选 撤销,可选 parameter-set 固定)以及 `verify_envelope_or_raise`,会为监管方侧使用抛出 `UntrustedIssuer` / `RevokedIssuer` / `WrongParameterSet` / `HashMismatch` / `InvalidSignature` / `TimestampInvalid`, - 一个密钥托管衔接层——`CallableKeyProvider` 将 Ed25519 签名 密钥保存在 KMS/HSM 中,因此只有公共 PEM 和 sign-callable 会进入 审计主机, - 一个可选的差分隐私输出扰动层 (`regaudit_fhe.dp`:Laplace / Gaussian 机制、基本的 composition accountant,以及信封中已签名的 `dp` 披露块), - 针对每个输入、输出以及信封本身的 JSON Schemas, - 加固的 HTTP 审计服务器,具有恒定时间 bearer token 比较、日志中不透明的哈希 key_id、作用域、body 大小限制、 速率限制、结构化日志、CORS 控制以及 `DEV_MODE` 非环回绑定保护, - 通过 `ContextVar` 实现的并发安全深度记录,因此并发的 加密请求不会在深度状态上发生竞态, - 供应链控制:Trusted-Publisher PyPI 发布、Sigstore 对 wheel + sdist 的无密钥签名、可重现构建 CI 门控 (固定的 `SOURCE_DATE_EPOCH`,两次构建,相同的 SHA)、 CycloneDX SBOM、`pip-audit`、CodeQL、每周的 Dependabot。 不接受贡献——请参阅 [CONTRIBUTING.md](CONTRIBUTING.md)。
标签:AI审计, Python, 同态加密, 数据合规, 无后门, 逆向工具, 隐私计算