Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(tunnel): 加入源码环境的 Cloudflare 命名隧道模式

longmeidao6addbd403d36
diff --git a/frontend/src/react/bundle.d.ts b/frontend/src/react/bundle.d.ts
index c39c4e0a0..2e05687c3 100644
--- a/frontend/src/react/bundle.d.ts
+++ b/frontend/src/react/bundle.d.ts
@@ -13,6 +13,13 @@ export interface TunnelState {
url: string;
error: string;
available: boolean;
+ mode: 'quick' | 'named';
+ /** 命名隧道绑定的公开主机名,临时链接模式下为空。 */
+ hostname: string;
+ /** 隧道令牌存没存过。令牌本身不回传,页面只据此显示已保存。 */
+ token_set: boolean;
+ /** 这台部署能不能用命名隧道;独立包为 false,那一块整个不渲染。 */
+ named_available: boolean;
}
export interface AccessSettingsProps {
diff --git a/frontend/src/react/settings/tunnel-settings.tsx b/frontend/src/react/settings/tunnel-settings.tsx
index f7e333c18..4558358dc 100644
--- a/frontend/src/react/settings/tunnel-settings.tsx
+++ b/frontend/src/react/settings/tunnel-settings.tsx
@@ -1,14 +1,19 @@
-/* Cloudflare Quick Tunnel:只显示本机托盘服务实际返回的随机入口。
- * Quick Tunnel 没有稳定域名和独立身份层,服务端会在 `open` 模式下拒绝启动;
- * 这里不保存 URL 或任何密码,刷新配置页重新读取服务状态。 */
+/* Cloudflare Tunnel:临时链接显示服务实际返回的随机入口,命名隧道显示配置好的公开主机名。
+ *
+ * 临时链接没有稳定域名和独立身份层,服务端会在 `open` 模式下拒绝启动。命名隧道多一份
+ * 隧道令牌:它只往服务端去,回来的只有「存过没有」,这里任何时候都不显示令牌本身。
+ * 模式选择只在源码开发环境出现,独立包收到的 `named_available` 是 false。 */
import { useEffect, useState, type FormEvent } from 'react';
+import { Radio, RadioGroup } from 'react-aria-components';
import { Button } from '@/components/base/buttons/button';
+import { Input } from '@/components/base/input/input';
-import { apiSend } from '../../api';
+import { ApiError, apiSend, errorMessage } from '../../api';
import type { ConfigurationData, TunnelState } from '../bundle';
import { Note } from '../components/note';
import { queryClient } from '../query';
+import { SEGMENT, SEGMENTED_TRACK } from '../components/segmented';
import { CONFIGURATION_KEY, fetchConfiguration } from './configuration';
import { ExternalLink, ErrorText, Footer, Help, Section, Stack } from './section';
import { busyProps, useAction } from './use-action';
@@ -16,6 +21,16 @@ import { busyProps, useAction } from './use-action';
/** 连接握手在服务端进行,页面按固定间隔重问,直到拿到入口或失败原因。 */
const POLL_INTERVAL = 2000;
+const MODES: [TunnelState['mode'], string][] = [['quick', '临时链接'], ['named', '命名隧道']];
+
+const HELP: Record<TunnelState['mode'], string> = {
+ quick: '只用于临时预览;地址随机、重启后会变化。启动前必须设置访问密码。',
+ named: '地址是你在 Cloudflare 后台绑定的公开主机名,重启后不变。启动前必须设置访问密码,'
+ + '身份策略在 Cloudflare Access 里配置。',
+};
+
+type FieldErrors = Partial<Record<'hostname' | 'mode', string>>;
+
export function TunnelSettings({ revision: initialRevision, initial, receipt }: {
revision: string;
initial: TunnelState;
@@ -23,8 +38,13 @@ export function TunnelSettings({ revision: initialRevision, initial, receipt }:
}) {
const [state, setState] = useState(initial);
const [revision, setRevision] = useState(initialRevision);
+ const [mode, setMode] = useState<TunnelState['mode']>(initial.mode);
+ const [hostname, setHostname] = useState(initial.hostname);
+ const [token, setToken] = useState('');
+ const [fields, setFields] = useState<FieldErrors>({});
const action = useAction();
const active = state.state === 'starting' || state.state === 'running';
+ const named = state.named_available && mode === 'named';
useEffect(() => {
if (state.state !== 'starting') return undefined;
@@ -46,35 +66,77 @@ export function TunnelSettings({ revision: initialRevision, initial, receipt }:
};
}, [state.state]);
- const submit = (event: FormEvent<HTMLFormElement>) => {
- event.preventDefault();
- void action.run('toggle', (signal) => apiSend<TunnelState & { revision: string }>(
+ /** 开关和保存走同一个端点:形态与开关状态一次提交,服务端据此构造启动计划。 */
+ const send = (key: 'save' | 'toggle', enabled: boolean, done: (next: TunnelState) => void) => {
+ setFields({});
+ void action.run(key, (signal) => apiSend<TunnelState & { revision: string }>(
'/api/configuration/tunnel',
- { revision, enabled: !active }, 'POST', signal,
+ { revision, enabled, mode, hostname, token }, 'POST', signal,
), (next) => {
setState(next);
setRevision(next.revision);
- receipt(next.enabled ? '临时远程链接已启动' : '临时远程链接已停止');
+ setMode(next.mode);
+ setHostname(next.hostname);
+ // 令牌交上去之后草稿就清掉:页面上不留一份明文,回来的也只有「存过没有」。
+ setToken('');
+ done(next);
+ }, (cause) => {
+ const payload = cause instanceof ApiError
+ ? cause.body as { errors?: FieldErrors; detail?: { errors?: FieldErrors } } : null;
+ const errors = payload?.errors || payload?.detail?.errors;
+ if (errors) setFields(errors); else action.setError(errorMessage(cause));
});
};
+ const submit = (event: FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ send('save', active, () => receipt('已保存配置'));
+ };
+
+ const toggle = () => send('toggle', !active, (next) => receipt(
+ next.enabled ? '公网入口已启动' : '公网入口已停止',
+ ));
+
return (
- <Section title="Cloudflare 临时链接" onSubmit={submit}>
+ <Section title="Cloudflare 公网入口" onSubmit={submit}>
<Stack>
- <Help>只用于临时预览;地址随机、重启后会变化。启动前必须设置访问密码。</Help>
+ {state.named_available
+ ? <RadioGroup aria-label="公网入口的形态(二选一)" value={mode} isDisabled={active}
+ onChange={(next) => setMode(next as TunnelState['mode'])} className={SEGMENTED_TRACK}>
+ {MODES.map(([value, label]) => (
+ <Radio key={value} value={value} className={SEGMENT}>{label}</Radio>
+ ))}
+ </RadioGroup>
+ : null}
+ <Help>{HELP[named ? 'named' : 'quick']}</Help>
+ {named ? <>
+ <Input id="tunnel-hostname" label="公开主机名" autoComplete="off" maxLength={253}
+ value={hostname} onChange={setHostname} isDisabled={active} validationBehavior="aria"
+ isInvalid={Boolean(fields.hostname)}
+ hint={fields.hostname || '在 Cloudflare Zero Trust 里指向本机 origin 的那个主机名。'} />
+ <Input id="tunnel-token" type="password" label="隧道令牌" autoComplete="off" maxLength={2048}
+ value={token} onChange={setToken} isDisabled={active} validationBehavior="aria"
+ hint={state.token_set
+ ? '已保存。留空表示沿用已保存的令牌。'
+ : '在 Cloudflare Zero Trust 的隧道详情页复制。'} />
+ </> : null}
{!state.available
? <Note tone="warning" title="找不到 cloudflared">请安装官方 cloudflared,或在设置文件的 tunnel.binary 指定路径,也可用 PEACH_CLOUDFLARED 指定。</Note>
: null}
{state.state === 'running' && state.url
- ? <Note tone="info" title="临时链接"><ExternalLink href={state.url}>{state.url}</ExternalLink></Note>
+ ? <Note tone="info" title="公网地址"><ExternalLink href={state.url}>{state.url}</ExternalLink></Note>
: null}
- {state.state === 'starting' ? <Note tone="info" title="正在连接">正在等待 Cloudflare 返回入口地址。</Note> : null}
+ {state.state === 'starting' ? <Note tone="info" title="正在连接">正在等待 cloudflared 连上 Cloudflare 边缘。</Note> : null}
{state.error ? <ErrorText>{state.error}</ErrorText> : null}
+ {action.error ? <ErrorText>{action.error}</ErrorText> : null}
</Stack>
<Footer status={state.enabled ? '服务重启时会按设置尝试恢复。' : '默认关闭,不会自动暴露本机服务。'}>
- <Button type="submit" {...busyProps(action.busy === 'toggle')}>
- {active ? '停止临时链接' : '启动临时链接'}
+ <Button onClick={toggle} {...busyProps(action.busy === 'toggle')}>
+ {active ? '停止公网入口' : '启动公网入口'}
</Button>
+ {state.named_available
+ ? <Button type="submit" {...busyProps(action.busy === 'save')}>保存配置</Button>
+ : null}
</Footer>
</Section>
);
diff --git a/frontend/test/react/tunnel-settings.test.tsx b/frontend/test/react/tunnel-settings.test.tsx
new file mode 100644
index 000000000..6e74e35d6
--- /dev/null
+++ b/frontend/test/react/tunnel-settings.test.tsx
@@ -0,0 +1,115 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, expect, it, vi } from 'vitest';
+
+import type { TunnelState } from '../../src/react/bundle';
+import { TunnelSettings } from '../../src/react/settings/tunnel-settings';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+/** 夹具里的令牌是假值;真实令牌不进仓库,页面上也不会出现任何一份。 */
+const FAKE_TOKEN = 'fake-tunnel-token-for-tests';
+
+const STOPPED: TunnelState = {
+ enabled: false, state: 'stopped', url: '', error: '', available: true,
+ mode: 'quick', hostname: '', token_set: false, named_available: true,
+};
+
+const roots: Root[] = [];
+afterEach(() => {
+ for (const root of roots.splice(0)) act(() => root.unmount());
+ document.body.innerHTML = '';
+ vi.unstubAllGlobals();
+});
+
+async function mount(initial: TunnelState, receipt = vi.fn()) {
+ const host = document.createElement('div');
+ host.className = 'peach-react';
+ document.body.append(host);
+ const root = createRoot(host);
+ roots.push(root);
+ await act(async () => root.render(
+ <TunnelSettings revision="rev" initial={initial} receipt={receipt} />,
+ ));
+ return host;
+}
+
+async function type(input: HTMLInputElement, value: string) {
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+const click = (el: HTMLElement) => act(async () => el.click());
+const submit = (host: HTMLElement) => act(async () => {
+ host.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+});
+const sentBody = (fetcher: ReturnType<typeof vi.fn>) =>
+ JSON.parse((fetcher.mock.calls[0] as unknown as [string, RequestInit])[1].body as string);
+const radio = (host: HTMLElement, value: string) =>
+ host.querySelector<HTMLInputElement>(`input[type="radio"][value="${value}"]`)!;
+
+it('切到命名隧道才出现主机名与令牌,保存键是主按钮', async () => {
+ const saved = {
+ ...STOPPED, mode: 'named', hostname: 'peach.example.com',
+ token_set: true, revision: 'next',
+ };
+ const fetcher = vi.fn(async () => ({ ok: true, json: async () => saved }));
+ vi.stubGlobal('fetch', fetcher);
+ const receipt = vi.fn();
+ const host = await mount(STOPPED, receipt);
+ expect(host.querySelector('#tunnel-hostname')).toBeNull();
+ expect(host.querySelector('#tunnel-token')).toBeNull();
+
+ await click(radio(host, 'named'));
+ const hostname = host.querySelector<HTMLInputElement>('#tunnel-hostname')!;
+ const token = host.querySelector<HTMLInputElement>('#tunnel-token')!;
+ expect(token.type).toBe('password');
+ await type(hostname, 'peach.example.com');
+ await type(token, FAKE_TOKEN);
+ expect(host.querySelector('button[type="submit"]')?.textContent).toBe('保存配置');
+
+ await submit(host);
+ expect(sentBody(fetcher)).toMatchObject({
+ enabled: false, mode: 'named', hostname: 'peach.example.com', token: FAKE_TOKEN,
+ });
+ expect(receipt).toHaveBeenCalledWith('已保存配置');
+});
+
+it('保存后令牌不回显,只说已保存', async () => {
+ const saved = {
+ ...STOPPED, mode: 'named', hostname: 'peach.example.com',
+ token_set: true, revision: 'next',
+ };
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => saved })));
+ const host = await mount(STOPPED);
+ await click(radio(host, 'named'));
+ await type(host.querySelector<HTMLInputElement>('#tunnel-token')!, FAKE_TOKEN);
+ await submit(host);
+ const token = host.querySelector<HTMLInputElement>('#tunnel-token')!;
+ expect(token.value).toBe('');
+ expect(host.textContent).not.toContain(FAKE_TOKEN);
+ expect(host.textContent).toContain('已保存');
+});
+
+it('独立包不渲染模式切换,只剩开关', async () => {
+ const host = await mount({ ...STOPPED, named_available: false });
+ expect(host.querySelector('[role="radiogroup"]')).toBeNull();
+ expect(host.querySelector('button[type="submit"]')).toBeNull();
+ expect(host.textContent).toContain('启动公网入口');
+});
+
+it('主机名的字段错误落在输入框上,不写成一行红字', async () => {
+ const fetcher = vi.fn(async () => ({
+ ok: false,
+ status: 400,
+ json: async () => ({ error: '公开主机名不是有效的域名', errors: { hostname: '公开主机名不是有效的域名' } }),
+ }));
+ vi.stubGlobal('fetch', fetcher);
+ const host = await mount({ ...STOPPED, mode: 'named' });
+ await type(host.querySelector<HTMLInputElement>('#tunnel-hostname')!, 'peach.example.com/admin');
+ await submit(host);
+ expect(host.querySelector('#tunnel-hostname')?.getAttribute('aria-invalid')).toBe('true');
+ expect(host.querySelector('[role="alert"]')).toBeNull();
+});
diff --git a/src/peach/cli.py b/src/peach/cli.py
index fb66dca57..4a2262764 100644
--- a/src/peach/cli.py
+++ b/src/peach/cli.py
@@ -22,6 +22,9 @@ from .config import (
STATE_DIR,
CLOUDFLARED_BINARY,
TUNNEL_ENABLED,
+ TUNNEL_HOSTNAME,
+ TUNNEL_MODE,
+ TUNNEL_TOKEN,
PeachSettings,
)
from .migrations import plan, upgrade
@@ -103,6 +106,9 @@ def _serve(args: argparse.Namespace) -> int:
tls_enabled=tls_enabled,
tunnel_enabled=TUNNEL_ENABLED,
tunnel_binary=CLOUDFLARED_BINARY,
+ tunnel_mode=TUNNEL_MODE,
+ tunnel_token=TUNNEL_TOKEN,
+ tunnel_hostname=TUNNEL_HOSTNAME,
tunnel_standalone=distribution.standalone(),
tunnel_lan_address=tunnel_lan_address,
tunnel_origin_port=(args.port if distribution.standalone() or tls_enabled else None),
@@ -555,7 +561,7 @@ def _token(args: argparse.Namespace) -> int:
def _tunnel(args: argparse.Namespace) -> int:
- """运行一个前台 Quick Tunnel;托盘/配置页使用同一模块的生命周期管理。"""
+ """按设置文件的模式运行一个前台隧道;托盘/配置页使用同一模块的生命周期管理。"""
_require_readable_settings()
config = settings_file.load_config()
if not config.configured:
@@ -595,7 +601,7 @@ def _tunnel(args: argparse.Namespace) -> int:
# 起来了,只有走到 finally 才收得掉。
try:
snapshot = manager.start(plan)
- print(f"临时链接:{snapshot.url}", flush=True)
+ print(f"公网入口:{snapshot.url}", flush=True)
while manager.snapshot().state == "running":
time.sleep(1)
except KeyboardInterrupt:
@@ -714,7 +720,7 @@ def build_parser() -> argparse.ArgumentParser:
token.set_defaults(handler=_token)
tunnel_parser = commands.add_parser(
- "tunnel", help="运行或查看 Cloudflare Quick Tunnel(默认要求已设置访问密码)",
+ "tunnel", help="运行或查看 Cloudflare Tunnel(默认要求已设置访问密码)",
)
tunnel_parser.add_argument("action", choices=("start", "status"), nargs="?", default="start")
tunnel_parser.add_argument("--lan-address", help=argparse.SUPPRESS)
diff --git a/src/peach/config.py b/src/peach/config.py
index 7f429eb85..31c4b089b 100644
--- a/src/peach/config.py
+++ b/src/peach/config.py
@@ -72,6 +72,9 @@ SERVE_HOST: str = _SETTINGS.server.host
SERVE_PORT: int = _SETTINGS.server.port
TUNNEL_ENABLED: bool = _SETTINGS.tunnel.enabled
CLOUDFLARED_BINARY: str = _SETTINGS.tunnel.binary
+TUNNEL_MODE: str = _SETTINGS.tunnel.mode
+TUNNEL_TOKEN: str = _SETTINGS.tunnel.token
+TUNNEL_HOSTNAME: str = _SETTINGS.tunnel.hostname
@dataclass(frozen=True)
@@ -91,6 +94,11 @@ class PeachSettings:
#: 从设置文件读出后注入,`create_app()` 自己构造的设置一律是关闭加空路径。
tunnel_enabled: bool = False
tunnel_binary: str = ""
+ #: 公网入口的形态。`named` 走用户自建的命名隧道,只在源码开发环境成立;
+ #: 令牌从设置文件注入,进程内只用于拼启动参数,不写日志也不回给页面。
+ tunnel_mode: str = "quick"
+ tunnel_token: str = ""
+ tunnel_hostname: str = ""
tunnel_standalone: bool = False
tunnel_lan_address: str | None = None
#: Tunnel origin 的实际端口;源码部署留 None 表示标准 HTTPS 端口。
diff --git a/src/peach/routes_auth.py b/src/peach/routes_auth.py
index c82883ef2..c79778425 100644
--- a/src/peach/routes_auth.py
+++ b/src/peach/routes_auth.py
@@ -99,7 +99,7 @@ class AssetLoginRequired(Exception):
def _origin_key(value: str) -> tuple[str, str, int | None] | None:
- """把 Origin 头和随机 Quick Tunnel URL 归一到可比较的三元组。"""
+ """把 Origin 头和隧道 URL 归一到可比较的三元组。"""
try:
parsed = urlsplit(value.strip().rstrip("/"))
except ValueError:
@@ -115,7 +115,7 @@ def _origin_key(value: str) -> tuple[str, str, int | None] | None:
def _tunnel_origin(request: Request) -> tuple[str, str, int | None] | None:
- """返回当前进程实际拿到的 Quick Tunnel origin,而不是信任请求头。"""
+ """返回当前进程实际拿到的隧道 origin,而不是信任请求头。"""
manager = getattr(request.app.state, "tunnel", None)
if manager is None:
return None
@@ -126,13 +126,27 @@ def _tunnel_origin(request: Request) -> tuple[str, str, int | None] | None:
return _origin_key(url) if url else None
+def _named_origin(request: Request) -> tuple[str, str, int | None] | None:
+ """命名隧道的公开主机名。
+
+ 它来自本次启动注入的运行设置,不是请求头,也不随隧道握手完成才出现:连接刚建立
+ 那几秒页面就已经能提交,这时 manager 的快照还没进入 running。
+ """
+ settings = getattr(request.app.state, "settings", None)
+ if getattr(settings, "tunnel_mode", "") != tunnel.NAMED_MODE:
+ return None
+ hostname = (getattr(settings, "tunnel_hostname", "") or "").strip()
+ return _origin_key(tunnel.public_url(hostname)) if hostname else None
+
+
def same_origin(request: Request) -> None:
- """浏览器写请求只接受 Peach 页面或当前 Quick Tunnel 页面发来的 Origin。
+ """浏览器写请求只接受 Peach 页面或当前隧道页面发来的 Origin。
独立包的 origin 是回环 HTTP,cloudflared 转发时 Host 仍可能是本机地址,
- 所以不能单纯把 ``Origin`` 和 ASGI 的 ``base_url`` 比较。随机入口由当前
- TunnelManager 产生并保存在进程内,外部 Origin 必须精确匹配这一份,不能由
- 调用方通过 ``X-Forwarded-*`` 自己声明一个可信地址。
+ 所以不能单纯把 ``Origin`` 和 ASGI 的 ``base_url`` 比较。临时链接的随机入口由当前
+ TunnelManager 产生并保存在进程内,命名隧道的公开主机名来自本次启动的运行设置;
+ 外部 Origin 必须精确匹配这两者之一,不能由调用方通过 ``X-Forwarded-*`` 自己
+ 声明一个可信地址。
"""
origin = request.headers.get("origin")
if request.headers.get("sec-fetch-site") == "cross-site":
@@ -140,8 +154,8 @@ def same_origin(request: Request) -> None:
if origin:
supplied = _origin_key(origin)
local = _origin_key(str(request.base_url))
- tunnel_origin = _tunnel_origin(request)
- if supplied is None or supplied not in {local, tunnel_origin}:
+ allowed = {local, _tunnel_origin(request), _named_origin(request)}
+ if supplied is None or supplied not in allowed:
raise HTTPException(403, "请从 Peach 配置页提交")
diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.py
index ed9f1b0ec..7d5d67ddb 100644
--- a/src/peach/routes_configuration.py
+++ b/src/peach/routes_configuration.py
@@ -135,6 +135,12 @@ def tunnel_payload(config, state: tunnel.TunnelSnapshot, enabled: bool) -> dict[
"url": state.url,
"error": state.error,
"available": tunnel.resolve_binary(config.tunnel.binary) is not None,
+ "mode": (getattr(config.tunnel, "mode", "") or tunnel.QUICK_MODE).strip().lower(),
+ "hostname": getattr(config.tunnel, "hostname", ""),
+ # 令牌是凭据,只回报存没存过。页面据此显示「已保存」,不回显任何字符。
+ "token_set": bool((getattr(config.tunnel, "token", "") or "").strip()),
+ # 命名隧道要一份自建隧道的后台配置,独立包给不出,这一块在那里根本不渲染。
+ "named_available": not distribution.standalone(),
}
@@ -372,10 +378,36 @@ def save_access(request: Request, body: dict[str, Any] = Body(default_factory=di
return response
+def tunnel_changes(config, body: dict[str, Any]) -> dict[str, Any]:
+ """从写回请求里取出隧道形态,缺席的键保持设置文件里的现值。
+
+ 令牌不回显,页面也就交不回原值:空串一律当作「不改」,要换只能提交一个新的。
+ 命名隧道在独立包里没有着落点,这里当场拒绝,不让它先落盘再在启动时失败。
+ """
+ changes: dict[str, Any] = {}
+ for key in ("mode", "hostname", "token"):
+ if key in body and not isinstance(body[key], str):
+ raise HTTPException(400, f"{key} 必须是文字")
+ try:
+ if "mode" in body:
+ changes["mode"] = tunnel.normalize_mode(body["mode"])
+ if body.get("hostname", "").strip():
+ changes["hostname"] = tunnel.normalize_hostname(body["hostname"])
+ except tunnel.TunnelError as exc:
+ field = "mode" if "mode" in body and "mode" not in changes else "hostname"
+ raise HTTPException(400, {"message": str(exc), "errors": {field: str(exc)}}) from exc
+ if body.get("token", "").strip():
+ changes["token"] = body["token"].strip()
+ mode = changes.get("mode") or (getattr(config.tunnel, "mode", "") or tunnel.QUICK_MODE)
+ if mode == tunnel.NAMED_MODE and distribution.standalone():
+ raise HTTPException(400, tunnel.STANDALONE_NAMED_ERROR)
+ return changes
+
+
@router.post("/api/configuration/tunnel")
def save_tunnel(request: Request, body: dict[str, Any] = Body(default_factory=dict),
_args=Depends(require_auth)):
- """启动或停止本机 Quick Tunnel;入口只对本机配置页开放。"""
+ """保存隧道形态并启动或停止它;入口只对本机配置页开放。"""
local_only(request)
same_origin(request)
config = settings_file.load_config()
@@ -386,6 +418,9 @@ def save_tunnel(request: Request, body: dict[str, Any] = Body(default_factory=di
enabled = body.get("enabled")
if not isinstance(enabled, bool):
raise HTTPException(400, "enabled 必须是 true 或 false")
+ updated = replace(
+ config, tunnel=replace(config.tunnel, enabled=enabled, **tunnel_changes(config, body)),
+ )
manager = request.app.state.tunnel
state = tunnel.TunnelSnapshot(state="stopped")
started_here = False
@@ -394,8 +429,9 @@ def save_tunnel(request: Request, body: dict[str, Any] = Body(default_factory=di
try:
existing = manager.snapshot()
started_here = existing.state not in {"starting", "running"}
+ # 计划按这次提交的形态构造,不是磁盘上那一份:模式和主机名可能就是本次改的。
plan = tunnel.plan_for_config(
- config,
+ updated,
access_path=settings.access_path,
token=settings.token,
standalone_mode=getattr(settings, "tunnel_standalone", distribution.standalone()),
@@ -406,7 +442,6 @@ def save_tunnel(request: Request, body: dict[str, Any] = Body(default_factory=di
state = manager.start(plan)
except tunnel.TunnelError as exc:
raise HTTPException(409, str(exc)) from exc
- updated = replace(config, tunnel=replace(config.tunnel, enabled=enabled))
try:
with FileLock(str(config.path.with_suffix(".lock")), timeout=0):
current = settings_file.load_config()
diff --git a/src/peach/settings_file.py b/src/peach/settings_file.py
index f6be3a90a..a883618d8 100644
--- a/src/peach/settings_file.py
+++ b/src/peach/settings_file.py
@@ -157,15 +157,22 @@ class ReplicationSettings:
@dataclass(frozen=True)
class TunnelSettings:
- """Cloudflare Quick Tunnel 的本机开关。
+ """Cloudflare Tunnel 的本机开关。
Quick Tunnel 没有稳定域名,也没有 Cloudflare Access 身份层,所以默认关闭,
只有在 Peach 自己已经启用访问密码时才允许打开。`binary` 只记录本机可执行文件
的显式位置,不把二进制或下载地址写进设置文件。
+
+ `mode = "named"` 换成用户自己在 Cloudflare 后台建的命名隧道:入口是 `hostname`
+ 这个固定主机名,凭据是 `token`。令牌只落在这个文件里,不进账本、日志和健康检查。
+ 命名隧道只在源码开发环境可用,独立包读到它会拒绝启动隧道。
"""
enabled: bool = False
binary: str = ""
+ mode: str = "quick"
+ token: str = ""
+ hostname: str = ""
@dataclass(frozen=True)
@@ -385,6 +392,12 @@ def _merge(
tunnel_table, "enabled", tunnel_defaults.enabled, path, "tunnel."),
binary=_string(
tunnel_table, "binary", tunnel_defaults.binary, path, "tunnel."),
+ mode=_string(
+ tunnel_table, "mode", tunnel_defaults.mode, path, "tunnel."),
+ token=_string(
+ tunnel_table, "token", tunnel_defaults.token, path, "tunnel."),
+ hostname=_string(
+ tunnel_table, "hostname", tunnel_defaults.hostname, path, "tunnel."),
)
config = PeachConfig(
@@ -590,12 +603,18 @@ def render(config: PeachConfig) -> str:
lines += [
"",
"[tunnel]",
- "# Cloudflare Quick Tunnel 默认关闭;打开前必须先设置访问密码。",
+ "# Cloudflare Tunnel 默认关闭;打开前必须先设置访问密码。",
"# binary 留空时按内置包、PEACH_CLOUDFLARED 和 PATH 的顺序寻找 cloudflared。",
+ "# mode = \"quick\" 是随机地址的临时链接;\"named\" 用自建命名隧道,只在源码开发",
+ "# 环境可用,需要 hostname(Cloudflare 后台绑定的公开主机名)和 token(隧道令牌)。",
+ "# token 是凭据:这个文件是它唯一的存放处,不要复制到别处,也不要提交进 Git。",
]
lines += _render_pairs({
"enabled": config.tunnel.enabled,
"binary": config.tunnel.binary,
+ "mode": config.tunnel.mode,
+ "hostname": config.tunnel.hostname,
+ "token": config.tunnel.token,
})
return "\n".join(lines) + "\n"
diff --git a/src/peach/tunnel.py b/src/peach/tunnel.py
index 2d081b14a..41cbdcbc8 100644
--- a/src/peach/tunnel.py
+++ b/src/peach/tunnel.py
@@ -1,8 +1,12 @@
-"""Cloudflare Quick Tunnel 的受控进程边界。
+"""Cloudflare Tunnel 的受控进程边界。
Peach 不实现 Cloudflare 协议,只负责三件事:为两种部署选正确的本机 origin,
把访问密码作为启动前置条件,以及在自己的服务生命周期内管理 ``cloudflared``。
Quick Tunnel 的随机地址只写进数据根的状态文件,不进入设置、账本或日志文档。
+
+命名隧道(Named Tunnel)多一条固定入口:地址是用户在 Cloudflare 后台绑定的公开主机名,
+不从 cloudflared 的输出里捕获,就绪判据只剩 pidfile。它要一份隧道令牌,只存在设置文件里,
+不进账本、日志与健康检查;本模块把它从子进程输出中抹掉,也不打印任何启动计划。
"""
from __future__ import annotations
@@ -35,6 +39,15 @@ QUICK_URL_RE = re.compile(
)
#: cloudflared 转发时一定会带上的请求头;只要隧道在跑,带这些头的连接就来自公网。
EDGE_HEADERS = ("cf-connecting-ip", "cf-ray")
+QUICK_MODE = "quick"
+NAMED_MODE = "named"
+MODES = (QUICK_MODE, NAMED_MODE)
+STANDALONE_NAMED_ERROR = "独立包只支持临时链接"
+#: 一段主机名标签:字母数字开头结尾,中间可带连字符;整串至少两段且不超过 253 字符。
+HOSTNAME_RE = re.compile(
+ r"^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"
+ r"(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$"
+)
class TunnelError(RuntimeError):
@@ -53,6 +66,11 @@ class TunnelPlan:
binary: Path
origin: TunnelOrigin
command: tuple[str, ...]
+ mode: str = QUICK_MODE
+ #: 命名隧道的公开入口。非空表示地址已经定下来,不必也不该从子进程输出里捕获。
+ url: str = ""
+ #: 命令里带着的凭据。管理器只用它做一件事:把它从子进程日志里抹掉。
+ secret: str = ""
@dataclass(frozen=True)
@@ -192,6 +210,37 @@ def validate_access(access_path: Path | None, token: str) -> None:
raise TunnelError(message)
+def normalize_mode(value: str) -> str:
+ """把设置里的模式收敛成两个已知值之一;空串按临时链接处理。"""
+ mode = (value or "").strip().lower() or QUICK_MODE
+ if mode not in MODES:
+ raise TunnelError(f"tunnel.mode 只能是 quick 或 named:{value}")
+ return mode
+
+
+def normalize_hostname(value: str) -> str:
+ """校验公开主机名。
+
+ 用户多半从 Cloudflare 后台整条地址复制过来,所以容忍 `https://` 前缀和末尾的点;
+ 其余一律按域名判,路径、端口和空格都算填错——这个值同时用于展示和同源校验,
+ 放一个解析不出主机的串进去等于把写接口的门开在一个谁都对不上的名字上。
+ """
+ host = (value or "").strip().rstrip(".").lower()
+ for prefix in ("https://", "http://"):
+ if host.startswith(prefix):
+ host = host[len(prefix):]
+ host = host.rstrip("/").rstrip(".")
+ if not host:
+ raise TunnelError("命名隧道需要填写公开主机名")
+ if not HOSTNAME_RE.match(host):
+ raise TunnelError(f"公开主机名不是有效的域名:{value}")
+ return host
+
+
+def public_url(hostname: str) -> str:
+ return f"https://{hostname}"
+
+
def build_command(binary: Path, origin: TunnelOrigin) -> tuple[str, ...]:
"""构造不带凭据的 Quick Tunnel 命令。"""
command = [
@@ -205,6 +254,30 @@ def build_command(binary: Path, origin: TunnelOrigin) -> tuple[str, ...]:
return tuple(command)
+def build_named_command(binary: Path, token: str) -> tuple[str, ...]:
+ """命名隧道的入向配置在 Cloudflare 后台,这里不传 `--url` 也不传 origin 选项。"""
+ return (
+ str(binary), "tunnel", "run", "--token", token,
+ "--no-autoupdate", "--loglevel", "info", "--metrics", "127.0.0.1:0",
+ )
+
+
+def named_plan(
+ binary: Path, *, token: str, hostname: str, standalone_mode: bool,
+) -> TunnelPlan:
+ """命名隧道只在源码开发环境可用,且必须同时有令牌和公开主机名。"""
+ if standalone_mode:
+ raise TunnelError(STANDALONE_NAMED_ERROR)
+ secret = (token or "").strip()
+ if not secret:
+ raise TunnelError("命名隧道需要填写 Cloudflare 隧道令牌")
+ url = public_url(normalize_hostname(hostname))
+ return TunnelPlan(
+ binary=binary, origin=TunnelOrigin(url), command=build_named_command(binary, secret),
+ mode=NAMED_MODE, url=url, secret=secret,
+ )
+
+
def plan_for_config(
config,
*,
@@ -227,6 +300,13 @@ def plan_for_config(
getattr(tunnel_settings, "binary", ""),
executable=executable, environ=environ, which=which,
)
+ if normalize_mode(getattr(tunnel_settings, "mode", "")) == NAMED_MODE:
+ return named_plan(
+ binary,
+ token=getattr(tunnel_settings, "token", ""),
+ hostname=getattr(tunnel_settings, "hostname", ""),
+ standalone_mode=standalone_mode,
+ )
origin = origin_for_config(
config, standalone_mode=standalone_mode, lan_address=lan_address,
https_port=https_port,
@@ -270,6 +350,13 @@ def plan_for_settings(
binary = _require_binary(
settings.tunnel_binary, executable=executable, environ=environ, which=which,
)
+ if normalize_mode(getattr(settings, "tunnel_mode", "")) == NAMED_MODE:
+ return named_plan(
+ binary,
+ token=getattr(settings, "tunnel_token", ""),
+ hostname=getattr(settings, "tunnel_hostname", ""),
+ standalone_mode=settings.tunnel_standalone,
+ )
origin = build_origin(
standalone_mode=settings.tunnel_standalone,
port=settings.tunnel_origin_port,
@@ -560,6 +647,9 @@ class TunnelManager:
self._process: subprocess.Popen | None = None
self._reader: threading.Thread | None = None
self._url = ""
+ # 命名隧道的地址由设置给定,子进程输出里出现的任何地址都不该盖掉它。
+ self._fixed_url = False
+ self._secret = ""
self._error = ""
self._started_at = ""
self._ready = threading.Event()
@@ -643,6 +733,10 @@ class TunnelManager:
def _write_error(self, message: str) -> None:
self._error = message
+ # 启动失败后不留着命名隧道那个固定地址:它是计划里的值,不是一条在服务的入口。
+ self._url = ""
+ self._fixed_url = False
+ self._secret = ""
try:
_write_state(self.state_file, TunnelSnapshot(state="error", error=message))
except OSError:
@@ -673,9 +767,14 @@ class TunnelManager:
try:
for raw in iter(stream.readline, ""):
line = str(raw).rstrip("\r\n")
+ secret = self._secret
+ if secret:
+ line = line.replace(secret, "***")
if line:
handle.write(line + "\n")
handle.flush()
+ if self._fixed_url:
+ continue
url = extract_quick_url(line)
if url:
with self._lock:
@@ -718,7 +817,10 @@ class TunnelManager:
return self.snapshot()
self._generation += 1
generation = self._generation
- self._url = ""
+ # 命名隧道开工前地址就是已知的,等的只是 cloudflared 把 pidfile 写出来。
+ self._url = plan.url
+ self._fixed_url = bool(plan.url)
+ self._secret = plan.secret
self._error = ""
self._started_at = datetime.now(timezone.utc).isoformat()
self._ready.clear()
@@ -846,6 +948,8 @@ class TunnelManager:
self._generation += 1
cleanup_generation = self._generation
self._url = ""
+ self._fixed_url = False
+ self._secret = ""
self._error = ""
self._ready.set()
self._terminate_process(process)
diff --git a/tests/test_tunnel.py b/tests/test_tunnel.py
index 21e6b6ba5..28444e456 100644
--- a/tests/test_tunnel.py
+++ b/tests/test_tunnel.py
@@ -11,7 +11,7 @@ from unittest import mock
from fastapi import HTTPException
from fastapi.testclient import TestClient
-from peach import access, api, routes_auth, routes_configuration, tunnel
+from peach import access, api, routes_auth, routes_configuration, settings_file, tunnel
from peach.config import PeachSettings
#: 假扮 cloudflared 的真实子进程:写 pidfile、按行吐出一条入口,然后等着被收掉。
@@ -29,11 +29,18 @@ while True:
'''
+#: 夹具里的隧道令牌一律是这个假值;真实令牌不进仓库,也不进任何测试输出。
+FAKE_TOKEN = "fake-tunnel-token-for-tests"
+
+
class _Config:
- def __init__(self, root: Path, *, port: int = 8900, binary: str = ""):
+ def __init__(self, root: Path, *, port: int = 8900, binary: str = "",
+ mode: str = "quick", token: str = "", hostname: str = ""):
self.data_root = root
self.server = SimpleNamespace(port=port, mdns_name="peach")
- self.tunnel = SimpleNamespace(binary=binary)
+ self.tunnel = SimpleNamespace(
+ binary=binary, mode=mode, token=token, hostname=hostname,
+ )
def directory(self, name: str) -> Path:
return self.data_root / name
@@ -226,6 +233,87 @@ class TunnelPlanTests(unittest.TestCase):
with self.assertRaisesRegex(tunnel.TunnelError, "需要正在运行的 HTTPS"):
tunnel.plan_for_settings(settings, environ={})
+ def named_config(self, **overrides):
+ values = {
+ "binary": str(self.binary), "mode": "named",
+ "token": FAKE_TOKEN, "hostname": "peach.example.com",
+ }
+ return _Config(self.root, **{**values, **overrides})
+
+ def test_named_mode_runs_by_token_and_takes_its_url_from_the_hostname(self):
+ plan = tunnel.plan_for_config(
+ self.named_config(), access_path=self.access_path, token="internal-token",
+ standalone_mode=False, lan_address="192.0.2.162",
+ )
+ self.assertEqual(plan.mode, "named")
+ self.assertEqual(plan.url, "https://peach.example.com")
+ self.assertEqual(plan.origin.url, "https://peach.example.com")
+ self.assertEqual(plan.command[1:5], ("tunnel", "run", "--token", FAKE_TOKEN))
+ self.assertNotIn("--url", plan.command)
+ for option in ("--no-autoupdate", "--metrics"):
+ self.assertIn(option, plan.command)
+ self.assertEqual(plan.command[plan.command.index("--metrics") + 1], "127.0.0.1:0")
+
+ def test_a_standalone_package_refuses_the_named_mode(self):
+ with self.assertRaisesRegex(tunnel.TunnelError, tunnel.STANDALONE_NAMED_ERROR):
+ tunnel.plan_for_config(
+ self.named_config(), access_path=self.access_path, token="internal-token",
+ standalone_mode=True,
+ )
+
+ def test_named_mode_needs_both_a_token_and_a_hostname(self):
+ with self.assertRaisesRegex(tunnel.TunnelError, "隧道令牌"):
+ tunnel.plan_for_config(
+ self.named_config(token=" "), access_path=self.access_path,
+ token="internal-token", standalone_mode=False,
+ )
+ with self.assertRaisesRegex(tunnel.TunnelError, "公开主机名"):
+ tunnel.plan_for_config(
+ self.named_config(hostname=""), access_path=self.access_path,
+ token="internal-token", standalone_mode=False,
+ )
+
+ def test_a_hostname_with_a_path_or_a_bare_label_is_rejected(self):
+ for value in ("peach.example.com/admin", "localhost", "peach.example.com:8443", "-bad.example.com"):
+ with self.subTest(value=value), self.assertRaises(tunnel.TunnelError):
+ tunnel.normalize_hostname(value)
+
+ def test_a_hostname_copied_with_its_scheme_still_resolves(self):
+ self.assertEqual(
+ tunnel.normalize_hostname(" https://Peach.Example.COM/ "), "peach.example.com")
+
+ def test_an_unknown_mode_is_refused_instead_of_falling_back(self):
+ with self.assertRaisesRegex(tunnel.TunnelError, "quick 或 named"):
+ tunnel.normalize_mode("tunnel")
+ self.assertEqual(tunnel.normalize_mode(""), "quick")
+
+ def test_injected_settings_carry_the_named_mode_without_an_origin_lookup(self):
+ settings = SimpleNamespace(
+ access_path=self.access_path, token="internal-token",
+ tunnel_standalone=False, tunnel_binary=str(self.binary),
+ tunnel_mode="named", tunnel_token=FAKE_TOKEN,
+ tunnel_hostname="peach.example.com",
+ tunnel_origin_port=None, tunnel_lan_address=None,
+ tunnel_ca_path=self.root / "missing-ca.crt", tls_enabled=True,
+ mdns_name="peach",
+ )
+ plan = tunnel.plan_for_settings(settings, environ={})
+ self.assertEqual(plan.url, "https://peach.example.com")
+ self.assertEqual(plan.secret, FAKE_TOKEN)
+
+ def test_a_standalone_package_refuses_named_settings_at_startup(self):
+ settings = SimpleNamespace(
+ access_path=self.access_path, token="internal-token",
+ tunnel_standalone=True, tunnel_binary=str(self.binary),
+ tunnel_mode="named", tunnel_token=FAKE_TOKEN,
+ tunnel_hostname="peach.example.com",
+ tunnel_origin_port=8900, tunnel_lan_address=None,
+ tunnel_ca_path=self.root / "missing-ca.crt", tls_enabled=False,
+ mdns_name="peach",
+ )
+ with self.assertRaisesRegex(tunnel.TunnelError, tunnel.STANDALONE_NAMED_ERROR):
+ tunnel.plan_for_settings(settings, environ={})
+
class TunnelManagerTests(unittest.TestCase):
def setUp(self):
@@ -250,6 +338,45 @@ class TunnelManagerTests(unittest.TestCase):
command=("cloudflared", "tunnel", "--url", "http://127.0.0.1:8900"),
)
+ def named_plan(self):
+ return tunnel.TunnelPlan(
+ binary=self.root / "cloudflared.exe",
+ origin=tunnel.TunnelOrigin("https://peach.example.com"),
+ command=("cloudflared", "tunnel", "run", "--token", FAKE_TOKEN),
+ mode="named", url="https://peach.example.com", secret=FAKE_TOKEN,
+ )
+
+ def test_a_named_tunnel_is_ready_on_its_pidfile_and_keeps_its_own_url(self):
+ manager = tunnel.TunnelManager(
+ self.root / "state", self.root / "logs", popen=self.popen, wait_timeout=2,
+ )
+ started = manager.start(self.named_plan())
+ self.assertEqual(started.state, "running")
+ # 子进程那一行随机地址不能盖掉设置里定下来的入口。
+ self.assertEqual(started.url, "https://peach.example.com")
+ manager.stop()
+
+ def test_the_tunnel_token_never_reaches_the_log_or_the_snapshot(self):
+ def leaky(command, **kwargs):
+ pid_index = command.index("--pidfile") + 1
+ Path(command[pid_index]).write_text("4123\n", encoding="ascii")
+ process = _Process(_Stream(f"INF | registering with token {FAKE_TOKEN}\n"))
+ self.processes.append(process)
+ return process
+
+ manager = tunnel.TunnelManager(
+ self.root / "state", self.root / "logs", popen=leaky, wait_timeout=2,
+ )
+ started = manager.start(self.named_plan())
+ manager.stop()
+ log = (self.root / "logs" / tunnel.LOG_FILENAME).read_text(encoding="utf-8")
+ self.assertNotIn(FAKE_TOKEN, log)
+ self.assertIn("***", log)
+ self.assertNotIn(FAKE_TOKEN, repr(started))
+ state_file = self.root / "state" / tunnel.STATE_FILENAME
+ if state_file.exists():
+ self.assertNotIn(FAKE_TOKEN, state_file.read_text(encoding="utf-8"))
+
def test_start_writes_url_and_stop_removes_state(self):
manager = tunnel.TunnelManager(
self.root / "state", self.root / "logs", popen=self.popen, wait_timeout=2,
@@ -368,6 +495,35 @@ class TunnelOriginGuardTests(unittest.TestCase):
routes_auth.same_origin(self.request("https://other.trycloudflare.com"))
self.assertEqual(raised.exception.status_code, 403)
+ def named_request(self, origin: str, *, hostname: str = "peach.example.com"):
+ """命名隧道的主机名来自运行设置,隧道快照此刻还没有地址。"""
+ manager = SimpleNamespace(snapshot=lambda: tunnel.TunnelSnapshot(state="starting"))
+ settings = SimpleNamespace(tunnel_mode="named", tunnel_hostname=hostname)
+ return SimpleNamespace(
+ app=SimpleNamespace(state=SimpleNamespace(tunnel=manager, settings=settings)),
+ headers={"origin": origin},
+ base_url="http://127.0.0.1:8900/",
+ )
+
+ def test_the_configured_named_hostname_is_allowed_before_the_handshake_finishes(self):
+ routes_auth.same_origin(self.named_request("https://peach.example.com"))
+
+ def test_another_hostname_is_rejected_in_the_named_mode(self):
+ with self.assertRaises(HTTPException) as raised:
+ routes_auth.same_origin(self.named_request("https://peach.example.net"))
+ self.assertEqual(raised.exception.status_code, 403)
+
+ def test_a_named_hostname_is_not_allowed_while_the_mode_is_quick(self):
+ manager = SimpleNamespace(snapshot=lambda: tunnel.TunnelSnapshot(state="stopped"))
+ settings = SimpleNamespace(tunnel_mode="quick", tunnel_hostname="peach.example.com")
+ request = SimpleNamespace(
+ app=SimpleNamespace(state=SimpleNamespace(tunnel=manager, settings=settings)),
+ headers={"origin": "https://peach.example.com"},
+ base_url="http://127.0.0.1:8900/",
+ )
+ with self.assertRaises(HTTPException):
+ routes_auth.same_origin(request)
+
class TunnelRouteTests(unittest.TestCase):
def setUp(self):
@@ -482,6 +638,122 @@ class TunnelRouteTests(unittest.TestCase):
manager.stop.assert_not_called()
+class NamedTunnelRouteTests(unittest.TestCase):
+ """写回接口同时收下形态与开关;令牌只进设置文件,不回给页面。"""
+
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.root = Path(self.temp.name).resolve()
+ self.config_path = self.root / "config.toml"
+ self.config_path.write_text("[tunnel]\nenabled = false\n", encoding="utf-8")
+ self.config = settings_file.PeachConfig(
+ data_root=self.root, path=self.config_path, present=True,
+ )
+ self.settings = SimpleNamespace(
+ access_path=self.root / "access.json", token="internal-token",
+ tunnel_standalone=False, tunnel_lan_address="192.0.2.162",
+ tunnel_origin_port=443, tls_enabled=True,
+ )
+ self.plan = tunnel.TunnelPlan(
+ binary=self.root / "cloudflared.exe",
+ origin=tunnel.TunnelOrigin("https://peach.example.com"),
+ command=("cloudflared", "tunnel", "run", "--token", FAKE_TOKEN),
+ mode="named", url="https://peach.example.com", secret=FAKE_TOKEN,
+ )
+
+ def tearDown(self):
+ self.temp.cleanup()
+
+ def request(self, manager):
+ state = SimpleNamespace(tunnel=manager, settings=self.settings)
+ return SimpleNamespace(
+ app=SimpleNamespace(state=state),
+ 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):
+ manager = mock.Mock()
+ manager.snapshot.return_value = tunnel.TunnelSnapshot(state="stopped")
+ manager.start.return_value = tunnel.TunnelSnapshot(
+ state="running", url="https://peach.example.com", pid=4123,
+ )
+ manager.stop.return_value = tunnel.TunnelSnapshot(state="stopped")
+ return manager
+
+ def save(self, body, *, plan_for_config=None):
+ written = mock.Mock()
+ manager = self.manager()
+ planner = plan_for_config or mock.Mock(return_value=self.plan)
+ with mock.patch.multiple(
+ routes_configuration.settings_file,
+ load_config=mock.Mock(return_value=self.config), write=written,
+ ), mock.patch.object(routes_configuration, "revision", return_value="rev"), \
+ mock.patch.object(routes_configuration.tunnel, "plan_for_config", planner), \
+ mock.patch.object(routes_configuration, "FileLock") as lock:
+ lock.return_value.__enter__.return_value = lock.return_value
+ result = routes_configuration.save_tunnel(
+ self.request(manager), {"revision": "rev", **body}, None,
+ )
+ return result, written, manager, planner
+
+ def test_the_named_form_is_persisted_and_the_plan_uses_this_submission(self):
+ result, written, _manager, planner = self.save({
+ "enabled": True, "mode": "named",
+ "hostname": "https://Peach.Example.com/", "token": FAKE_TOKEN,
+ })
+ saved = written.call_args.args[0]
+ self.assertEqual(saved.tunnel.mode, "named")
+ self.assertEqual(saved.tunnel.hostname, "peach.example.com")
+ self.assertEqual(saved.tunnel.token, FAKE_TOKEN)
+ self.assertEqual(planner.call_args.args[0].tunnel.hostname, "peach.example.com")
+ self.assertEqual(result["mode"], "named")
+ self.assertEqual(result["hostname"], "peach.example.com")
+ self.assertTrue(result["token_set"])
+ self.assertTrue(result["named_available"])
+
+ def test_the_response_never_carries_the_token_itself(self):
+ result, _written, _manager, _planner = self.save({
+ "enabled": True, "mode": "named",
+ "hostname": "peach.example.com", "token": FAKE_TOKEN,
+ })
+ self.assertNotIn(FAKE_TOKEN, json.dumps(result, ensure_ascii=False))
+ self.assertNotIn("token", set(result) - {"token_set"})
+
+ def test_an_empty_token_keeps_the_saved_one(self):
+ self.config = settings_file.PeachConfig(
+ data_root=self.root, path=self.config_path, present=True,
+ tunnel=settings_file.TunnelSettings(
+ mode="named", token=FAKE_TOKEN, hostname="peach.example.com"),
+ )
+ _result, written, _manager, _planner = self.save({
+ "enabled": False, "mode": "named", "hostname": "peach.example.com", "token": "",
+ })
+ self.assertEqual(written.call_args.args[0].tunnel.token, FAKE_TOKEN)
+
+ def test_an_invalid_hostname_comes_back_as_a_field_error(self):
+ with self.assertRaises(HTTPException) as raised:
+ self.save({"enabled": False, "mode": "named", "hostname": "peach.example.com/admin"})
+ self.assertEqual(raised.exception.status_code, 400)
+ self.assertIn("hostname", raised.exception.detail["errors"])
+
+ def test_a_standalone_package_refuses_to_store_the_named_mode(self):
+ with mock.patch.object(routes_configuration.distribution, "standalone", return_value=True):
+ with self.assertRaises(HTTPException) as raised:
+ routes_configuration.tunnel_changes(self.config, {"mode": "named"})
+ self.assertEqual(raised.exception.status_code, 400)
+ self.assertEqual(raised.exception.detail, tunnel.STANDALONE_NAMED_ERROR)
+
+ def test_a_standalone_package_reports_that_the_named_mode_is_unavailable(self):
+ with mock.patch.object(routes_configuration.distribution, "standalone", return_value=True):
+ payload = routes_configuration.tunnel_payload(
+ self.config, tunnel.TunnelSnapshot(), False)
+ self.assertFalse(payload["named_available"])
+
+
def direct_interpreter() -> str:
"""找一个自己就是最终进程的解释器。