fix(updater): harden forced startup updates
This commit is contained in:
1 parent
55d38c46ec
commit
b61f766ea6
7 files changed
+270
-12
No files matched your search
+4
-2
@@ -10,6 +10,10 @@ _BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if _BASE_DIR not in sys.path:
|
||||
sys.path.insert(0, _BASE_DIR)
|
||||
|
||||
from douyin.updater.bootstrap import run_startup_update_check_early
|
||||
|
||||
run_startup_update_check_early(app_name="run_cli")
|
||||
|
||||
# 可选:全局参数/调用跟踪(仅在环境变量 PARAM_TRACK_ALL=1 时启用)
|
||||
if os.environ.get("PARAM_TRACK_ALL") == "1":
|
||||
try:
|
||||
@@ -99,7 +103,6 @@ os.environ.setdefault("OMP_NUM_THREADS", "1")
|
||||
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
from douyin.license.license_manager import require_license_or_exit
|
||||
from douyin.updater.force_update import run_startup_update_check
|
||||
|
||||
|
||||
def ensure_adb_in_path() -> None:
|
||||
@@ -341,7 +344,6 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
run_startup_update_check(app_name="run_cli")
|
||||
require_license_or_exit()
|
||||
ensure_adb_in_path()
|
||||
args = parse_args(argv)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
|
||||
def run_startup_update_check_early(app_name: str) -> None:
|
||||
"""Run the updater before importing the heavier app modules."""
|
||||
try:
|
||||
from douyin.updater.force_update import run_startup_update_check
|
||||
|
||||
run_startup_update_check(app_name=app_name)
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception as exc:
|
||||
print(f"[更新] {app_name} 早期更新检查异常:{exc}", file=sys.stderr)
|
||||
@@ -4,6 +4,7 @@ import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
@@ -37,6 +38,8 @@ class UpdateSettings:
|
||||
timeout_seconds: float = 20.0
|
||||
fail_closed: bool = True
|
||||
require_sha256: bool = True
|
||||
require_https: bool = True
|
||||
allow_cross_origin: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -148,9 +151,39 @@ def load_update_settings() -> UpdateSettings:
|
||||
timeout_seconds=timeout_seconds,
|
||||
fail_closed=_to_bool(section.get("fail_closed"), True),
|
||||
require_sha256=_to_bool(section.get("require_sha256"), True),
|
||||
require_https=_to_bool(section.get("require_https"), True),
|
||||
allow_cross_origin=_to_bool(section.get("allow_cross_origin"), False),
|
||||
)
|
||||
|
||||
|
||||
def _origin(value: str) -> tuple[str, str, int]:
|
||||
parsed = urlparse(value)
|
||||
scheme = (parsed.scheme or "").lower()
|
||||
host = (parsed.hostname or "").lower()
|
||||
port = parsed.port
|
||||
if port is None:
|
||||
port = 443 if scheme == "https" else 80 if scheme == "http" else -1
|
||||
return scheme, host, port
|
||||
|
||||
|
||||
def _validate_manifest_url(settings: UpdateSettings) -> None:
|
||||
parsed = urlparse(settings.manifest_url)
|
||||
if settings.require_https and parsed.scheme.lower() != "https":
|
||||
raise UpdateError("manifest_url 必须使用 HTTPS")
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
raise UpdateError("manifest_url 必须是完整 URL")
|
||||
|
||||
|
||||
def _validate_installer_url(settings: UpdateSettings, download_url: str) -> None:
|
||||
parsed = urlparse(download_url)
|
||||
if settings.require_https and parsed.scheme.lower() != "https":
|
||||
raise UpdateError("安装包 URL 必须使用 HTTPS")
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
raise UpdateError("安装包 URL 必须是完整 URL")
|
||||
if not settings.allow_cross_origin and _origin(download_url) != _origin(settings.manifest_url):
|
||||
raise UpdateError("安装包 URL 必须与 manifest 同源")
|
||||
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict[str, Any]:
|
||||
req = Request(url, headers={"User-Agent": f"douyin-guaji-updater/{VERSION}"})
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
@@ -193,18 +226,73 @@ def _safe_installer_name(manifest: dict[str, Any], download_url: str, version: s
|
||||
return re.sub(r'[<>:"/\\|?*]+', "_", raw)
|
||||
|
||||
|
||||
def _installer_log_arg(version: str) -> str:
|
||||
safe_version = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(version or "unknown"))
|
||||
log_dir = Path(path_config.get_logs_dir()) / "updates"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
return f"/LOG={log_dir / f'installer-{safe_version}.log'}"
|
||||
|
||||
|
||||
def _build_installer_cmd(
|
||||
installer_path: Path,
|
||||
installer_args: tuple[str, ...],
|
||||
version: str,
|
||||
) -> list[str]:
|
||||
args = [str(x) for x in installer_args]
|
||||
if not any(arg.upper().startswith("/LOG") for arg in args):
|
||||
args.append(_installer_log_arg(version))
|
||||
return [str(installer_path), *args]
|
||||
|
||||
|
||||
def launch_installer(cmd: list[str]) -> None:
|
||||
creationflags = 0
|
||||
cwd = str(Path(cmd[0]).parent)
|
||||
if sys.platform.startswith("win"):
|
||||
creationflags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
|
||||
parent_pid = os.getpid()
|
||||
quoted_args = ", ".join(_ps_quote(arg) for arg in cmd[1:])
|
||||
script = (
|
||||
f"Wait-Process -Id {parent_pid} -ErrorAction SilentlyContinue; "
|
||||
"$p = Start-Process "
|
||||
f"-FilePath {_ps_quote(cmd[0])} "
|
||||
f"-ArgumentList @({quoted_args}) "
|
||||
"-Wait -PassThru; "
|
||||
"exit $p.ExitCode"
|
||||
)
|
||||
subprocess.Popen(
|
||||
[
|
||||
"powershell",
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-WindowStyle",
|
||||
"Hidden",
|
||||
"-Command",
|
||||
script,
|
||||
],
|
||||
cwd=cwd,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
close_fds=True,
|
||||
creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
|
||||
)
|
||||
return
|
||||
|
||||
creationflags = 0
|
||||
subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(Path(cmd[0]).parent),
|
||||
cwd=cwd,
|
||||
close_fds=True,
|
||||
creationflags=creationflags,
|
||||
)
|
||||
|
||||
|
||||
def _ps_quote(value: str) -> str:
|
||||
text = str(value)
|
||||
if sys.platform.startswith("win"):
|
||||
return "'" + text.replace("'", "''") + "'"
|
||||
return shlex.quote(text)
|
||||
|
||||
|
||||
def perform_forced_update(
|
||||
settings: UpdateSettings,
|
||||
*,
|
||||
@@ -216,6 +304,7 @@ def perform_forced_update(
|
||||
if not settings.enabled:
|
||||
return UpdateResult("disabled", "未配置更新服务器")
|
||||
|
||||
_validate_manifest_url(settings)
|
||||
manifest = fetch_manifest(settings.manifest_url, settings.timeout_seconds)
|
||||
latest_version = str(manifest.get("version", "") or "").strip()
|
||||
if not latest_version:
|
||||
@@ -227,6 +316,7 @@ def perform_forced_update(
|
||||
if not raw_url:
|
||||
raise UpdateError("manifest 缺少 url")
|
||||
download_url = urljoin(settings.manifest_url, raw_url)
|
||||
_validate_installer_url(settings, download_url)
|
||||
expected_sha = str(manifest.get("sha256") or "").strip().lower()
|
||||
if settings.require_sha256 and not re.fullmatch(r"[0-9a-fA-F]{64}", expected_sha):
|
||||
raise UpdateError("manifest 缺少有效 sha256")
|
||||
@@ -245,7 +335,7 @@ def perform_forced_update(
|
||||
pass
|
||||
raise UpdateError(f"sha256 校验失败: expected={expected_sha} actual={actual_sha}")
|
||||
|
||||
cmd = [str(installer_path), *settings.installer_args]
|
||||
cmd = _build_installer_cmd(installer_path, settings.installer_args, latest_version)
|
||||
launch_installer(cmd)
|
||||
return UpdateResult(
|
||||
"update_started",
|
||||
|
||||
+4
-2
@@ -8,6 +8,10 @@ _project_root = os.path.dirname(_script_dir)
|
||||
if _project_root not in sys.path:
|
||||
sys.path.insert(0, _project_root)
|
||||
|
||||
from douyin.updater.bootstrap import run_startup_update_check_early
|
||||
|
||||
run_startup_update_check_early(app_name="gui_app")
|
||||
|
||||
# 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化)
|
||||
from gui.gui_core import (
|
||||
RunParams,
|
||||
@@ -16,7 +20,6 @@ from gui.gui_core import (
|
||||
)
|
||||
from douyin.core.path_config import get_logs_dir
|
||||
from douyin.license.license_manager import require_license_or_exit
|
||||
from douyin.updater.force_update import run_startup_update_check
|
||||
from gui.components.wifi_adb_scan_dialog import open_scan_dialog # noqa: F401 re-export
|
||||
from gui.components.preview_view import (
|
||||
async_refresh_preview as _async_refresh_preview_impl,
|
||||
@@ -55,7 +58,6 @@ def format_gui_log_line(line: str) -> str: # noqa: F401 re-export for backward
|
||||
|
||||
|
||||
def main():
|
||||
run_startup_update_check(app_name="gui_app")
|
||||
require_license_or_exit()
|
||||
_bundle = setup_root_window(read_config=read_config)
|
||||
root = _bundle.root
|
||||
|
||||
+4
-2
@@ -18,9 +18,12 @@ project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if project_root not in sys.path:
|
||||
sys.path.insert(0, project_root)
|
||||
|
||||
from douyin.updater.bootstrap import run_startup_update_check_early
|
||||
|
||||
run_startup_update_check_early(app_name="web_gui")
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.license.license_manager import require_license_or_exit
|
||||
from douyin.updater.force_update import run_startup_update_check
|
||||
|
||||
# 从子包 re-export 顶层 helper(保持兼容)
|
||||
from gui.web_gui_pkg import (
|
||||
@@ -842,7 +845,6 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
|
||||
def main() -> int:
|
||||
run_startup_update_check(app_name="web_gui")
|
||||
require_license_or_exit()
|
||||
host = get_web_gui_host()
|
||||
# 支持 PORT / WEB_GUI_PORT 两种环境变量,默认 8000
|
||||
|
||||
+110
-2
@@ -72,9 +72,46 @@ def test_forced_update_downloads_verifies_and_launches_installer(tmp_path):
|
||||
assert result.status == "update_started"
|
||||
assert result.exit_required is True
|
||||
assert downloaded == ["https://example.test/DouyinGuaji-3.3.4-Setup.exe"]
|
||||
assert launched == [
|
||||
[str(tmp_path / "DouyinGuaji-3.3.4-Setup.exe"), "/VERYSILENT", "/CURRENTUSER"]
|
||||
assert launched
|
||||
assert launched[0][:3] == [
|
||||
str(tmp_path / "DouyinGuaji-3.3.4-Setup.exe"),
|
||||
"/VERYSILENT",
|
||||
"/CURRENTUSER",
|
||||
]
|
||||
assert any(arg.startswith("/LOG=") for arg in launched[0])
|
||||
|
||||
|
||||
def test_launch_installer_on_windows_waits_for_parent_before_setup(monkeypatch, tmp_path):
|
||||
from douyin.updater import force_update
|
||||
|
||||
calls: list[tuple[list[str], dict]] = []
|
||||
monkeypatch.setattr(force_update.sys, "platform", "win32")
|
||||
monkeypatch.setattr(force_update.os, "getpid", lambda: 24680)
|
||||
|
||||
def fake_popen(cmd, **kwargs):
|
||||
calls.append((list(cmd), kwargs))
|
||||
|
||||
class Proc:
|
||||
pass
|
||||
|
||||
return Proc()
|
||||
|
||||
monkeypatch.setattr(force_update.subprocess, "Popen", fake_popen)
|
||||
|
||||
installer = tmp_path / "DouyinGuaji Setup.exe"
|
||||
force_update.launch_installer([str(installer), "/VERYSILENT", "/LOG=C:\\tmp\\install.log"])
|
||||
|
||||
assert calls
|
||||
cmd, kwargs = calls[0]
|
||||
assert cmd[:4] == ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass"]
|
||||
assert "-WindowStyle" in cmd
|
||||
script = cmd[-1]
|
||||
assert "Wait-Process -Id 24680" in script
|
||||
assert "Start-Process" in script
|
||||
assert str(installer) in script
|
||||
assert kwargs["cwd"] == str(tmp_path)
|
||||
assert kwargs["close_fds"] is True
|
||||
assert kwargs["stdin"] is force_update.subprocess.DEVNULL
|
||||
|
||||
|
||||
def test_forced_update_rejects_hash_mismatch(tmp_path):
|
||||
@@ -111,6 +148,77 @@ def test_forced_update_rejects_hash_mismatch(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
def test_forced_update_rejects_insecure_manifest_url_by_default(tmp_path):
|
||||
from douyin.updater.force_update import (
|
||||
UpdateError,
|
||||
UpdateSettings,
|
||||
perform_forced_update,
|
||||
)
|
||||
|
||||
called = False
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict:
|
||||
nonlocal called
|
||||
called = True
|
||||
return {}
|
||||
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="http://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
)
|
||||
|
||||
with pytest.raises(UpdateError, match="HTTPS"):
|
||||
perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=fetch_manifest,
|
||||
download_file=lambda url, dest, timeout: None,
|
||||
launch_installer=lambda cmd: None,
|
||||
)
|
||||
|
||||
assert called is False
|
||||
|
||||
|
||||
def test_forced_update_rejects_cross_origin_installer_url_by_default(tmp_path):
|
||||
from douyin.updater.force_update import (
|
||||
UpdateError,
|
||||
UpdateSettings,
|
||||
perform_forced_update,
|
||||
)
|
||||
|
||||
payload = b"fake installer bytes"
|
||||
expected_sha = hashlib.sha256(payload).hexdigest()
|
||||
downloaded: list[str] = []
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://updates.example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
)
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict:
|
||||
return {
|
||||
"version": "3.3.4",
|
||||
"url": "https://evil.example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": expected_sha,
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
downloaded.append(url)
|
||||
dest.write_bytes(payload)
|
||||
|
||||
with pytest.raises(UpdateError, match="同源"):
|
||||
perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=fetch_manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: None,
|
||||
)
|
||||
|
||||
assert downloaded == []
|
||||
|
||||
|
||||
def test_forced_update_ignores_manifest_force_false_for_newer_version(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _assert_bootstrap_before(path: str, *late_markers: str) -> None:
|
||||
text = Path(path).read_text(encoding="utf-8")
|
||||
import_marker = "from douyin.updater.bootstrap import run_startup_update_check_early"
|
||||
call_marker = "run_startup_update_check_early("
|
||||
assert import_marker in text
|
||||
assert call_marker in text
|
||||
call_index = text.index(call_marker)
|
||||
for marker in late_markers:
|
||||
assert marker in text
|
||||
assert call_index < text.index(marker)
|
||||
|
||||
|
||||
def test_run_cli_runs_update_bootstrap_before_heavy_imports():
|
||||
_assert_bootstrap_before(
|
||||
"bin/run_cli.py",
|
||||
"from douyin.core.douyin_fudai import fudai_analyse",
|
||||
"from douyin.license.license_manager import require_license_or_exit",
|
||||
)
|
||||
|
||||
|
||||
def test_gui_app_runs_update_bootstrap_before_gui_imports():
|
||||
_assert_bootstrap_before(
|
||||
"gui/gui_app.py",
|
||||
"from gui.gui_core import",
|
||||
"from douyin.license.license_manager import require_license_or_exit",
|
||||
)
|
||||
|
||||
|
||||
def test_web_gui_runs_update_bootstrap_before_gui_imports():
|
||||
_assert_bootstrap_before(
|
||||
"gui/web_gui.py",
|
||||
"from douyin.core import path_config",
|
||||
"from douyin.license.license_manager import require_license_or_exit",
|
||||
)
|
||||
Reference in new issue
Block a user