Peach: Local-first video metadata scraper and media manager.
fix(certs): 采用社区补丁补齐叶子密钥标识与存量补签
peach-patcher4d41f47c932a
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 104e5ae2a..954ecf4e3 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -431,6 +431,8 @@ minnano-av 与 javdb 使用实际解析并核对身份后落库的记录,显源码部署用本机自签的 CA 签发 HTTPS 证书(`.local` 名字无法使用 Let's Encrypt 这类公开证书)。证书和私钥都在本机 `<Peach 数据目录>/secrets/tls/`。+托盘启动或本机地址变化时检查叶子证书的覆盖范围、到期时间及颁发者密钥标识(AKI)。缺少 AKI 的存量叶子会使用原 CA 补签并保留备份,已安装的 CA 信任继续有效,无需手动重建 CA 或重装信任;符合条件的叶子不会重复补签。运行期和 TLS 设置脚本均显式签入 SKI、AKI,以满足严格 TLS 校验。+1. 把 `peach-local-ca.crt` 复制到要访问的设备上。只复制这一个文件,任何私钥都不要外发。2. 在设备上安装并信任它。iPhone/iPad 装好描述文件后,还要在「设置 → 通用 → 关于本机 → 证书信任设置」里打开完全信任。3. 用 `openssl x509 -noout -fingerprint` 核对设备上的证书指纹与本机一致。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 0086947e8..f5644548f 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -1,5 +1,11 @@# 复用清单+## 叶子证书密钥标识与存量补签++采用 peach-patcher 的 [PR #177](https://github.com/peach-mitao/peach/pull/177),固定来源提交 `62927d4b975bdad3420ef214bc9330382a4233d6`,许可证沿用本项目 AGPL-3.0-or-later。运行期与两个 TLS 设置脚本复用 OpenSSL 的 [`subjectKeyIdentifier` 和 `authorityKeyIdentifier`](https://docs.openssl.org/3.0/man5/x509v3_config/#authority-key-identifier) 扩展,显式签入叶子证书;标准库 [`ssl.create_default_context`](https://docs.python.org/3.14/library/ssl.html#ssl.create_default_context) 的严格验证策略保持启用。现有签发工具随运行环境提供,无新增依赖。++`certs.reissue_reason` 将缺少 AKI 的叶子证书交给已有补签流程,CA 和已安装信任保持原样;合格叶子沿用 SAN 与到期判据。存量回归采用临时 CA、缺 AKI 的有效叶子、真实严格 TLS 握手和补签后重复检查,核对 CA 保留及叶子备份。社区用例按 OpenSSL 与 LibreSSL 的缺标识签发行为适配,不用跳过测试代替存量验证。未采用 mkcert 或新增 X.509 编码库,现有工具已覆盖签发能力,Peach 仅保留 CA 生命周期和补签策略。+## 测试规划与阶段计时`scripts/test_resume.py` 的 `ImpactPlan` 在一次恢复规划内缓存域集合、测试导入图与路径影响;调用方用当前快照创建计划,检查点输入改变时重新计算。`scripts/test_runner.py` 的 `local_batches` 统一快速检查、普通分片和内部并行容器的执行顺序,`scripts/test_run_progress.py` 的 `phase` 将阶段墙钟写入正式测试记录。沿用标准库与现有单项证明协议,不改变证明有效期、环境身份或完整批次要求。使用范围与计时口径见 [测试与 CI](TESTING.md)。diff --git a/scripts/setup_local_tls.ps1 b/scripts/setup_local_tls.ps1index 644a844b3..a05d7e933 100644--- a/scripts/setup_local_tls.ps1+++ b/scripts/setup_local_tls.ps1@@ -70,6 +70,8 @@ basicConstraints=critical,CA:FALSEkeyUsage=critical,digitalSignature,keyEnciphermentextendedKeyUsage=serverAuthsubjectAltName=DNS:$DnsName,IP:$Address+subjectKeyIdentifier=hash+authorityKeyIdentifier=keyid,issuer"@ | Set-Content -LiteralPath $extensions -Encoding ascii& $openssl genrsa -out $caKey 3072diff --git a/scripts/setup_local_tls.sh b/scripts/setup_local_tls.shindex e718fb2d1..5f0288aa0 100644--- a/scripts/setup_local_tls.sh+++ b/scripts/setup_local_tls.sh@@ -60,6 +60,8 @@ subjectAltName = ${SAN}keyUsage = critical, digitalSignature, keyEnciphermentextendedKeyUsage = serverAuthbasicConstraints = critical, CA:FALSE+subjectKeyIdentifier = hash+authorityKeyIdentifier = keyid, issuerCNFopenssl req -new -newkey rsa:2048 -nodes \diff --git a/src/peach/certs.py b/src/peach/certs.pyindex 0675c174c..540d481d3 100644--- a/src/peach/certs.py+++ b/src/peach/certs.py@@ -96,12 +96,23 @@ def not_after(cert: Path) -> datetime | None:return None+def has_authority_key_identifier(cert: Path) -> bool:+ """叶子证书包含严格 X.509 校验要求的颁发者密钥标识。"""+ try:+ text = _openssl("x509", "-in", str(cert), "-noout", "-text")+ except (RuntimeError, OSError):+ return False+ return "Authority Key Identifier" in text++def reissue_reason(files: CertificateFiles, names: set[str], addresses: set[str], now: datetime | None = None,) -> str | None:"""需要重签就返回原因,不需要返回 None。"""if not files.cert.is_file() or not files.key.is_file():return "服务器证书不存在"+ if not has_authority_key_identifier(files.cert):+ return "证书缺少颁发者密钥标识"have_names, have_addresses = subject_alt_names(files.cert)missing = (names - have_names) | (addresses - have_addresses)if missing:@@ -132,6 +143,8 @@ def reissue("keyUsage = critical, digitalSignature, keyEncipherment\n""extendedKeyUsage = serverAuth\n""basicConstraints = critical, CA:FALSE\n"+ "subjectKeyIdentifier = hash\n"+ "authorityKeyIdentifier = keyid, issuer\n")with tempfile.TemporaryDirectory() as raw:work = Path(raw)diff --git a/tests/test_certs.py b/tests/test_certs.pyindex 6be667c03..3cce477af 100644--- a/tests/test_certs.py+++ b/tests/test_certs.py@@ -1,5 +1,10 @@+import os+import shutil+import socket+import sslimport subprocessimport tempfile+import threadingimport unittestfrom datetime import datetime, timedelta, timezonefrom pathlib import Path@@ -8,6 +13,7 @@ from unittest import mockfrom peach.certs import (CERT_DAYS,CertificateFiles,+ create_local_ca,ensure_certificate,not_after,reissue,@@ -42,7 +48,7 @@ class CertificateTests(unittest.TestCase):def setUp(self):self._tmp = tempfile.TemporaryDirectory()- self.tls = Path(self._tmp.name) / "tls"+ self.tls = (Path(self._tmp.name) / "tls").resolve()self.files = make_ca(self.tls)self.addCleanup(self._tmp.cleanup)@@ -82,6 +88,112 @@ class CertificateTests(unittest.TestCase):reason = reissue_reason(self.files, {"peach.local"}, {"127.0.0.1", "198.51.100.7"})self.assertIn("198.51.100.7", reason or "")+ def test_reissue_writes_key_identifiers_for_strict_verification(self):+ """叶子证书携带密钥标识,满足严格链验证。"""+ files = CertificateFiles.under((Path(self._tmp.name) / "strict").resolve())+ create_local_ca(files)+ reissue(files, "peach.local", {"peach.local", "localhost"}, {"127.0.0.1"})+ text = subprocess.run(["openssl", "x509", "-in", str(files.cert), "-noout", "-text"],+ check=True, capture_output=True, text=True, encoding="utf-8").stdout+ self.assertIn("Authority Key Identifier", text)+ self.assertIn("Subject Key Identifier", text)+ self.assert_strict_tls(files)++ def test_a_certificate_without_key_identifier_triggers_reissue(self):+ """缺少颁发者密钥标识的存量叶子按现有 CA 自动补签。"""+ work = Path(self._tmp.name).resolve()+ files = CertificateFiles.under(work / "legacy")+ create_local_ca(files)+ version = subprocess.run(["openssl", "version"], check=True, capture_output=True,+ text=True, encoding="utf-8").stdout+ identifiers = "" if "LibreSSL" in version else (+ "subjectKeyIdentifier = none\nauthorityKeyIdentifier = none\n")+ (work / "leaf.cnf").write_text(+ "[req]\ndistinguished_name = dn\nprompt = no\n[dn]\nCN = peach.local\n"+ "[ext]\nsubjectAltName = DNS:peach.local,DNS:localhost,IP:127.0.0.1\n"+ "basicConstraints = critical, CA:FALSE\nkeyUsage = critical,digitalSignature,keyEncipherment\n"+ "extendedKeyUsage = serverAuth\n" + identifiers, encoding="utf-8")+ subprocess.run(["openssl", "req", "-new", "-newkey", "rsa:2048", "-nodes",+ "-keyout", str(files.key), "-out", str(work / "leaf.csr"),+ "-config", str(work / "leaf.cnf")], check=True, capture_output=True)+ subprocess.run(["openssl", "x509", "-req", "-in", str(work / "leaf.csr"),+ "-CA", str(files.ca_cert), "-CAkey", str(files.ca_key), "-CAcreateserial",+ "-out", str(files.cert), "-days", "397", "-extfile", str(work / "leaf.cnf"),+ "-extensions", "ext"], check=True, capture_output=True)+ text = subprocess.run(["openssl", "x509", "-in", str(files.cert), "-noout", "-text"],+ check=True, capture_output=True, text=True, encoding="utf-8").stdout+ self.assertNotIn("Authority Key Identifier", text)+ original_ca = (files.ca_cert.read_bytes(), files.ca_key.read_bytes())+ original_leaf = files.cert.read_bytes()+ self.assertEqual(reissue_reason(files, {"peach.local", "localhost"}, {"127.0.0.1"}),+ "证书缺少颁发者密钥标识")+ self.assertEqual(ensure_certificate(files.cert.parent, "peach.local", set()),+ "证书缺少颁发者密钥标识")+ self.assertEqual((files.ca_cert.read_bytes(), files.ca_key.read_bytes()), original_ca)+ self.assertNotEqual(files.cert.read_bytes(), original_leaf)+ self.assertEqual(next(files.cert.parent.glob("peach.crt.bak.*")).read_bytes(), original_leaf)+ self.assert_strict_tls(files)+ refreshed = (files.cert.read_bytes(), files.key.read_bytes())+ self.assertIsNone(ensure_certificate(files.cert.parent, "peach.local", set()))+ self.assertEqual((files.cert.read_bytes(), files.key.read_bytes()), refreshed)++ def assert_strict_tls(self, files):+ """通过回环握手验证项目 CA、主机名与严格 X.509 校验。"""+ server = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ server.load_cert_chain(files.cert, files.key)+ client = ssl.create_default_context(cafile=str(files.ca_cert))+ client.verify_flags |= ssl.VERIFY_X509_STRICT+ failures = []+ with socket.socket() as listener:+ listener.bind(("127.0.0.1", 0))+ listener.listen(1)+ listener.settimeout(5)++ def accept():+ try:+ connection, _ = listener.accept()+ with connection, server.wrap_socket(connection, server_side=True) as secured:+ secured.sendall(b"verified")+ except Exception as exc:+ failures.append(exc)++ worker = threading.Thread(target=accept)+ worker.start()+ try:+ with socket.create_connection(listener.getsockname(), timeout=5) as connection:+ with client.wrap_socket(connection, server_hostname="peach.local") as secured:+ self.assertEqual(secured.recv(8), b"verified")+ finally:+ worker.join(6)+ self.assertFalse(worker.is_alive())+ self.assertEqual(failures, [])++ @unittest.skipUnless(os.name == "nt", "需要 Windows PowerShell 签发入口")+ def test_powershell_setup_issues_a_strict_leaf(self):+ tls = (Path(self._tmp.name) / "powershell").resolve()+ script = Path(__file__).resolve().parents[1] / "scripts" / "setup_local_tls.ps1"+ result = subprocess.run(+ [shutil.which("pwsh"), "-NoProfile", "-File", str(script), "-Address", "127.0.0.1",+ "-DnsName", "peach.local", "-OutDir", str(tls)],+ capture_output=True, text=True, encoding="utf-8", timeout=30)+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assert_strict_tls(CertificateFiles.under(tls))++ @unittest.skipIf(os.name == "nt", "需要 POSIX 签发入口")+ def test_shell_setup_preserves_ca_and_issues_a_strict_leaf(self):+ tls = (Path(self._tmp.name) / "shell").resolve()+ files = CertificateFiles.under(tls)+ create_local_ca(files)+ ca = (files.ca_cert.read_bytes(), files.ca_key.read_bytes())+ script = Path(__file__).resolve().parents[1] / "scripts" / "setup_local_tls.sh"+ result = subprocess.run(+ ["/bin/sh", str(script)], env={**os.environ, "PEACH_TLS_DIR": str(tls),+ "PEACH_LAN_IP": "none", "PEACH_MDNS_NAME": "peach"},+ capture_output=True, text=True, encoding="utf-8", timeout=30)+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual((files.ca_cert.read_bytes(), files.ca_key.read_bytes()), ca)+ self.assert_strict_tls(files)+def test_near_expiry_triggers_reissue(self):reissue(self.files, "peach.local", {"peach.local"}, {"127.0.0.1"})soon = datetime.now(timezone.utc) + timedelta(days=CERT_DAYS - 5)