From 650bc706b3621376bab0b543f3995525c1c4cc51 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 23 Sep 2026 12:22:58 +0800 Subject: [PATCH] feat(control): require a token on the control plane The socket's `0700` mode is a guarantee the filesystem makes, and it only holds on this platform. Windows has no equivalent: the control plane can only land on a loopback TCP port there, any local process can connect to one, and unlike a unix socket it cannot be asked who is on the other end. So the credential is a second door, and both platforms walk through it. A defence that only runs on one platform is a defence nobody exercises. The token comes from `TW_CONTROL_TOKEN` when the parent process passes one -- the desktop app spawns core itself, so it generates the token and hands it over through the environment, never through argv (Windows shows every process's command line to every other process of the same user) and never through a file. Without that variable someone is running `twcore serve` by hand, and the token is generated once into `control.token` beside the configuration, created `0600` rather than chmod'ed afterwards, so there is no window where the key to this door is world-readable. The guard goes on at the serving boundary, not inside `router()`. That route table is what a dozen integration tests drive directly; welding the door into it would only teach every one of those tests to open it. The smoke script now passes the token, and asserts that a request without one is refused. That assertion is the only thing that can prove the door is real: the middleware's own tests say it refuses, but whether it is actually mounted on the route table that faces the socket takes the real binary to answer -- and the shape of getting that wrong is every test still passing while the control plane stands open. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 1 + bin/twcore/src/main.rs | 6 +- crates/tw-control/Cargo.toml | 2 + crates/tw-control/src/lib.rs | 21 ++- crates/tw-control/src/token.rs | 318 +++++++++++++++++++++++++++++++++ scripts/smoke.sh | 31 +++- 6 files changed, 364 insertions(+), 15 deletions(-) create mode 100644 crates/tw-control/src/token.rs diff --git a/Cargo.lock b/Cargo.lock index 6c6cdbd1..f5199ee4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2832,6 +2832,7 @@ dependencies = [ "hyper", "hyper-util", "libc", + "rand 0.10.2", "reqwest", "serde", "serde_json", diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index e9cecf26..e45eb522 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -722,6 +722,10 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // **在起任何东西之前问**。等到 bind 失败时,网关已经在监听、客户端 // 可能已经连上来了,而这条错误当时只会进日志。 tw_control::socket_path_fits(&socket)?; + // 控制面的凭据,同样在起任何东西之前拿到:桌面端从环境变量交过来, + // 手工启动时生成一个写进配置目录。取不到就停在这儿 —— 一个装不上门的 + // 控制面不该先起来再说。 + let control_token = tw_control::token::Token::resolve(&dir)?; let config_path = path.to_path_buf(); rt.block_on(async move { let state = tw_gateway::AppState::new(cfg.clone()) @@ -836,7 +840,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // 太长)只在日志里躺着。退出让那句话有机会走到人眼前。 let (control_died, control_dead) = tokio::sync::oneshot::channel(); tokio::spawn(async move { - let r = tw_control::serve_unix(control, &sock).await; + let r = tw_control::serve_unix(control, &sock, control_token).await; let msg = match r { Err(e) => format!("{e}"), // serve_unix 正常返回意味着 accept 循环结束了,同样是没了 diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index ddd04e1c..8193552c 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -12,6 +12,8 @@ tw-api = { workspace = true } tw-types = { workspace = true } # 列网卡用 getifaddrs —— 比引一个 crate 便宜 libc = { workspace = true } +# 生成控制面的凭据 +rand = { workspace = true } tw-config = { workspace = true } tw-adopt = { workspace = true } tw-scan = { workspace = true } diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 32b44dbe..55cb55ff 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -1,8 +1,11 @@ //! 控制面:unix socket 上的 HTTP。 //! -//! **不占 TCP 端口**。理由不是省端口,是权限:一个 -//! `0700` 的 socket 文件天然只有当前用户能连,不需要再发明一套 token。 -//! 只有用户显式开启远程访问时才监听 TCP,那时才需要 token。 +//! **不占 TCP 端口**。理由不是省端口,是权限:一个 `0700` 的 socket 文件 +//! 天然只有当前用户能连。 +//! +//! 但那是文件系统给的保证,**只在这个平台上成立** —— Windows 上没有对等物, +//! 控制面在那里只能落在回环 TCP 上。所以凭据这道门是另外装的一道,两个平台 +//! 都走它,见 [`token`]。 use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -30,6 +33,7 @@ pub mod rotation; pub mod routes; pub mod scan; pub mod security; +pub mod token; pub mod zai; pub use config::{ApplyError, ConfigManager, resolve_path, spawn_watcher}; pub use tw_observe::EventBus; @@ -1468,7 +1472,11 @@ pub fn socket_path_fits(path: &Path) -> Result<(), ControlError> { /// /// 陈旧的 socket 文件直接删掉重建 —— 它和 lock 文件不一样,没有「另一个 /// 实例可能还在用」的歧义:单实例锁已经在上一步挡住了。 -pub async fn serve_unix(state: ControlState, path: &Path) -> Result<(), ControlError> { +pub async fn serve_unix( + state: ControlState, + path: &Path, + token: token::Token, +) -> Result<(), ControlError> { socket_path_fits(path)?; if path.exists() { let _ = std::fs::remove_file(path); @@ -1483,12 +1491,13 @@ pub async fn serve_unix(state: ControlState, path: &Path) -> Result<(), ControlE #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; - // 0700:只有当前用户能连。这就是不需要 token 的原因。 + // 0700:只有当前用户能连。凭据那道门在它之外,不是替代它 —— + // 两道都在,而只有这一道是平台给的。 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)); } tracing::info!(path = %path.display(), "the control plane is listening"); - let app = router(state); + let app = token::guard(router(state), token); loop { let (stream, _) = match listener.accept().await { Ok(x) => x, diff --git a/crates/tw-control/src/token.rs b/crates/tw-control/src/token.rs new file mode 100644 index 00000000..545c285b --- /dev/null +++ b/crates/tw-control/src/token.rs @@ -0,0 +1,318 @@ +//! 控制面的凭据。 +//! +//! # 为什么 socket 之外还要一道门 +//! +//! unix socket 那一套(`0700` 的文件,只有属主连得上)在 macOS 上够用,但它 +//! **是文件系统给的保证,不是我们给的**。Windows 上没有对等物:控制面在那里 +//! 只能落在 `127.0.0.1` 的 TCP 上,而本机任意进程都连得上一个回环端口,连上 +//! 之后也问不出对端是谁 —— unix socket 问得出(`SO_PEERCRED`),TCP 问不出。 +//! +//! 所以那里必须有一道自己的门。**两个平台装的是同一道**,不是只给 Windows +//! 装:一道只在一个平台上生效的防线,等于一道没人日常测的防线。 +//! +//! # token 从哪儿来 +//! +//! 优先环境变量。桌面端自己 spawn core(它从不接管已经在跑的),所以由它生成、 +//! 通过环境变量交过来。**不进 argv** —— Windows 的任务管理器和任意同用户进程 +//! 都看得见命令行 —— 也不落盘。 +//! +//! 没有环境变量,就是有人手工跑 `twcore serve`。那时自己生成一个,写进 +//! `<配置目录>/control.token`,下次再跑读回来。**不是每次现生成**:那样拿 +//! curl 调试的人每跑一次都得重抄一遍。 + +use std::path::{Path, PathBuf}; + +use axum::Json; +use axum::Router; +use axum::extract::{Request, State}; +use axum::http::{HeaderMap, StatusCode, header}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; +use std::sync::Arc; +use tw_types::msg; + +/// 桌面端把 token 交过来的那个环境变量。 +pub const ENV: &str = "TW_CONTROL_TOKEN"; + +/// 手工启动时 token 落在哪(相对配置目录)。 +pub const FILE: &str = "control.token"; + +#[derive(Debug, thiserror::Error)] +pub enum TokenError { + #[error("the control-plane token file {path} could not be read: {source}")] + Read { + path: PathBuf, + source: std::io::Error, + }, + #[error("the control-plane token file {path} could not be written: {source}")] + Write { + path: PathBuf, + source: std::io::Error, + }, +} + +#[derive(Clone)] +pub struct Token(String); + +/// **不打印出来。**`Token` 会跟着别的结构体一起落进 `tracing` 的 Debug 输出, +/// 而日志是会被整段贴进 issue 的。 +impl std::fmt::Debug for Token { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Token()") + } +} + +impl Token { + /// 环境变量优先,没有就读或建那个文件。 + pub fn resolve(dir: &Path) -> Result { + match Self::from_env() { + Some(t) => Ok(t), + None => Self::load_or_create(dir), + } + } + + pub fn from_env() -> Option { + let raw = std::env::var(ENV).ok()?; + let v = raw.trim(); + // 空字符串当作没给。**一个空 token 不是一道松的门,是一道开着的门** —— + // 下面的比较会对每一个同样没带凭据的请求成立。 + if v.is_empty() { + None + } else { + Some(Self(v.to_string())) + } + } + + fn load_or_create(dir: &Path) -> Result { + let path = dir.join(FILE); + match std::fs::read_to_string(&path) { + Ok(s) if !s.trim().is_empty() => return Ok(Self(s.trim().to_string())), + // 空文件:当没有过,重新生成盖掉。理由同 `from_env` 里那条。 + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(source) => return Err(TokenError::Read { path, source }), + } + let token = Self::generate(); + write_private(&path, token.as_str())?; + Ok(token) + } + + /// 32 字节的随机数,写成十六进制。 + pub fn generate() -> Self { + let mut bytes = [0u8; 32]; + rand::fill(&mut bytes); + let mut out = String::with_capacity(bytes.len() * 2); + for b in bytes { + use std::fmt::Write; + let _ = write!(out, "{b:02x}"); + } + Self(out) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + /// 对方给的那串对不对。 + /// + /// **恒定时间**:不在第一个不同的字节上提前返回。本机上的时序攻击不好做, + /// 但这里的差别只是一个 `|=` 和一个 `break`。 + pub fn matches(&self, presented: &str) -> bool { + let (want, got) = (self.0.as_bytes(), presented.as_bytes()); + // 长度不等直接否。**长度不是秘密** —— 自己生成的永远是 64 个十六进制 + // 字符 —— 所以为了不泄漏它去把比较写复杂没有意义。 + if want.len() != got.len() { + return false; + } + let mut diff = 0u8; + for (a, b) in want.iter().zip(got) { + diff |= a ^ b; + } + diff == 0 + } +} + +/// 建的时候就是 `0600`。 +/// +/// **不是建完再 `chmod`** —— 那中间有一个全世界可读的窗口,而窗口里躺着的 +/// 正是这道门的钥匙。已经存在的那个文件先删掉再建,否则 `mode` 对它不生效。 +fn write_private(path: &Path, contents: &str) -> Result<(), TokenError> { + use std::io::Write; + let err = |source| TokenError::Write { + path: path.to_path_buf(), + source, + }; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(err)?; + } + let _ = std::fs::remove_file(path); + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + opts.open(path) + .map_err(err)? + .write_all(contents.as_bytes()) + .map_err(err) +} + +/// 把鉴权装到一份路由表上。 +/// +/// **装在 serve 那一层,不装进 `router()`。**`router()` 是路由表本身,十几个 +/// 集成测试直接拿它跑处理函数;把门焊进去,等于让每个测试都先学会开门 —— +/// 而它们测的不是门。门装在真正对外的那一步上,门自己在下面单独测。 +pub fn guard(app: Router, token: Token) -> Router { + app.layer(axum::middleware::from_fn_with_state(Arc::new(token), check)) +} + +async fn check(State(token): State>, req: Request, next: Next) -> Response { + match bearer(req.headers()) { + Some(got) if token.matches(got) => next.run(req).await, + _ => unauthorized(), + } +} + +/// `Authorization: Bearer `。 +/// +/// 方案名按 RFC 7235 大小写不敏感 —— 我们自己的客户端永远写 `Bearer`,但拿 +/// curl 手敲的人写 `bearer` 不该被当成凭据不对。 +fn bearer(h: &HeaderMap) -> Option<&str> { + let v = h.get(header::AUTHORIZATION)?.to_str().ok()?; + let (scheme, rest) = v.split_once(' ')?; + scheme.eq_ignore_ascii_case("bearer").then(|| rest.trim()) +} + +fn unauthorized() -> Response { + ( + StatusCode::UNAUTHORIZED, + Json(msg!( + "control.unauthorized" => + "The control plane needs the token it was started with. The desktop app passes it automatically; \ + a hand-written client reads it from control.token in the configuration directory." + )), + ) + .into_response() +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::body::Body; + use axum::routing::get; + use tower::ServiceExt; + + fn app(token: Token) -> Router { + guard(Router::new().route("/x", get(|| async { "ok" })), token) + } + + async fn status_with(auth: Option<&str>) -> StatusCode { + let token = Token("sesame".to_string()); + let mut req = Request::builder().uri("/x"); + if let Some(a) = auth { + req = req.header(header::AUTHORIZATION, a); + } + app(token) + .oneshot(req.body(Body::empty()).unwrap()) + .await + .unwrap() + .status() + } + + #[tokio::test] + async fn the_right_token_gets_in_and_nothing_else_does() { + assert_eq!(status_with(Some("Bearer sesame")).await, StatusCode::OK); + // 方案名大小写不敏感 + assert_eq!(status_with(Some("bearer sesame")).await, StatusCode::OK); + + assert_eq!( + status_with(None).await, + StatusCode::UNAUTHORIZED, + "没带凭据" + ); + assert_eq!( + status_with(Some("Bearer open")).await, + StatusCode::UNAUTHORIZED, + "凭据不对" + ); + assert_eq!( + status_with(Some("sesame")).await, + StatusCode::UNAUTHORIZED, + "少了方案名" + ); + assert_eq!( + status_with(Some("Basic sesame")).await, + StatusCode::UNAUTHORIZED, + "换了方案名" + ); + assert_eq!( + status_with(Some("Bearer ")).await, + StatusCode::UNAUTHORIZED, + "空凭据" + ); + } + + /// 前缀对上不算对上 —— 恒定时间那段比较里长度是先判的,别把它判反了。 + #[test] + fn a_prefix_is_not_a_match() { + let t = Token("sesame".to_string()); + assert!(t.matches("sesame")); + assert!(!t.matches("sesam")); + assert!(!t.matches("sesamee")); + assert!(!t.matches("")); + } + + #[test] + fn a_generated_token_is_64_hex_characters_and_never_the_same_twice() { + let a = Token::generate(); + let b = Token::generate(); + assert_eq!(a.as_str().len(), 64); + assert!(a.as_str().chars().all(|c| c.is_ascii_hexdigit())); + assert_ne!(a.as_str(), b.as_str()); + } + + /// 第二次启动要拿到同一个 —— 否则每跑一次,手工客户端都得重抄一遍。 + #[test] + fn the_file_is_written_once_and_read_back_after_that() { + let d = tempfile::tempdir().unwrap(); + let first = Token::load_or_create(d.path()).unwrap(); + let again = Token::load_or_create(d.path()).unwrap(); + assert_eq!(first.as_str(), again.as_str()); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(d.path().join(FILE)) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600, "token 文件不该有别人的份"); + } + } + + /// 空文件当作没有。**留着它等于门开着** + #[test] + fn an_empty_file_is_replaced_rather_than_trusted() { + let d = tempfile::tempdir().unwrap(); + std::fs::write(d.path().join(FILE), " \n").unwrap(); + let t = Token::load_or_create(d.path()).unwrap(); + assert_eq!(t.as_str().len(), 64); + } + + /// 写进文件时带了换行,读回来不该把换行也当成凭据的一部分。 + #[test] + fn surrounding_whitespace_in_the_file_is_not_part_of_the_token() { + let d = tempfile::tempdir().unwrap(); + std::fs::write(d.path().join(FILE), " abc123\n").unwrap(); + assert!(Token::load_or_create(d.path()).unwrap().matches("abc123")); + } + + /// 日志里不能出现它。 + #[test] + fn it_does_not_print_itself() { + let t = Token("sesame".to_string()); + assert!(!format!("{t:?}").contains("sesame")); + } +} diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 7d9833eb..e3401fe7 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -18,6 +18,11 @@ export HOME="$FAKE_HOME" export THINKWATCH_HOME="$FAKE_HOME/.thinkwatch" mkdir -p "$THINKWATCH_HOME" "$FAKE_HOME/.claude" SOCK="$THINKWATCH_HOME/twcore.sock" +# 控制面要凭据。**这个脚本自己定它是什么**,通过环境变量交给 twcore —— +# 比等它自己生成一个、再去文件里把它捞回来少一步竞态(那个文件是在它 +# 启动过程中写的,而这里几乎同时就要用)。 +export TW_CONTROL_TOKEN="smoke-$$-$RANDOM" +AUTH=(-H "Authorization: Bearer $TW_CONTROL_TOKEN") PORT=18999 UPPORT=18998 PASS=0; FAIL=0 @@ -200,7 +205,7 @@ else # 根本没被当成 UTF-8。所以把这一次的路由决策和 core 日志一起交出来 —— # 少了这些,CI 上的一次失败在本机复现不出来就只能靠猜。 sleep 0.5 - CHAIN=$(curl -s --unix-socket "$SOCK" "http://localhost/history?limit=1" 2>/dev/null \ + CHAIN=$(curl -s --unix-socket "$SOCK" "${AUTH[@]}" "http://localhost/history?limit=1" 2>/dev/null \ | python3 -c 'import sys, json # /history 是个顶层数组。字段名在演化,所以打印整行而不是挑几个 —— # 挑错了名字就什么都看不到,而这段代码只在出事那一次跑。 @@ -240,7 +245,7 @@ echo "$S" | grep -q 'content_block_stop' && bad "切断之后还发了 content_b # 行一律没有用量,这笔钱就不在账上。 GOT="" for _ in $(seq 1 20); do - GOT=$(curl -s --unix-socket "$SOCK" "http://localhost/history?limit=1" 2>/dev/null \ + GOT=$(curl -s --unix-socket "$SOCK" "${AUTH[@]}" "http://localhost/history?limit=1" 2>/dev/null \ | python3 -c 'import sys, json rows = json.load(sys.stdin) r = rows[0] if rows else {} @@ -268,7 +273,7 @@ else GOT="" # 落库是异步的:事件先过广播,再由存储层的任务写进去 for _ in $(seq 1 20); do - GOT=$(curl -s --unix-socket "$SOCK" "http://localhost/history?limit=1" 2>/dev/null \ + GOT=$(curl -s --unix-socket "$SOCK" "${AUTH[@]}" "http://localhost/history?limit=1" 2>/dev/null \ | python3 -c 'import sys, json rows = json.load(sys.stdin) r = rows[0] if rows else {} @@ -284,10 +289,20 @@ print("ok" if good else json.dumps(r, ensure_ascii=False, sort_keys=True))' 2>/d fi # ---------------------------------------------------------------- 控制面 -step "控制面(每个端点)" +step "控制面要凭据" sleep 1 -get() { curl -s -o "$TMP/out" -w '%{http_code}' --unix-socket "$SOCK" "http://localhost$1"; } -post() { curl -s -o "$TMP/out" -w '%{http_code}' --unix-socket "$SOCK" -XPOST \ +# **只有这里能证明门是真的。**单元测试测的是那一层中间件,而「它到底有没有 +# 被挂到真正对外的那份路由表上」只有真二进制加真 socket 答得出来 —— 漏挂的 +# 样子是所有测试照常通过,而控制面对整台机器敞着。 +NOAUTH=$(curl -s -o /dev/null -w '%{http_code}' --unix-socket "$SOCK" http://localhost/status) +[ "$NOAUTH" = 401 ] && ok "不带凭据被拒" || bad "不带凭据竟然进去了" "$NOAUTH" +WRONG=$(curl -s -o /dev/null -w '%{http_code}' --unix-socket "$SOCK" \ + -H 'Authorization: Bearer not-the-one' http://localhost/status) +[ "$WRONG" = 401 ] && ok "凭据不对被拒" || bad "凭据不对竟然进去了" "$WRONG" + +step "控制面(每个端点)" +get() { curl -s -o "$TMP/out" -w '%{http_code}' --unix-socket "$SOCK" "${AUTH[@]}" "http://localhost$1"; } +post() { curl -s -o "$TMP/out" -w '%{http_code}' --unix-socket "$SOCK" "${AUTH[@]}" -XPOST \ -H 'content-type: application/json' -d "$2" "http://localhost$1"; } # **带上时间窗再打一次。**不带参数时一切正常、带上 `from_ms` 就 400, @@ -314,11 +329,11 @@ C=$(post /dryrun '{"model":"claude-sonnet-4-5","route":"默认"}'); [ "$C" = "20 C=$(post /clients/plan '{"client":"claude-code"}'); [ "$C" = "200" ] && ok "POST /clients/plan" || bad "POST /clients/plan 返回 $C" # 页面打开时补问模型清单:立刻返回开始问的那几家,不等上游回话 C=$(post /models/refresh '{}'); [ "$C" = "200" ] && ok "POST /models/refresh" || bad "POST /models/refresh 返回 $C" -C=$(curl -s --unix-socket "$SOCK" http://localhost/overview | python3 -c 'import json,sys;p=json.load(sys.stdin)["providers"][0];print(p["model_status"] in ("pending","listed","no_list","failed") and isinstance(p["model_fetching"],bool))') +C=$(curl -s --unix-socket "$SOCK" "${AUTH[@]}" http://localhost/overview | python3 -c 'import json,sys;p=json.load(sys.stdin)["providers"][0];print(p["model_status"] in ("pending","listed","no_list","failed") and isinstance(p["model_fetching"],bool))') [ "$C" = "True" ] && ok "/overview 带模型获取状态" || bad "/overview 的模型状态字段不对:$C" C=$(get /clients/claude-code/why); [ "$C" = "200" ] && ok "GET /clients/{id}/why" || bad "返回 $C" -ID=$(curl -s --unix-socket "$SOCK" "http://localhost/history?limit=1" \ +ID=$(curl -s --unix-socket "$SOCK" "${AUTH[@]}" "http://localhost/history?limit=1" \ | python3 -c 'import json,sys;d=json.load(sys.stdin);print(d[0]["id"] if d else 0)') if [ "$ID" != "0" ]; then C=$(get "/request/$ID"); [ "$C" = "200" ] && ok "GET /request/{id}" || bad "返回 $C"