diff --git a/Cargo.lock b/Cargo.lock index 01ac5df5..426e1d7b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2743,7 +2743,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.57.0" +version = "0.57.1" dependencies = [ "serde", "serde_json", @@ -2753,7 +2753,7 @@ dependencies = [ [[package]] name = "tw-bedrock" -version = "0.57.0" +version = "0.57.1" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -2774,7 +2774,7 @@ dependencies = [ [[package]] name = "tw-breaker" -version = "0.57.0" +version = "0.57.1" dependencies = [ "serde", "serde_json", @@ -2782,7 +2782,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.57.0" +version = "0.57.1" dependencies = [ "blake3", "libc", @@ -2807,7 +2807,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.57.0" +version = "0.57.1" dependencies = [ "axum", "base64", @@ -2847,7 +2847,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.57.0" +version = "0.57.1" dependencies = [ "serde", "serde_json", @@ -2855,7 +2855,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.57.0" +version = "0.57.1" dependencies = [ "serde", "serde_json", @@ -2868,7 +2868,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.57.0" +version = "0.57.1" dependencies = [ "arc-swap", "async-stream", @@ -2916,7 +2916,7 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.57.0" +version = "0.57.1" dependencies = [ "base64", "regex", @@ -2929,7 +2929,7 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.57.0" +version = "0.57.1" dependencies = [ "serde", "serde_json", @@ -2943,7 +2943,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.57.0" +version = "0.57.1" dependencies = [ "tokio", "tracing", @@ -2952,7 +2952,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.57.0" +version = "0.57.1" dependencies = [ "arc-swap", "flate2", @@ -2965,14 +2965,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.57.0" +version = "0.57.1" dependencies = [ "thiserror", ] [[package]] name = "tw-store" -version = "0.57.0" +version = "0.57.1" dependencies = [ "bytes", "rusqlite", @@ -2991,7 +2991,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.57.0" +version = "0.57.1" dependencies = [ "serde", "serde_json", @@ -3000,7 +3000,7 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.57.0" +version = "0.57.1" dependencies = [ "notify", "tempfile", @@ -3010,7 +3010,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.57.0" +version = "0.57.1" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -3020,7 +3020,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.57.0" +version = "0.57.1" dependencies = [ "anyhow", "axum", diff --git a/Cargo.toml b/Cargo.toml index 516ca4f7..28b92669 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,7 +50,7 @@ categories = ["network-programming", "web-programming::http-server"] # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.57.0" +version = "0.57.1" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index 92a67122..d4146dd6 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -237,6 +237,7 @@ gw.listen.denied gw.listen.nic_offline gw.listen.no_such_nic gw.listen.port_taken +gw.method.not_forwarded gw.model.no_upstream gw.model.no_upstream_available gw.model.no_upstream_rewritten diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 8234bf8c..7f53edac 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -50,8 +50,8 @@ pub fn router(state: AppState) -> Router { .route("/v1/files/{*rest}", any(no_files)) .route("/files", any(no_files)) .route("/files/{*rest}", any(no_files)) - // M0 只有透传:任何方法、任何路径都往上游送。M1 加路由时, - // 这里会先过规则引擎再决定送给谁。 + // 其余的路径都交给管线:过规则选上游,再送过去。**只送 POST**,别的方法就地回 + // 404(见 `passthrough`) .fallback(any(passthrough)) .with_state(state) } @@ -63,15 +63,23 @@ pub fn router(state: AppState) -> Router { /// `/v1/files`,失败了就改成内联 base64 —— 404 正是让它退回内联的那个回答,内联的 /// 图片哪家上游都能收(要转换时也转得过去)。 async fn no_files(headers: HeaderMap) -> Response { + not_found( + &headers, + msg!( + "gw.files.unsupported" => + "The gateway does not host files. Send images and documents inline in the request." + ), + ) +} + +/// 就地回 404,错误体照客户端的格式写:带 `anthropic-version` 的按 Anthropic,别的按 +/// Chat Completions。不经过管线,不转发、不记录。 +fn not_found(headers: &HeaderMap, m: tw_types::Msg) -> Response { let dialect = if headers.contains_key("anthropic-version") { tw_dialect::ir::Dialect::Anthropic } else { tw_dialect::ir::Dialect::Chat }; - let m = msg!( - "gw.files.unsupported" => - "The gateway does not host files. Send images and documents inline in the request." - ); let body = tw_dialect::convert::error_body(dialect, 404, &format!("[ThinkWatch] {}", m.text)); let mut resp = (axum::http::StatusCode::NOT_FOUND, body).into_response(); resp.headers_mut().insert( @@ -81,9 +89,12 @@ async fn no_files(headers: HeaderMap) -> Response { resp } +// 参数是 axum 的提取器,一样东西一个 +#[allow(clippy::too_many_arguments)] async fn passthrough( State(state): State, axum::extract::ConnectInfo(peer): axum::extract::ConnectInfo, + method: axum::http::Method, OriginalUri(uri): OriginalUri, RawQuery(query): RawQuery, // **必须排在 `body` 前面。**提取器按顺序跑,而 `Bytes` 会把体吃掉 @@ -141,6 +152,21 @@ async fn passthrough( ) .await; } + // **只有 POST 送往上游。**上游的接口都是 POST,发出去时也一律用 POST(见管线的 + // `hop::send`);别的方法走到这里,是客户端在探路 —— Hermes Agent 起来时拿 GET 挨个问 + // `/api/tags`、`/version` 这些本机模型服务的地址,看网关是不是 Ollama、LM Studio。原来 + // 这些请求被改成空正文的 POST 发给上游,每个都记成一条失败的请求,还在几家上游之间转一圈; + // 上游要是恰好回了 200,客户端还会把网关认成那种服务。它们不是一次调用:就地回 404, + // 不转发、不记录。**放在鉴权之后**:没带密钥的照旧是 401,不让陌生的来访者探出什么 + if method != axum::http::Method::POST { + return Ok(not_found( + &headers, + msg!( + "gw.method.not_forwarded", method = method.as_str(), path = uri.path() => + "{method} {path} is not an API call. The gateway forwards only POST requests to upstreams." + ), + )); + } // 客户端调的是哪种 API:**看路径**(见 `client_api`)。认不出的路径照旧 // 直通,出错时的格式退回按密钥位置猜。 let api = crate::client_api::ClientApi::of_path(uri.path()); diff --git a/crates/tw-gateway/tests/probes.rs b/crates/tw-gateway/tests/probes.rs new file mode 100644 index 00000000..a46dea40 --- /dev/null +++ b/crates/tw-gateway/tests/probes.rs @@ -0,0 +1,191 @@ +//! 不是 POST 的请求在网关就地回 404,不送上游、不记录。 +//! +//! 上游的接口都是 POST,网关发出去时也一律用 POST。别的方法落到透传上,是客户端在探路: +//! Hermes Agent 起来时拿 GET 挨个问 `/api/v1/models`、`/api/tags`、`/v1/props`、`/props`、 +//! `/version`,看网关是不是 LM Studio、Ollama、llama.cpp、vLLM。原来它们被改成空正文的 POST +//! 发给上游,每个都记成一条失败的请求;上游要是回了 200,Hermes 还会把网关认成那种服务。 + +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::Router; +use axum::extract::{OriginalUri, State}; +use reqwest::Method; +use serde_json::{Value, json}; +use tw_config::{Client, Config, Listen, Protocol, Provider}; + +type Log = Arc>>; + +/// 一个假上游:记下收到的每个请求(方法和路径),什么都回 200 —— 最糟的那种上游, +/// 探测要是漏过去,客户端就会把网关认错 +async fn upstream() -> (SocketAddr, Log) { + let log: Log = Arc::new(Mutex::new(Vec::new())); + let app = Router::new() + .fallback( + |State(log): State, method: axum::http::Method, OriginalUri(uri): OriginalUri| async move { + log.lock().unwrap().push((method.to_string(), uri.to_string())); + axum::Json(json!({ + "id": "chatcmpl-1", "object": "chat.completion", "model": "m", + "models": [], "version": "0.0.0", + "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 10, "completion_tokens": 2} + })) + }, + ) + .with_state(log.clone()); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + (addr, log) +} + +async fn gateway(up: SocketAddr) -> (SocketAddr, tokio::sync::broadcast::Receiver) { + let cfg = Config { + version: 1, + listen: Listen::default(), + clients: vec![Client { + name: "c".into(), + key: "tw-k".into(), + ..Default::default() + }], + providers: vec![Provider { + name: "relay".into(), + base_url: format!("http://{up}"), + key: Some("sk-upstream".into()), + protocol: Some(Protocol::OpenaiChat), + ..Default::default() + }], + ..Default::default() + }; + let state = tw_gateway::AppState::new(cfg).unwrap(); + let rx = state.bus.subscribe(); + let addr = tw_gateway::serve(state, ([127, 0, 0, 1], 0).into()) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + (addr, rx) +} + +/// 总线上说到请求的那些事件(开始、结局)。别的(熔断、模型清单)不算 +fn request_events(rx: &mut tokio::sync::broadcast::Receiver) -> Vec { + let mut out = Vec::new(); + while let Ok(ev) = rx.try_recv() { + let v = serde_json::to_value(&ev).unwrap(); + let kind = v["kind"].as_str().unwrap_or_default().to_string(); + if kind.starts_with("request_") { + out.push(kind); + } + } + out +} + +#[tokio::test] +async fn local_server_probes_get_a_404_from_the_gateway_itself() { + let (up, log) = upstream().await; + let (gw, mut rx) = gateway(up).await; + let http = reqwest::Client::new(); + for path in [ + "/api/v1/models", + "/api/tags", + "/v1/props", + "/props", + "/version", + ] { + let resp = http + .get(format!("http://{gw}{path}")) + .header("authorization", "Bearer tw-k") + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 404, "{path}"); + let v: Value = resp.json().await.unwrap(); + assert_eq!(v["error"]["type"], "not_found_error", "{path}: {v}"); + let message = v["error"]["message"].as_str().unwrap(); + assert!(message.starts_with("[ThinkWatch] GET "), "{path}: {v}"); + } + tokio::time::sleep(Duration::from_millis(100)).await; + assert!( + log.lock().unwrap().is_empty(), + "a probe reached the upstream: {:?}", + log.lock().unwrap() + ); + assert_eq!( + request_events(&mut rx), + Vec::::new(), + "a probe was recorded as a request" + ); +} + +#[tokio::test] +async fn no_method_but_post_is_forwarded() { + let (up, log) = upstream().await; + let (gw, mut rx) = gateway(up).await; + let http = reqwest::Client::new(); + for (method, path) in [ + (Method::GET, "/v1/chat/completions"), + (Method::HEAD, "/api/tags"), + (Method::OPTIONS, "/v1/messages"), + (Method::DELETE, "/v1/responses/resp_1"), + (Method::PUT, "/v1/chat/completions"), + ] { + let resp = http + .request(method.clone(), format!("http://{gw}{path}")) + .header("authorization", "Bearer tw-k") + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 404, "{method} {path}"); + } + tokio::time::sleep(Duration::from_millis(100)).await; + assert!(log.lock().unwrap().is_empty(), "{:?}", log.lock().unwrap()); + assert_eq!(request_events(&mut rx), Vec::::new()); + + // POST 照常送到上游、照常记录 + let resp = http + .post(format!("http://{gw}/v1/chat/completions")) + .header("authorization", "Bearer tw-k") + .json(&json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]})) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 200, "{}", resp.text().await.unwrap()); + assert_eq!( + *log.lock().unwrap(), + vec![("POST".to_string(), "/v1/chat/completions".to_string())] + ); + tokio::time::sleep(Duration::from_millis(100)).await; + assert!(request_events(&mut rx).contains(&"request_started".to_string())); +} + +/// 没带密钥的照旧是 401:陌生的来访者探不出网关会怎么回 +#[tokio::test] +async fn a_probe_without_a_key_is_still_turned_away() { + let (up, log) = upstream().await; + let (gw, _rx) = gateway(up).await; + let resp = reqwest::Client::new() + .get(format!("http://{gw}/api/tags")) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 401); + assert!(log.lock().unwrap().is_empty()); +} + +/// 带 `anthropic-version` 的按 Anthropic 的格式回错误,外面多一层 `type` +#[tokio::test] +async fn the_404_speaks_the_clients_format() { + let (up, _log) = upstream().await; + let (gw, _rx) = gateway(up).await; + let resp = reqwest::Client::new() + .get(format!("http://{gw}/v1/messages")) + .header("x-api-key", "tw-k") + .header("anthropic-version", "2023-06-01") + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 404); + let v: Value = resp.json().await.unwrap(); + assert_eq!(v["type"], "error", "{v}"); + assert_eq!(v["error"]["type"], "not_found_error", "{v}"); +} diff --git a/release-notes/0.57.1.md b/release-notes/0.57.1.md new file mode 100644 index 00000000..1b6504b5 --- /dev/null +++ b/release-notes/0.57.1.md @@ -0,0 +1,13 @@ +This release answers requests other than POST in the gateway itself. Before, they were forwarded to an upstream and recorded as failed requests, so a client checking whether the gateway is a local model server sent those checks on to the upstreams. + +**Upgrade notes** + +- The control-plane protocol version is unchanged (31) and so is the request store's schema (23). ThinkWatch Lite 2026.9.26 includes 0.56.0 (protocol 30) and does not connect to 0.57.x: a server used with it stays on 0.56.0 until the app is updated to a release that includes 0.57.1. +- One message code is added: `gw.method.not_forwarded`. +- A GET, HEAD, OPTIONS, PUT or DELETE to a path the gateway does not serve itself now gets a 404 from the gateway instead of whatever the upstream answered to an empty POST. + +**Requests other than POST.** Every upstream API the gateway forwards to takes POST, and the gateway always sent the upstream request as POST. Any other method that reached the catch-all route was sent on as an empty POST, recorded as a failed request and, with failover, tried on the next upstreams. +- Hermes Agent sends five such GETs when it starts (`/api/v1/models`, `/api/tags`, `/v1/props`, `/props`, `/version`) to tell whether a server is LM Studio, Ollama, llama.cpp or vLLM. +- An upstream that answered one of them with 200 made Hermes take the gateway for that kind of server. + +These requests now get a 404 in the client's error format, after the key check, and are neither forwarded nor recorded. A request without a key still gets 401. `/v1/models`, `/v1beta/models`, `/api/hello`, `/healthz` and WebSocket upgrades are unchanged.