Peach: Local-first video metadata scraper and media manager.
fix(setup): TLS 签发失败时保留可重试的首次设置
longmeidao7c86ce7ed904
diff --git a/src/peach/certs.py b/src/peach/certs.pyindex 14f1d316b..e9f550c85 100644--- a/src/peach/certs.py+++ b/src/peach/certs.py@@ -59,6 +59,8 @@ class CertificateFiles:def _openssl(*args: str, stdin: bytes | None = None) -> str:binary = shutil.which("openssl") or "/usr/bin/openssl"+ if not Path(binary).is_file():+ raise RuntimeError("未找到 OpenSSL,请安装并加入 PATH 后重试")result = subprocess.run([binary, *args], input=stdin, capture_output=True,# 显式给 encoding:text=True 会用平台默认编码,中文输出会静默丢成空 stdout。@@ -74,6 +76,11 @@ def _openssl(*args: str, stdin: bytes | None = None) -> str:"utf-8", "replace")+def require_openssl() -> None:+ """在必须启用 TLS 的首次设置保存前,核对签发工具可执行。"""+ _openssl("version")++def subject_alt_names(cert: Path) -> tuple[set[str], set[str]]:"""返回 (DNS 名字集合, IP 集合)。读不出来就当成空,调用方会据此重签。"""try:diff --git a/src/peach/onboarding.py b/src/peach/onboarding.pyindex 6e9fd0377..3a9e91dfd 100644--- a/src/peach/onboarding.py+++ b/src/peach/onboarding.py@@ -447,6 +447,7 @@ def create_data_tree(config: PeachConfig) -> DataTree:def apply(config: PeachConfig, answers: Answers, *, windows: bool, force: bool = False,access_password: str = "", peach_proxy_values: dict | None = None,+ require_tls: bool = False,) -> Applied:"""把答案变成一台可以直接起服务的机器:目录、账本、CA、口令、设置文件。@@ -454,7 +455,11 @@ def apply(设置页都只调这一个函数,两条前端因此不可能在「首次运行到底做了什么」上分叉。"""prepared = configure(config, answers, windows=windows)+ if require_tls:+ certs.require_openssl()tree = create_data_tree(prepared)+ if require_tls and tree.ca_error:+ raise RuntimeError(tree.ca_error)from . import accessaccess_path = prepared.directory("secrets") / "access.json"if not config.present and not access_path.exists():diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.pyindex d48e0a93c..08402032d 100644--- a/src/peach/routes_pages.py+++ b/src/peach/routes_pages.py@@ -602,7 +602,7 @@ async def setup_submit_json(request: Request):raise HTTPException(status_code=409, detail="settings file already exists")try:applied = onboarding.apply(resolved, answers, windows=windows, access_password=password,- peach_proxy_values=proxy_values)+ peach_proxy_values=proxy_values, require_tls=windows and not standalone)settings_file.remember_data_root(settings_file.active(), applied.config)except (OSError, RuntimeError) as exc:errors = {"data_root": str(exc)}diff --git a/tests/test_certs.py b/tests/test_certs.pyindex 3cce477af..6dd960e31 100644--- a/tests/test_certs.py+++ b/tests/test_certs.py@@ -34,6 +34,15 @@ def make_ca(tls_dir: Path) -> CertificateFiles:class CertificateTests(unittest.TestCase):+ def test_missing_openssl_reports_the_required_tool_before_launch(self):+ from peach import certs+ with mock.patch.object(certs.shutil, 'which', return_value=None), \+ mock.patch.object(certs.Path, 'is_file', return_value=False), \+ mock.patch.object(certs.subprocess, 'run') as run:+ with self.assertRaisesRegex(RuntimeError, '未找到 OpenSSL'):+ certs.require_openssl()+ run.assert_not_called()+def test_openssl_hides_its_windows_console_and_preserves_output(self):from peach import certsresult = subprocess.CompletedProcess(['openssl'], 0, 'certificate output', '')diff --git a/tests/test_onboarding.py b/tests/test_onboarding.pyindex 5f2e2d9bb..dab6189f4 100644--- a/tests/test_onboarding.py+++ b/tests/test_onboarding.py@@ -377,6 +377,21 @@ class ApplyTests(_Case):loaded, _ = onboarding.resolve_config(self.root / "peach-data", environ={})self.assertEqual(loaded.server.port, 9100)+ def test_required_tls_checks_the_signer_before_creating_the_data_tree(self):+ with mock.patch.object(onboarding.certs, "require_openssl", side_effect=RuntimeError("OpenSSL 未取得")):+ with self.assertRaisesRegex(RuntimeError, "OpenSSL"):+ onboarding.apply(self.config, self._answers(), windows=NATIVE_WINDOWS, require_tls=True)+ self.assertFalse((self.root / "peach-data" / "database" / "ledger.db").exists())+ self.assertFalse((self.root / "peach-data" / "config.toml").exists())+ self.certs.assert_not_called()++ def test_required_tls_does_not_save_settings_after_certificate_generation_fails(self):+ self.certs.side_effect = RuntimeError("证书签发失败")+ with mock.patch.object(onboarding.certs, "require_openssl"):+ with self.assertRaisesRegex(RuntimeError, "证书签发失败"):+ onboarding.apply(self.config, self._answers(), windows=NATIVE_WINDOWS, require_tls=True)+ self.assertFalse((self.root / "peach-data" / "config.toml").exists())+def test_the_first_scan_marker_is_consumed_exactly_once(self):applied = onboarding.apply(self.config, self._answers(), windows=NATIVE_WINDOWS)config = applied.config@@ -465,6 +480,19 @@ class SetupJsonContractTests(_SetupHttpCase):QUESTIONS = "/api/setup/questions"SUBMIT = "/api/setup"+ @unittest.skipUnless(NATIVE_WINDOWS, 'Windows 源码首设需要 TLS')+ def test_windows_source_setup_reports_missing_openssl_and_accepts_a_retry(self):+ with mock.patch.object(distribution, 'standalone', return_value=False), \+ mock.patch.object(onboarding.certs, 'require_openssl',+ side_effect=RuntimeError('未找到 OpenSSL')) as require:+ response = self._send('POST', self.SUBMIT, json=self._body(scan_now=False))+ self.assertEqual(response.status_code, 400, response.text)+ self.assertIn('OpenSSL', response.json()['errors']['data_root'])+ self.assertFalse((self.data_root / 'config.toml').exists())+ require.side_effect = None+ response = self._send('POST', self.SUBMIT, json=self._body(scan_now=False))+ self.assertEqual(response.status_code, 200, response.text)+def _rows(self, *paths, location="local"):return [{"path": str(path), "location": location,"root": "" if NATIVE_WINDOWS else "R:\\media" + (str(index + 1) if index else "")}