Peach: Local-first video metadata scraper and media manager.
fix(network): 收紧 Cloudflare Tunnel 的启停与来源判定
longmeidaoe543a4a51b4e
diff --git a/src/peach/api.py b/src/peach/api.pyindex 16a504b1f..4cd37379c 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -31,7 +31,7 @@ from fastapi.staticfiles import StaticFilesfrom starlette.exceptions import HTTPException as StarletteHTTPExceptionfrom starlette.middleware.gzip import DEFAULT_EXCLUDED_CONTENT_TYPES, GZipMiddleware-from . import __version__, settings_file, tunnel, web_contract, web_follow+from . import __version__, tunnel, web_contract, web_followfrom . import routes_api, routes_auth, routes_configuration, routes_media, routes_pagesfrom .buildinfo import frozen_buildfrom .config import PeachSettings@@ -106,24 +106,12 @@ def _resolve_tunnel_manager()-def _tunnel_plan(settings: PeachSettings) -> tunnel.TunnelPlan:- config = settings_file.load_config()- return tunnel.plan_for_config(- config,- access_path=settings.access_path,- token=settings.token,- standalone_mode=settings.tunnel_standalone,- lan_address=settings.tunnel_lan_address,- https_port=settings.tunnel_origin_port,- tls_enabled=settings.tls_enabled,- )--def _start_tunnel(settings: PeachSettings, manager: tunnel.TunnelManager) -> None:+ """公网入口只按本次启动注入的设置开;不回头读设置文件里的当前值。"""if not (settings.tunnel_enabled and settings.configured):returntry:- manager.start(_tunnel_plan(settings))+ manager.start(tunnel.plan_for_settings(settings))except tunnel.TunnelError:LOGGER.warning("Cloudflare Tunnel 未能启动", exc_info=True)@@ -238,7 +226,9 @@ def create_app(if recovered:logging.getLogger(__name__).info("task center recovered %s interrupted run(s)", len(recovered))- _start_tunnel(settings, tunnel_manager)+ # 启动握手要等 cloudflared 连上边缘,可以占到几十秒;和 mDNS 一样交给线程,+ # 不要在事件循环里卡住整条服务的启动。+ await asyncio.to_thread(_start_tunnel, settings, tunnel_manager)follow_scheduler.start()automatic_updates.start()warmup = asyncio.create_task(warm_startup_entries())@@ -259,7 +249,7 @@ def create_app(contract.stop_background_jobs()if mdns is not None:await asyncio.to_thread(mdns.stop)- tunnel_manager.stop()+ await asyncio.to_thread(tunnel_manager.stop)http_transport.close()hls_plan_executor.shutdown(wait=False, cancel_futures=True)diff --git a/src/peach/cli.py b/src/peach/cli.pyindex 5df3147cb..0e22495b0 100644--- a/src/peach/cli.py+++ b/src/peach/cli.py@@ -591,9 +591,11 @@ def _tunnel(args: argparse.Namespace) -> int:https_port=origin_port,)manager = tunnel.TunnelManager(state_dir, log_dir, wait_timeout=args.timeout)- snapshot = manager.start(plan)- print(f"临时链接:{snapshot.url}", flush=True)+ # 启动握手本身也要在 try 里:Ctrl-C 打在等待边缘连接的那几十秒上时,子进程已经+ # 起来了,只有走到 finally 才收得掉。try:+ snapshot = manager.start(plan)+ print(f"临时链接:{snapshot.url}", flush=True)while manager.snapshot().state == "running":time.sleep(1)except KeyboardInterrupt:diff --git a/src/peach/config.py b/src/peach/config.pyindex e4a4faa91..7f429eb85 100644--- a/src/peach/config.py+++ b/src/peach/config.py@@ -87,13 +87,16 @@ class PeachSettings:mdns_port: int = 80mdns_address: str | None = Nonetls_enabled: bool = False- #: Quick Tunnel 由应用进程管理;默认关闭,打开前由 tunnel 模块检查访问密码。- tunnel_enabled: bool = TUNNEL_ENABLED- tunnel_binary: str = CLOUDFLARED_BINARY+ #: Quick Tunnel 由应用进程管理,公网入口不能从默认值打开:这两项只由 `cli._serve`+ #: 从设置文件读出后注入,`create_app()` 自己构造的设置一律是关闭加空路径。+ tunnel_enabled: bool = False+ tunnel_binary: str = ""tunnel_standalone: bool = Falsetunnel_lan_address: str | None = None- #: Tunnel origin 的实际端口;None 表示独立包取设置文件端口,源码取 443。+ #: Tunnel origin 的实际端口;源码部署留 None 表示标准 HTTPS 端口。tunnel_origin_port: int | None = None+ #: 源码部署的 Tunnel origin 走本机 HTTPS,cloudflared 用这份项目 CA 校验它。+ tunnel_ca_path: Path = SECRETS_DIR / "tls" / "peach-local-ca.crt"tunnel_state_root: Path = STATE_DIRtunnel_log_root: Path = LOG_DIR#: 这台机器跑过 `peach init` 了没有。`/healthz` 与首页据此决定是否弹首次运行提示。diff --git a/src/peach/routes_auth.py b/src/peach/routes_auth.pyindex e568dcb19..c82883ef2 100644--- a/src/peach/routes_auth.py+++ b/src/peach/routes_auth.py@@ -15,7 +15,7 @@ from collections import OrderedDictimport threadingimport timefrom urllib.parse import urlsplit-from . import access+from . import access, tunnelfrom .web_entry import board_entry_stylefrom starlette.concurrency import run_in_threadpoolfrom urllib.parse import parse_qs@@ -28,9 +28,23 @@ _ATTEMPTS: OrderedDict[str, list[float]] = OrderedDict()_ATTEMPTS_LOCK = threading.Lock()+def _attempt_key(request: Request) -> str:+ """限速按真实来源分桶。++ 隧道在跑时所有请求的连接源都是 cloudflared 的回环地址,按它计数等于把整个公网+ 合成一个桶:外面一台机器试满十次,本机浏览器也跟着被锁一分钟。这时改用边缘给出+ 的客户端地址,隧道没在跑就仍按连接源,避免任何人自带一个头就换一个桶。+ """+ if tunnel.running(getattr(request.app.state, "tunnel", None)):+ forwarded = (request.headers.get("cf-connecting-ip") or "").strip()+ if forwarded:+ return f"cf:{forwarded}"+ return request.client.host if request.client else "unknown"++def _login_attempt(request: Request) -> None:"""按连接来源限制密码尝试,保留有界的短期计数。"""- peer = request.client.host if request.client else "unknown"+ peer = _attempt_key(request)now = time.monotonic()with _ATTEMPTS_LOCK:attempts = [stamp for stamp in _ATTEMPTS.pop(peer, []) if now - stamp < 60]diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.pyindex a4e45d6b1..f188b0af2 100644--- a/src/peach/routes_configuration.py+++ b/src/peach/routes_configuration.py@@ -50,9 +50,18 @@ def revision(config) -> str:return hashlib.sha256(config.path.read_bytes()).hexdigest()+def tunnel_forwarded(request: Request) -> bool:+ """隧道在跑时,带 Cloudflare 转发头的请求一律按公网来源处理。++ cloudflared 从本机回环连进来,源 IP 与本机浏览器完全一样;转发头是唯一能把+ 两者分开的证据,宁可把伪造了这些头的本机请求挡在配置页外面。+ """+ return tunnel.from_edge(getattr(request.app.state, "tunnel", None), request.headers)++def local_client(request: Request) -> bool:"""按连接两端的 IP 识别本机;Host 只用于校验允许的入口名称。"""- if not request.client:+ if not request.client or tunnel_forwarded(request):return Falseserver = request.scope.get("server")try:@@ -127,9 +136,7 @@ def read_configuration(request: Request, _args=Depends(require_auth)):"state": state.state,"url": state.url,"error": state.error,- "available": tunnel.resolve_binary(- config.tunnel.binary, base_dir=config.data_root,- ) is not None,+ "available": tunnel.resolve_binary(config.tunnel.binary) is not None,}result["automatic_updates"] = request.app.state.automatic_updates.snapshot()if result["automatic_updates"].get("result"):@@ -277,6 +284,34 @@ def _validate(body: dict[str, Any], config) -> tuple[dict[str, Any], dict[str, Areturn errors, validated+def _close_tunnel_without_password(request: Request) -> str:+ """没有访问密码就不能留着公网入口;这里当场停掉并把开关写回关闭。++ 启动前的检查挡不住这条路径:隧道是在有密码时起来的,密码被关掉之后它还在转发。+ """+ manager = getattr(request.app.state, "tunnel", None)+ if manager is None:+ return ""+ try:+ state = manager.snapshot().state+ except (AttributeError, OSError, ValueError):+ return ""+ if state not in {"starting", "running"}:+ return ""+ manager.stop()+ try:+ config = settings_file.load_config()+ if config.present and config.tunnel.enabled:+ with FileLock(str(config.path.with_suffix(".lock")), timeout=0):+ settings_file.write(+ replace(config, tunnel=replace(config.tunnel, enabled=False)),+ force=True,+ )+ except (Timeout, OSError, ValueError):+ return "临时远程链接已停止;设置文件未能写入,请在本机检查设置文件。"+ return "已停止临时远程链接:没有访问密码时不保留公网入口。"++@router.post("/api/configuration/access")def save_access(request: Request, body: dict[str, Any] = Body(default_factory=dict),_args=Depends(require_auth)):@@ -314,7 +349,12 @@ def save_access(request: Request, body: dict[str, Any] = Body(default_factory=diraise HTTPException(409, "访问设置正在保存,请稍后重试") from Noneexcept ValueError as exc:raise HTTPException(400, str(exc)) from exc- response = JSONResponse(access.public(policy), headers={"Cache-Control": "no-store"})+ payload = access.public(policy)+ if policy["mode"] != "password":+ notice = _close_tunnel_without_password(request)+ if notice:+ payload["tunnel_notice"] = notice+ response = JSONResponse(payload, headers={"Cache-Control": "no-store"})response.delete_cookie("tok", path="/")response.delete_cookie(access.COOKIE, path="/")if policy["mode"] == "password":diff --git a/src/peach/tunnel.py b/src/peach/tunnel.pyindex 05c06637f..2fc2b0773 100644--- a/src/peach/tunnel.py+++ b/src/peach/tunnel.py@@ -6,11 +6,13 @@ Quick Tunnel 的随机地址只写进数据根的状态文件,不进入设置"""from __future__ import annotations+import ctypesimport jsonimport ipaddressimport osimport reimport shutil+import signalimport subprocessimport sysimport tempfile@@ -28,9 +30,11 @@ STATE_FILENAME = "cloudflare-tunnel.json"LOG_FILENAME = "cloudflare-tunnel.log"PID_FILENAME = "cloudflared.pid"QUICK_URL_RE = re.compile(- r"https://[a-z0-9][a-z0-9-]*\.trycloudflare\.com(?:/[^\s]*)?",+ r"https://[a-z0-9][a-z0-9-]*\.trycloudflare\.com",re.IGNORECASE,)+#: cloudflared 转发时一定会带上的请求头;只要隧道在跑,带这些头的连接就来自公网。+EDGE_HEADERS = ("cf-connecting-ip", "cf-ray")class TunnelError(RuntimeError):@@ -77,12 +81,15 @@ def extract_quick_url(line: str) -> str | None:def resolve_binary(configured: str = "",*,- base_dir: Path | None = None,executable: Path | None = None,environ: dict[str, str] | None = None,which: Callable[[str], str | None] = shutil.which,) -> Path | None:- """按显式配置、打包旁路、环境变量和 PATH 的顺序找 cloudflared。"""+ """按显式配置、打包旁路、环境变量和 PATH 的顺序找 cloudflared。++ 数据根不在搜索范围里:它是用户放媒体和账本的地方,任何能往那里写文件的人都+ 不该因此获得一次本机可执行文件的启动机会。+ """environ = os.environ if environ is None else environcandidates: list[Path] = []@@ -100,9 +107,6 @@ def resolve_binary(package_dir / "_internal" / "cloudflared.exe",package_dir / "_internal" / "cloudflared",))- if base_dir is not None:- candidates.extend((Path(base_dir) / "cloudflared.exe", Path(base_dir) / "cloudflared"))-for candidate in candidates:try:if candidate.is_file():@@ -117,23 +121,22 @@ def resolve_binary(return None-def origin_for_config(- config, *, standalone_mode: bool, lan_address: str | None = None,- https_port: int | None = None,+def build_origin(+ *, standalone_mode: bool, port: int | None, mdns_name: str = "",+ lan_address: str | None = None, ca_path: Path | None = None,) -> TunnelOrigin:"""为源码托盘和独立包分别构造 origin。源码服务的 80 端口只是跳转口,不能拿来做 Tunnel origin;独立包则没有本机 TLS- 入口,使用回环 HTTP。Cloudflare edge 到浏览器仍然是 HTTPS。未显式传端口时,- 独立包取设置文件里的服务端口,源码取标准 HTTPS 端口。+ 入口,使用回环 HTTP。Cloudflare edge 到浏览器仍然是 HTTPS。源码未显式传端口时+ 取标准 HTTPS 端口。"""if standalone_mode:- port = config.server.port if https_port is None else https_portif type(port) is not int or not 1 <= port <= 65535:raise TunnelError(f"独立包 Tunnel 的 HTTP 端口无效:{port}")return TunnelOrigin(f"http://127.0.0.1:{port}")- if https_port is None:- https_port = 443+ if port is None:+ port = 443address = (lan_address or "").strip()if not address:raise TunnelError("无法确定源码服务的局域网地址")@@ -141,18 +144,31 @@ def origin_for_config(parsed_address = ipaddress.ip_address(address)except ValueError as exc:raise TunnelError(f"源码 Tunnel 的局域网地址不是 IP:{address}") from exc- hostname = config.server.mdns_name.strip().rstrip(".")+ hostname = (mdns_name or "").strip().rstrip(".")if not hostname:raise TunnelError("源码服务没有配置 mDNS 名称")origin_name = hostname if hostname.endswith(".local") else f"{hostname}.local"- ca = config.directory("secrets") / "tls" / "peach-local-ca.crt"- if not ca.is_file():- raise TunnelError(f"源码 Tunnel 需要项目 CA:{ca}")- if type(https_port) is not int or not 1 <= https_port <= 65535:- raise TunnelError(f"源码 Tunnel 的 HTTPS 端口无效:{https_port}")+ if ca_path is None or not Path(ca_path).is_file():+ raise TunnelError(f"源码 Tunnel 需要项目 CA:{ca_path}")+ if type(port) is not int or not 1 <= port <= 65535:+ raise TunnelError(f"源码 Tunnel 的 HTTPS 端口无效:{port}")host = f"[{address}]" if parsed_address.version == 6 else addressreturn TunnelOrigin(- f"https://{host}:{https_port}", origin_server_name=origin_name, ca_path=ca,+ f"https://{host}:{port}", origin_server_name=origin_name, ca_path=Path(ca_path),+ )+++def origin_for_config(+ config, *, standalone_mode: bool, lan_address: str | None = None,+ https_port: int | None = None,+) -> TunnelOrigin:+ """从设置文件取端口、mDNS 名和项目 CA,其余交给 `build_origin`。"""+ port = config.server.port if standalone_mode and https_port is None else https_port+ return build_origin(+ standalone_mode=standalone_mode, port=port,+ mdns_name=getattr(config.server, "mdns_name", ""),+ lan_address=lan_address,+ ca_path=config.directory("secrets") / "tls" / "peach-local-ca.crt",)@@ -207,24 +223,79 @@ def plan_for_config(if not standalone_mode and not tls_enabled:raise TunnelError("源码 Tunnel 需要正在运行的 HTTPS 服务")tunnel_settings = getattr(config, "tunnel", None)- binary = resolve_binary(+ binary = _require_binary(getattr(tunnel_settings, "binary", ""),- base_dir=Path(getattr(config, "data_root", ".")),- executable=executable,- environ=environ,- which=which,+ executable=executable, environ=environ, which=which,+ )+ origin = origin_for_config(+ config, standalone_mode=standalone_mode, lan_address=lan_address,+ https_port=https_port,+ )+ return TunnelPlan(binary=binary, origin=origin, command=build_command(binary, origin))+++def _require_binary(+ configured: str,+ *,+ executable: Path | None = None,+ environ: dict[str, str] | None = None,+ which: Callable[[str], str | None] = shutil.which,+) -> Path:+ binary = resolve_binary(+ configured, executable=executable, environ=environ, which=which,)if binary is None:raise TunnelError("找不到 cloudflared;请安装官方 cloudflared,或设置 PEACH_CLOUDFLARED")- origin = origin_for_config(- config, standalone_mode=standalone_mode, lan_address=lan_address,- https_port=https_port,+ return binary+++def plan_for_settings(+ settings,+ *,+ executable: Path | None = None,+ environ: dict[str, str] | None = None,+ which: Callable[[str], str | None] = shutil.which,+) -> TunnelPlan:+ """只用本次启动注入的运行设置构造计划。++ 服务进程不再回头读设置文件:公网入口的开关、端口和 origin 必须与这条服务实际+ 监听的形态一致,而设置文件可以在服务运行期间被改成别的样子。+ """+ validate_access(settings.access_path, settings.token)+ if not settings.tunnel_standalone and not settings.tls_enabled:+ raise TunnelError("源码 Tunnel 需要正在运行的 HTTPS 服务")+ binary = _require_binary(+ settings.tunnel_binary, executable=executable, environ=environ, which=which,+ )+ origin = build_origin(+ standalone_mode=settings.tunnel_standalone,+ port=settings.tunnel_origin_port,+ mdns_name=settings.mdns_name,+ lan_address=settings.tunnel_lan_address,+ ca_path=settings.tunnel_ca_path,)return TunnelPlan(binary=binary, origin=origin, command=build_command(binary, origin))+def running(manager) -> bool:+ """只有 manager 自己报告 running 才算公网入口在服务中。"""+ if manager is None:+ return False+ try:+ return manager.snapshot().state == "running"+ except (AttributeError, OSError, ValueError):+ return False+++def from_edge(manager, headers) -> bool:+ """隧道在跑时,带 Cloudflare 转发头的连接一律按公网来源处理。"""+ if not running(manager):+ return False+ return any(headers.get(name) for name in EDGE_HEADERS)++def _read_state(path: Path) -> TunnelSnapshot:try:data = json.loads(path.read_text(encoding="utf-8"))@@ -247,7 +318,9 @@ def saved_snapshot(state_dir: Path) -> TunnelSnapshot:"""读取状态文件;不把旧的 running 记录误报成当前进程仍在运行。"""saved = _read_state(state_path(state_dir))if saved.state in {"running", "starting"}:- return TunnelSnapshot(state="stopped", error="上一次 Tunnel 已随服务停止")+ return TunnelSnapshot(+ state="stopped", error="上一次 Tunnel 没有正常收尾,运行结果未取得",+ )return saved@@ -274,6 +347,190 @@ def _write_state(path: Path, snapshot: TunnelSnapshot) -> None:Path(temporary).unlink(missing_ok=True)+_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000+_PROCESS_TERMINATE = 0x0001+_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000+#: JobObjectExtendedLimitInformation+_JOB_EXTENDED_LIMIT_CLASS = 9+++def _windows_image_name(pid: int) -> str:+ from ctypes import wintypes++ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.OpenProcess.restype = wintypes.HANDLE+ kernel32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)+ kernel32.QueryFullProcessImageNameW.argtypes = (+ wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD),+ )+ handle = kernel32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)+ if not handle:+ return ""+ try:+ size = wintypes.DWORD(32768)+ buffer = ctypes.create_unicode_buffer(size.value)+ if not kernel32.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(size)):+ return ""+ return Path(buffer.value).name+ finally:+ kernel32.CloseHandle(handle)+++def _posix_image_name(pid: int) -> str:+ try:+ return Path(f"/proc/{pid}/comm").read_text(encoding="utf-8", errors="replace").strip()+ except OSError:+ pass+ try:+ result = subprocess.run(+ ["ps", "-p", str(pid), "-o", "comm="],+ capture_output=True, text=True, timeout=5, check=False,+ )+ except (OSError, subprocess.SubprocessError):+ return ""+ return Path(result.stdout.strip()).name if result.returncode == 0 else ""+++def process_image_name(pid: int) -> str:+ """取这个 pid 当前的可执行名;取不到就返回空串,调用方按未取得处理。"""+ if pid <= 0:+ return ""+ try:+ return _windows_image_name(pid) if os.name == "nt" else _posix_image_name(pid)+ except (OSError, ValueError, AttributeError):+ return ""+++def _terminate_windows_pid(pid: int) -> None:+ from ctypes import wintypes++ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.OpenProcess.restype = wintypes.HANDLE+ kernel32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)+ handle = kernel32.OpenProcess(_PROCESS_TERMINATE | 0x00100000, False, pid)+ if not handle:+ return+ try:+ kernel32.TerminateProcess(handle, 1)+ kernel32.WaitForSingleObject(handle, 5000)+ finally:+ kernel32.CloseHandle(handle)+++def _terminate_posix_pid(pid: int) -> None:+ try:+ os.kill(pid, signal.SIGTERM)+ except OSError:+ return+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ try:+ os.kill(pid, 0)+ except OSError:+ return+ time.sleep(0.1)+ try:+ os.kill(pid, signal.SIGKILL)+ except OSError:+ pass+++def terminate_pid(pid: int) -> None:+ """终止一个不是本进程子进程的 pid;调用方负责先确认它就是 cloudflared。"""+ if pid <= 0:+ return+ try:+ if os.name == "nt":+ _terminate_windows_pid(pid)+ else:+ _terminate_posix_pid(pid)+ except (OSError, ValueError, AttributeError):+ pass+++def _create_kill_on_close_job():+ """建一个随句柄关闭一并终止成员的 Job Object;非 Windows 返回 None。++ 服务进程被强杀时不会走 `stop()`,只有内核托管的 Job 能保证 cloudflared 不会+ 独自留在公网上继续转发。+ """+ if os.name != "nt":+ return None+ from ctypes import wintypes++ class _IoCounters(ctypes.Structure):+ _fields_ = [(name, ctypes.c_ulonglong) for name in (+ "ReadOperationCount", "WriteOperationCount", "OtherOperationCount",+ "ReadTransferCount", "WriteTransferCount", "OtherTransferCount",+ )]++ class _BasicLimits(ctypes.Structure):+ _fields_ = [+ ("PerProcessUserTimeLimit", ctypes.c_longlong),+ ("PerJobUserTimeLimit", ctypes.c_longlong),+ ("LimitFlags", wintypes.DWORD),+ ("MinimumWorkingSetSize", ctypes.c_size_t),+ ("MaximumWorkingSetSize", ctypes.c_size_t),+ ("ActiveProcessLimit", wintypes.DWORD),+ ("Affinity", ctypes.c_size_t),+ ("PriorityClass", wintypes.DWORD),+ ("SchedulingClass", wintypes.DWORD),+ ]++ class _ExtendedLimits(ctypes.Structure):+ _fields_ = [+ ("BasicLimitInformation", _BasicLimits),+ ("IoInfo", _IoCounters),+ ("ProcessMemoryLimit", ctypes.c_size_t),+ ("JobMemoryLimit", ctypes.c_size_t),+ ("PeakProcessMemoryUsed", ctypes.c_size_t),+ ("PeakJobMemoryUsed", ctypes.c_size_t),+ ]++ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.CreateJobObjectW.restype = wintypes.HANDLE+ kernel32.CreateJobObjectW.argtypes = (wintypes.LPVOID, wintypes.LPCWSTR)+ job = kernel32.CreateJobObjectW(None, None)+ if not job:+ return None+ limits = _ExtendedLimits()+ limits.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE+ if not kernel32.SetInformationJobObject(+ wintypes.HANDLE(job), _JOB_EXTENDED_LIMIT_CLASS,+ ctypes.byref(limits), ctypes.sizeof(limits),+ ):+ kernel32.CloseHandle(wintypes.HANDLE(job))+ return None+ return job+++def _assign_to_job(job, process) -> None:+ if job is None or os.name != "nt":+ return+ handle = getattr(process, "_handle", None)+ if handle is None:+ return+ from ctypes import wintypes++ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ try:+ kernel32.AssignProcessToJobObject(wintypes.HANDLE(job), wintypes.HANDLE(int(handle)))+ except (OSError, ValueError, TypeError):+ # 内核拒绝嵌套 Job 时仍然启动:stop() 与 pidfile 回收仍会收掉这个子进程。+ pass+++def _close_job(job) -> None:+ if job is None or os.name != "nt":+ return+ from ctypes import wintypes++ try:+ ctypes.WinDLL("kernel32", use_last_error=True).CloseHandle(wintypes.HANDLE(job))+ except (OSError, ValueError):+ pass++class TunnelManager:"""一个 Peach 服务进程拥有的一条 cloudflared 子进程。"""@@ -285,10 +542,13 @@ class TunnelManager:popen: Callable[..., subprocess.Popen] = subprocess.Popen,wait_timeout: float = 30.0,clock: Callable[[], float] = time.monotonic,+ image_name: Callable[[int], str] = process_image_name,) -> None:self.state_dir = Path(state_dir)self.log_dir = Path(log_dir)self._popen = popen+ self._image_name = image_name+ self._job = Noneself._wait_timeout = wait_timeoutself._clock = clockself._lock = threading.RLock()@@ -361,6 +621,24 @@ class TunnelManager:except (AttributeError, OSError, subprocess.TimeoutExpired):pass+ def reclaim_orphan(self) -> int | None:+ """收掉上一次服务留下的 cloudflared,并返回被收掉的 pid。++ 判据是 pidfile 里的进程此刻还在、且可执行名就是 cloudflared;名字取不到或+ 对不上就原样留着,绝不按 pid 猜身份去杀一个别人的进程。+ """+ try:+ pid = int(self.pid_file.read_text(encoding="ascii").strip())+ except (OSError, ValueError):+ return None+ if pid <= 0 or pid == os.getpid():+ return None+ name = self._image_name(pid)+ if "cloudflared" not in name.lower():+ return None+ terminate_pid(pid)+ return pid+def _write_error(self, message: str) -> None:self._error = messagetry:@@ -444,7 +722,10 @@ class TunnelManager:self._ready.clear()self.state_dir.mkdir(parents=True, exist_ok=True)self.log_dir.mkdir(parents=True, exist_ok=True)+ self.reclaim_orphan()self.pid_file.unlink(missing_ok=True)+ if self._job is None:+ self._job = _create_kill_on_close_job()handle: TextIO | None = Noneprocess: subprocess.Popen | None = Nonetry:@@ -473,6 +754,7 @@ class TunnelManager:self._ready.set()self._write_error(message)raise TunnelError(message) from exc+ _assign_to_job(self._job, process)self._process = processstream = process.stdoutif stream is None:@@ -555,14 +837,17 @@ class TunnelManager:with self._lock:process = self._processreader = self._reader+ job = self._jobself._process = Noneself._reader = None+ self._job = Noneself._generation += 1cleanup_generation = self._generationself._url = ""self._error = ""self._ready.set()self._terminate_process(process)+ _close_job(job)if reader is not None and reader.is_alive():reader.join(timeout=1)snapshot = TunnelSnapshot(state="stopped")diff --git a/tests/test_tunnel.py b/tests/test_tunnel.pyindex 975f25088..fcd394437 100644--- a/tests/test_tunnel.py+++ b/tests/test_tunnel.py@@ -1,14 +1,32 @@import json+import os+import subprocess+import sysimport tempfile-import timeimport unittestfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest import mockfrom fastapi import HTTPException+from fastapi.testclient import TestClient++from peach import access, api, routes_auth, routes_configuration, tunnel+from peach.config import PeachSettings-from peach import access, routes_auth, routes_configuration, tunnel+#: 假扮 cloudflared 的真实子进程:写 pidfile、按行吐出一条入口,然后等着被收掉。+FAKE_CLOUDFLARED = '''\+import os+import sys+import time++arguments = sys.argv[1:]+with open(arguments[arguments.index("--pidfile") + 1], "w", encoding="ascii") as handle:+ handle.write(str(os.getpid()))+print("INF | Your quick Tunnel has been created! https://real-child.trycloudflare.com", flush=True)+while True:+ time.sleep(0.2)+'''class _Config:@@ -61,6 +79,18 @@ class _Process:return self._returncode+class _StubbornProcess(_Process):+ """收到 terminate 之后继续活着,逼出 kill 那一步。"""++ def terminate(self):+ self.terminated = True++ def wait(self, timeout=None):+ if self._returncode is None:+ raise subprocess.TimeoutExpired("cloudflared", timeout)+ return self._returncode++class TunnelPlanTests(unittest.TestCase):def setUp(self):self.temp = tempfile.TemporaryDirectory()@@ -161,6 +191,41 @@ class TunnelPlanTests(unittest.TestCase):standalone_mode=True, environ={}, which=lambda _name: None,)+ def test_a_binary_dropped_into_the_data_root_is_not_picked_up(self):+ self.config.tunnel.binary = ""+ with self.assertRaisesRegex(tunnel.TunnelError, "找不到 cloudflared"):+ tunnel.plan_for_config(+ self.config, access_path=self.access_path, token="internal-token",+ standalone_mode=True, environ={}, which=lambda _name: None,+ )++ def test_a_plan_built_from_injected_settings_never_reads_the_settings_file(self):+ settings = SimpleNamespace(+ access_path=self.access_path, token="internal-token",+ tunnel_standalone=True, tunnel_binary=str(self.binary),+ tunnel_origin_port=18902, tunnel_lan_address=None,+ tunnel_ca_path=self.root / "missing-ca.crt", tls_enabled=False,+ mdns_name="peach",+ )+ with mock.patch.object(+ tunnel, "validate_access", wraps=tunnel.validate_access,+ ) as validated:+ plan = tunnel.plan_for_settings(settings, environ={})+ self.assertEqual(plan.origin.url, "http://127.0.0.1:18902")+ self.assertEqual(plan.binary, self.binary)+ validated.assert_called_once_with(self.access_path, "internal-token")++ def test_source_settings_without_tls_are_rejected(self):+ settings = SimpleNamespace(+ access_path=self.access_path, token="internal-token",+ tunnel_standalone=False, tunnel_binary=str(self.binary),+ tunnel_origin_port=443, tunnel_lan_address="192.0.2.162",+ tunnel_ca_path=self.root / "ca.crt", tls_enabled=False,+ mdns_name="peach",+ )+ with self.assertRaisesRegex(tunnel.TunnelError, "需要正在运行的 HTTPS"):+ tunnel.plan_for_settings(settings, environ={})+class TunnelManagerTests(unittest.TestCase):def setUp(self):@@ -251,6 +316,26 @@ class TunnelManagerTests(unittest.TestCase):self.assertTrue(self.processes[0].terminated)self.assertFalse((self.root / "state" / tunnel.PID_FILENAME).exists())+ def test_a_child_that_ignores_terminate_is_killed(self):+ manager = tunnel.TunnelManager(+ self.root / "state", self.root / "logs", popen=self.popen, wait_timeout=2,+ )++ def stubborn_popen(command, **kwargs):+ pid_index = command.index("--pidfile") + 1+ Path(command[pid_index]).write_text("4123\n", encoding="ascii")+ process = _StubbornProcess(_Stream(+ "INF | Your quick Tunnel has been created! https://unit-7.trycloudflare.com\n",+ ))+ self.processes.append(process)+ return process++ manager._popen = stubborn_popen+ manager.start(self.plan())+ manager.stop()+ self.assertTrue(self.processes[0].terminated)+ self.assertTrue(self.processes[0].killed)+def test_snapshot_accepts_a_process_without_a_pid_attribute(self):process = SimpleNamespace(poll=lambda: None, stdout=_Stream())manager = tunnel.TunnelManager(self.root / "state", self.root / "logs")@@ -380,5 +465,271 @@ class TunnelRouteTests(unittest.TestCase):manager.stop.assert_not_called()+def direct_interpreter() -> str:+ """找一个自己就是最终进程的解释器。++ venv 的 `python.exe` 在 Windows 上是启动器,真解释器是它的子进程,pid 与+ `Popen.pid` 对不上;假 cloudflared 写出来的 pidfile 于是永远匹配不了。+ """+ for candidate in (getattr(sys, "_base_executable", "") or "", sys.executable):+ if not candidate:+ continue+ try:+ child = subprocess.Popen(+ [candidate, "-c", "import os; print(os.getpid())"],+ stdout=subprocess.PIPE, text=True,+ )+ printed, _ = child.communicate(timeout=60)+ except (OSError, ValueError, subprocess.SubprocessError):+ continue+ if printed.strip() == str(child.pid):+ return candidate+ return ""+++class TunnelChildProcessTests(unittest.TestCase):+ """用真实子进程覆盖行缓冲读取、收尾与遗留进程回收。"""++ @classmethod+ def setUpClass(cls):+ cls.python = direct_interpreter()++ def setUp(self):+ if not self.python:+ self.skipTest("本机解释器都带启动器跳板,pid 与子进程对不上")+ self.temp = tempfile.TemporaryDirectory()+ self.root = Path(self.temp.name).resolve()+ self.script = self.root / "fake_cloudflared.py"+ self.script.write_text(FAKE_CLOUDFLARED, encoding="utf-8")+ self.children = []++ def tearDown(self):+ for child in self.children:+ if child.poll() is None:+ child.kill()+ child.wait(timeout=30)+ self.temp.cleanup()++ def spawn(self, command, **kwargs):+ child = subprocess.Popen(+ [self.python, "-X", "utf8", str(self.script), *command[1:]], **kwargs,+ )+ self.children.append(child)+ return child++ def background_child(self, pid_file: Path):+ child = subprocess.Popen(+ [self.python, "-X", "utf8", str(self.script), "--pidfile", str(pid_file)],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ )+ self.children.append(child)+ return child++ def plan(self):+ return tunnel.TunnelPlan(+ binary=self.root / "cloudflared.exe",+ origin=tunnel.TunnelOrigin("http://127.0.0.1:8900"),+ command=("cloudflared", "tunnel", "--url", "http://127.0.0.1:8900"),+ )++ def test_a_real_child_publishes_its_url_and_leaves_nothing_behind(self):+ manager = tunnel.TunnelManager(+ self.root / "state", self.root / "logs", popen=self.spawn, wait_timeout=60,+ )+ started = manager.start(self.plan())+ self.assertEqual(started.state, "running")+ self.assertEqual(started.url, "https://real-child.trycloudflare.com")+ child = self.children[0]+ self.assertIsNone(child.poll())+ manager.stop()+ child.wait(timeout=30)+ self.assertIsNotNone(child.returncode)+ self.assertFalse((self.root / "state" / tunnel.PID_FILENAME).exists())+ self.assertFalse((self.root / "state" / tunnel.STATE_FILENAME).exists())++ def test_a_live_cloudflared_from_the_last_run_is_reclaimed(self):+ state_dir = self.root / "state"+ state_dir.mkdir()+ child = self.background_child(state_dir / "child.pid")+ (state_dir / tunnel.PID_FILENAME).write_text(str(child.pid), encoding="ascii")+ manager = tunnel.TunnelManager(+ state_dir, self.root / "logs", image_name=lambda _pid: "cloudflared.exe",+ )+ self.assertEqual(manager.reclaim_orphan(), child.pid)+ child.wait(timeout=30)+ self.assertIsNotNone(child.returncode)++ def test_a_pid_that_is_no_longer_cloudflared_is_left_alone(self):+ state_dir = self.root / "state"+ state_dir.mkdir()+ child = self.background_child(state_dir / "child.pid")+ (state_dir / tunnel.PID_FILENAME).write_text(str(child.pid), encoding="ascii")+ manager = tunnel.TunnelManager(+ state_dir, self.root / "logs", image_name=lambda _pid: "postgres.exe",+ )+ self.assertIsNone(manager.reclaim_orphan())+ self.assertIsNone(child.poll())++ def test_the_image_name_of_a_live_process_is_readable(self):+ self.assertIn("python", tunnel.process_image_name(os.getpid()).lower())+++class TunnelStartupTests(unittest.TestCase):+ """服务自己不会因为设置文件里写着 enabled 就打开公网入口。"""++ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.root = Path(self.temp.name).resolve()++ def tearDown(self):+ self.temp.cleanup()++ def test_default_settings_keep_the_tunnel_closed(self):+ settings = PeachSettings()+ self.assertFalse(settings.tunnel_enabled)+ self.assertEqual(settings.tunnel_binary, "")++ def test_start_tunnel_does_nothing_when_disabled(self):+ manager = mock.Mock()+ api._start_tunnel(PeachSettings(configured=True), manager)+ manager.start.assert_not_called()++ def test_create_app_does_not_start_a_tunnel_by_default(self):+ manager = mock.Mock()+ manager.snapshot.return_value = tunnel.TunnelSnapshot()+ settings = PeachSettings(+ db_path=self.root / "peach.db", configured=True, token="",+ tunnel_state_root=self.root / "state", tunnel_log_root=self.root / "logs",+ )+ with TestClient(api.create_app(settings, tunnel_manager=manager)) as client:+ client.get("/healthz")+ manager.start.assert_not_called()+++class LocalClientTests(unittest.TestCase):+ """隧道转发进来的请求不算本机,配置页对它一律关门。"""++ def request(self, state: str, headers: dict[str, str]):+ manager = SimpleNamespace(snapshot=lambda: tunnel.TunnelSnapshot(+ state=state, url="https://unit-7.trycloudflare.com",+ ))+ return SimpleNamespace(+ app=SimpleNamespace(state=SimpleNamespace(+ tunnel=manager, settings=SimpleNamespace(mdns_name="peach", configured=True),+ )),+ client=SimpleNamespace(host="127.0.0.1"),+ scope={"server": ("127.0.0.1", 8900)},+ url=SimpleNamespace(hostname="127.0.0.1"),+ headers=headers,+ )++ def test_a_loopback_request_without_edge_headers_is_local(self):+ self.assertTrue(routes_configuration.local_client(self.request("running", {})))++ def test_cf_ray_during_a_running_tunnel_is_not_local(self):+ request = self.request("running", {"cf-ray": "7a0-LAX"})+ self.assertFalse(routes_configuration.local_client(request))++ def test_cf_connecting_ip_during_a_running_tunnel_is_not_local(self):+ request = self.request("running", {"cf-connecting-ip": "198.51.100.7"})+ self.assertFalse(routes_configuration.local_client(request))++ def test_edge_headers_alone_do_not_lock_out_a_stopped_tunnel(self):+ request = self.request("stopped", {"cf-connecting-ip": "198.51.100.7"})+ self.assertTrue(routes_configuration.local_client(request))++ def test_the_debug_serve_branch_also_refuses_forwarded_requests(self):+ request = self.request("running", {"cf-ray": "7a0-LAX"})+ with mock.patch.dict("os.environ", {"PEACH_DEV": "1"}):+ self.assertFalse(routes_configuration.configurable(request))++ def test_the_login_rate_limit_separates_edge_clients(self):+ request = self.request("running", {"cf-connecting-ip": "198.51.100.7"})+ self.assertEqual(routes_auth._attempt_key(request), "cf:198.51.100.7")++ def test_the_login_rate_limit_uses_the_peer_without_a_tunnel(self):+ request = self.request("stopped", {"cf-connecting-ip": "198.51.100.7"})+ self.assertEqual(routes_auth._attempt_key(request), "127.0.0.1")+++class AccessTunnelInterlockTests(unittest.TestCase):+ """关掉访问密码就没有第二道闸门,公网入口必须当场收掉。"""++ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.root = Path(self.temp.name).resolve()+ self.access_path = self.root / "secrets" / "access.json"+ access.save(self.access_path, "a-strong-test-password")+ self.config_path = self.root / "config.toml"+ self.config_path.write_text("[tunnel]\nenabled = true\n", encoding="utf-8")+ self.config = SimpleNamespace(+ present=True, path=self.config_path, data_root=self.root,+ tunnel=SimpleNamespace(enabled=True, binary=""),+ )++ def tearDown(self):+ self.temp.cleanup()++ def request(self, manager):+ settings = SimpleNamespace(+ access_path=self.access_path, configured=True, mdns_name="peach",+ token="internal-token",+ )+ return SimpleNamespace(+ app=SimpleNamespace(state=SimpleNamespace(tunnel=manager, settings=settings)),+ client=SimpleNamespace(host="127.0.0.1"),+ scope={"server": ("127.0.0.1", 8900)},+ url=SimpleNamespace(hostname="127.0.0.1"),+ headers={"origin": "http://127.0.0.1:8900"},+ base_url="http://127.0.0.1:8900/",+ )++ def manager(self, state: str):+ manager = mock.Mock()+ manager.snapshot.return_value = tunnel.TunnelSnapshot(+ state=state, url="https://unit-7.trycloudflare.com",+ )+ manager.stop.return_value = tunnel.TunnelSnapshot(state="stopped")+ return manager++ def disable_body(self):+ policy = access.load(self.access_path)+ return {+ "action": "disable", "confirm_disable": True, "revision": policy["revision"],+ "current_password": "a-strong-test-password", "password": "", "confirmation": "",+ }++ def save(self, manager):+ def fake_replace(target, **changes):+ return SimpleNamespace(**{**vars(target), **changes})++ with mock.patch.object(+ routes_configuration.settings_file, "load_config", return_value=self.config,+ ), mock.patch.object(+ routes_configuration.settings_file, "write",+ ) as write, mock.patch.object(+ routes_configuration, "replace", side_effect=fake_replace,+ ), mock.patch.object(routes_configuration, "FileLock") as lock:+ lock.return_value.__enter__.return_value = lock.return_value+ response = routes_configuration.save_access(+ self.request(manager), self.disable_body(), None,+ )+ return response, write++ def test_disabling_the_password_stops_the_tunnel_and_writes_the_switch_back(self):+ manager = self.manager("running")+ response, write = self.save(manager)+ manager.stop.assert_called_once_with()+ self.assertFalse(write.call_args.args[0].tunnel.enabled)+ self.assertIn("临时远程链接", json.loads(response.body)["tunnel_notice"])++ def test_disabling_the_password_without_a_tunnel_changes_nothing(self):+ manager = self.manager("stopped")+ response, write = self.save(manager)+ manager.stop.assert_not_called()+ write.assert_not_called()+ self.assertNotIn("tunnel_notice", json.loads(response.body))++if __name__ == "__main__":unittest.main()