diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 0b157836..8ad47065 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -75,6 +75,11 @@ pub enum Event { /// 而「隔了多久」要看上一条是什么时候,那是 recorder 的活。 #[serde(default, skip_serializing_if = "Option::is_none")] session_fp: Option, + /// 请求从哪台机器来:**这条连接对面的地址**,不可伪造。本机(回环) + /// 来的不记 —— 那是绝大多数请求,写上只是噪音;局域网来的才值得 + /// 说一句「来自 192.168.1.23」。几台机器共用一把密钥时,只有它分得开 + #[serde(default, skip_serializing_if = "Option::is_none")] + peer: Option, provider: String, /// 客户端要的模型名。**成本要靠它查价**,而它只在请求体里 —— /// 少了这个字段,落库那一步就只能记一笔没有模型的账 @@ -456,6 +461,15 @@ pub enum Event { LocallyAnswered { id: u64, client: String, + /// 请求头透出来的旁证,同 `RequestStarted` + #[serde(default, skip_serializing_if = "Option::is_none")] + client_hint: Option, + /// 请求从哪台机器来:**这条连接对面的地址**,不可伪造。本机(回环) + /// 来的不记 —— 那是绝大多数请求,写上只是噪音;局域网来的才值得 + /// 说一句「来自 192.168.1.23」。几台机器共用一把密钥时,只有它分得开 + #[serde(default, skip_serializing_if = "Option::is_none")] + peer: Option, + /// 哪一类辅助请求,和 `ProbeView.id` 同一个词表。字段叫 `probe` 而 /// 不是 `kind` —— 那个名字已经被枚举的 tag 占了 probe: String, @@ -1915,6 +1929,13 @@ pub struct HistoryRow { /// 认不出会话的请求(拼不出指纹的、老记录)是 `None`。 #[serde(default, skip_serializing_if = "Option::is_none")] pub session: Option, + /// 按请求头推测是哪个应用发的(`claude-code`、`codex`…)。**可以伪造**, + /// 只用来显示;身份是 `client` 那把密钥 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_hint: Option, + /// 非本机来的请求的来源地址。本机来的没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub peer: Option, /// 这次请求在两项防护上留下的记录(和安全日志同一份)。没有就是空的。 /// /// **流量页的徽标靠它。**以前徽标只来自实时事件,关窗再开就没了 —— @@ -2717,6 +2738,13 @@ pub struct SecurityEventView { pub excerpt: String, /// 出站脱敏:这个值在请求里出现了几次 pub count: i64, + /// 按请求头推测是哪个应用发的(`claude-code`、`codex`…)。**可以伪造**, + /// 只用来显示;身份是 `client` 那把密钥 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_hint: Option, + /// 非本机来的请求的来源地址。本机来的没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub peer: Option, } /// 安全日志的一页。**按时间倒序**,`more` 说后面还有没有。 @@ -2899,6 +2927,7 @@ mod tests { // UI 靠 id 把四个事件缝成一行。 for e in [ Event::RequestStarted { + peer: None, id: 7, client: "c".into(), client_hint: None, diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index ae099c0a..f7f68985 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -1002,6 +1002,8 @@ fn history_row( .as_deref() .and_then(|j| serde_json::from_str(j).ok()), session: r.session, + client_hint: r.client_hint, + peer: r.peer, security, } } diff --git a/crates/tw-control/tests/adopt.rs b/crates/tw-control/tests/adopt.rs index 1128f1b9..fe7aa754 100644 --- a/crates/tw-control/tests/adopt.rs +++ b/crates/tw-control/tests/adopt.rs @@ -444,6 +444,7 @@ async fn replaying_a_truncated_body_is_refused_rather_than_misleading() { let db = tw_store::Db::open(&d.path().join("data.db")).unwrap(); let blobs = tw_store::Blobs::new(d.path().join("blobs")); let mut row = tw_store::db::RequestRow { + peer: None, id: 1, at_ms: 1000, client: "我".into(), diff --git a/crates/tw-control/tests/in_flight.rs b/crates/tw-control/tests/in_flight.rs index 513525f6..215fffa7 100644 --- a/crates/tw-control/tests/in_flight.rs +++ b/crates/tw-control/tests/in_flight.rs @@ -34,6 +34,7 @@ fn app() -> (tempfile::TempDir, tw_observe::EventBus, axum::Router) { fn started(id: u64, model: &str) -> tw_api::Event { tw_api::Event::RequestStarted { + peer: None, id, client: "我".into(), client_hint: Some("claude-code".into()), diff --git a/crates/tw-control/tests/security.rs b/crates/tw-control/tests/security.rs index 0f031146..d0838baf 100644 --- a/crates/tw-control/tests/security.rs +++ b/crates/tw-control/tests/security.rs @@ -41,6 +41,7 @@ impl Bed { fn request(id: i64, at_ms: i64, provider: &str) -> tw_store::db::RequestRow { tw_store::db::RequestRow { + peer: None, id, at_ms, client: "default".into(), @@ -617,7 +618,11 @@ async fn trying_a_tool_call_says_what_enforce_would_do_with_it() { #[tokio::test] async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request() { let b = bed_with(BASE, |db| { - db.insert(&request(1, 1_000, "中转")).unwrap(); + // 局域网里另一台机器,看样子是 Claude Code 发的 + let mut r = request(1, 1_000, "中转"); + r.peer = Some("192.168.1.23".into()); + r.client_hint = Some("claude-code".into()); + db.insert(&r).unwrap(); db.insert_security_event(&event(1, 1_001, "redact", "anthropic-api-key", "recorded")) .unwrap(); db.insert_security_event(&event(1, 1_002, "inspect_tools", "curl-pipe-sh", "cut")) @@ -645,6 +650,12 @@ async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request( ); assert_eq!(events[1]["model"], "claude-sonnet-4-5"); assert_eq!(events[1]["tool"], "Bash"); + // 是谁发的:密钥是身份,应用是旁证,来源是这条连接对面的地址 + assert_eq!(events[1]["client"], "default"); + assert_eq!(events[1]["client_hint"], "claude-code"); + assert_eq!(events[1]["peer"], "192.168.1.23"); + // 本机来的、还没落库的,都没有来源 + assert!(events[0].get("peer").is_none(), "{}", events[0]); let before = events[1]["id"].as_i64().unwrap(); let (_, v) = call( diff --git a/crates/tw-control/tests/sessions.rs b/crates/tw-control/tests/sessions.rs index 9d02c0ee..e2cadbc6 100644 --- a/crates/tw-control/tests/sessions.rs +++ b/crates/tw-control/tests/sessions.rs @@ -17,6 +17,7 @@ const BASE: &str = "version: 1\nclients:\n - name: 我\n key: tw-一把钥 fn turn(id: i64, billing: &str) -> tw_store::db::RequestRow { let per_token = billing == "per-token"; tw_store::db::RequestRow { + peer: None, id, at_ms: 1000 + id, client: "codex".into(), diff --git a/crates/tw-gateway/src/hint.rs b/crates/tw-gateway/src/hint.rs index f27e1ef6..5da2792b 100644 --- a/crates/tw-gateway/src/hint.rs +++ b/crates/tw-gateway/src/hint.rs @@ -52,6 +52,16 @@ pub fn client_hint(headers: &HeaderMap) -> Option { None } +/// 请求从哪台机器来。**本机(回环)来的不记** —— 那是绝大多数请求,写上 +/// 只是噪音;局域网来的才值得说一句「来自 192.168.1.23」。 +/// +/// 和上面的旁证不是一类东西:它是这条 TCP 连接对面的地址,**不能伪造**。 +/// 几台机器共用一把网关密钥时,只有它分得开是哪台发的。 +pub fn peer_of(ip: std::net::IpAddr) -> Option { + let ip = ip.to_canonical(); + (!ip.is_loopback()).then(|| ip.to_string()) +} + #[cfg(test)] mod tests { use super::*; @@ -110,4 +120,18 @@ mod tests { let got = client_hint(&h(&[(OURS, &long)])).unwrap(); assert!(got.chars().count() <= 40, "{}", got.len()); } + + #[test] + fn only_a_request_from_another_machine_has_a_peer() { + let ip = |s: &str| s.parse::().unwrap(); + assert_eq!(peer_of(ip("127.0.0.1")), None); + assert_eq!(peer_of(ip("::1")), None); + // 双栈监听时本机连过来是 IPv4 映射的 IPv6,也是本机 + assert_eq!(peer_of(ip("::ffff:127.0.0.1")), None); + assert_eq!(peer_of(ip("192.168.1.23")).as_deref(), Some("192.168.1.23")); + assert_eq!( + peer_of(ip("::ffff:192.168.1.23")).as_deref(), + Some("192.168.1.23") + ); + } } diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 860fab07..6e71d17f 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -1018,6 +1018,7 @@ async fn ws_upgrade( headers: HeaderMap, started: std::time::Instant, live: crate::live::Pass, + peer: Option, ) -> Result { // 升级请求没有体,所以性质里只有客户端名字 —— 按模型路由的规则 // 对它不适用,而那是对的:这条连接上会跑什么模型,现在还不知道 @@ -1075,6 +1076,7 @@ async fn ws_upgrade( client: client_name, client_hint: crate::hint::client_hint(&headers), session_fp: None, + peer, provider: name.clone(), model: String::new(), method: "WS".to_string(), @@ -1292,6 +1294,8 @@ async fn passthrough( )); } let (client_name, position) = state.identify(&headers, query.as_deref())?; + // 请求从哪台机器来。本机来的是 None + let from = crate::hint::peer_of(peer.ip()); // WebSocket 升级。**在鉴权之后、解体之前分叉** —— 鉴权 // 在前是因为一个不该连过来的地址不该有机会升级;解体之前是因为 // 升级要的是那条连接,而 `Bytes` 会把它读干净。 @@ -1306,6 +1310,7 @@ async fn passthrough( headers, started, live, + from, ) .await; } @@ -1342,6 +1347,7 @@ async fn passthrough( dialect, started, live, + from, &mut ending, ) .await; @@ -1423,6 +1429,7 @@ async fn pipeline( dialect: crate::error::Dialect, started: std::time::Instant, live: crate::live::Pass, + peer: Option, ending: &mut Option, ) -> Result { forward::check_body_size(&body, MAX_BODY)?; @@ -1447,6 +1454,8 @@ async fn pipeline( state.bus.emit(tw_api::Event::LocallyAnswered { id, client: client_name.clone(), + client_hint: crate::hint::client_hint(&headers), + peer: peer.clone(), probe: kind.slug().to_string(), at_ms: now_ms(), }); @@ -1645,6 +1654,7 @@ async fn pipeline( // 认出「这几十个请求是同一次任务」。**认不出来就是 // None** —— 硬凑一个会把互不相干的请求并成一个「会话」 session_fp: parsed.as_ref().and_then(crate::session::fingerprint), + peer, provider: alive.first().map(|s| s.as_str()).unwrap_or("?").to_string(), model: facts.model.clone(), method: "POST".to_string(), diff --git a/crates/tw-observe/src/bus.rs b/crates/tw-observe/src/bus.rs index c8745501..bb5d7efe 100644 --- a/crates/tw-observe/src/bus.rs +++ b/crates/tw-observe/src/bus.rs @@ -134,6 +134,7 @@ mod tests { fn started(id: u64) -> tw_api::Event { tw_api::Event::RequestStarted { + peer: None, id, client: "c".into(), client_hint: None, diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index 26f3446e..6857564d 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -17,7 +17,7 @@ use rusqlite::{Connection, OptionalExtension, params}; use tw_api::Msg; /// 当前 schema 版本。**加字段就加一,并在 `migrate` 里补一步。** -const SCHEMA: i64 = 14; +const SCHEMA: i64 = 15; /// 这一行算不出钱,**因为价目表里没有这个模型**:用量是有的,缺的是单价。 /// @@ -80,6 +80,8 @@ pub struct RequestRow { /// 请求头透出来的旁证。**可以伪造** —— 只用来显示和判断接管有没有 /// 生效,从不参与鉴权、路由或配额 pub client_hint: Option, + /// 非本机来的请求的来源地址(这条连接对面的地址)。本机来的是 None + pub peer: Option, /// 这条属于哪一次任务。**指纹 + 起始时刻**,老记录是 None pub session: Option, pub provider: String, @@ -388,6 +390,12 @@ impl Db { ALTER TABLE requests DROP COLUMN tool_calls;", )?; } + if from < 15 { + // 请求从哪台机器来。**网关开给局域网之后**,几台机器共用一把密钥 + // 时只有它分得开是谁发的;本机来的留空 + self.conn + .execute_batch("ALTER TABLE requests ADD COLUMN peer TEXT;")?; + } self.conn.pragma_update(None, "user_version", SCHEMA)?; Ok(()) } @@ -400,8 +408,8 @@ impl Db { input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_micros, cost_estimated, error, local, routing, billing, cache_saved_micros, client_hint, session, cancelled, price_source, translated, - error_code, error_args) - VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,?25,?26,?27,?28)", + error_code, error_args, peer) + VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,?25,?26,?27,?28,?29)", params![ r.id, r.at_ms, @@ -434,6 +442,7 @@ impl Db { .as_ref() .filter(|e| !e.args.is_empty()) .map(|e| serde_json::to_string(&e.args).unwrap_or_default()), + r.peer, ], )?; Ok(()) @@ -1170,6 +1179,7 @@ fn row_from(r: &rusqlite::Row) -> rusqlite::Result { at_ms: r.get("at_ms")?, client: r.get("client")?, client_hint: r.get("client_hint")?, + peer: r.get("peer")?, session: r.get("session")?, provider: r.get("provider")?, model: r.get("model")?, @@ -1255,7 +1265,8 @@ const SECURITY_SELECT: &str = COALESCE(NULLIF(r.provider, ''), e.provider), COALESCE(NULLIF(r.client, ''), e.client), COALESCE(r.model, ''), - e.tool, e.excerpt, e.count + e.tool, e.excerpt, e.count, + r.client_hint, r.peer FROM security_events e LEFT JOIN requests r ON r.id = e.request_id"; fn security_view(r: &rusqlite::Row) -> rusqlite::Result { @@ -1273,6 +1284,8 @@ fn security_view(r: &rusqlite::Row) -> rusqlite::Result RequestRow { RequestRow { + peer: None, client_hint: None, session: None, id, @@ -1824,6 +1838,7 @@ pub(crate) mod tests { db.conn .execute_batch( "DROP INDEX requests_session; + ALTER TABLE requests DROP COLUMN peer; ALTER TABLE requests DROP COLUMN error_args; ALTER TABLE requests DROP COLUMN error_code; ALTER TABLE requests DROP COLUMN translated; @@ -1864,13 +1879,17 @@ pub(crate) mod tests { assert!(got.iter().all(|r| r.price_source.is_none())); // 老记录没有落库的转换,那就是没有 assert!(got.iter().all(|r| r.translated.is_none())); + // 老记录不知道从哪台机器来,那就是没有 —— 不是「本机」 + assert!(got.iter().all(|r| r.peer.is_none())); let mut fresh = row(3, 300); fresh.client_hint = Some("codex".into()); fresh.session = Some("abc-100".into()); + fresh.peer = Some("192.168.1.23".into()); db.insert(&fresh).unwrap(); let back = &db.recent(None, 1).unwrap()[0]; assert_eq!(back.client_hint.as_deref(), Some("codex")); assert_eq!(back.session.as_deref(), Some("abc-100")); + assert_eq!(back.peer.as_deref(), Some("192.168.1.23")); } #[test] diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index a41afa06..de170807 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -20,6 +20,7 @@ struct Partial { at_ms: i64, client: String, client_hint: Option, + peer: Option, session: Option, provider: String, model: String, @@ -166,6 +167,7 @@ impl Recorder { client, client_hint, session_fp, + peer, provider, model, path, @@ -186,6 +188,7 @@ impl Recorder { at_ms: *at_ms as i64, client: client.clone(), client_hint: client_hint.clone(), + peer: peer.clone(), session, provider: provider.clone(), model: model.clone(), @@ -396,6 +399,8 @@ impl Recorder { Event::LocallyAnswered { id, client, + client_hint, + peer, probe, at_ms, } => { @@ -405,8 +410,9 @@ impl Recorder { id: *id as i64, at_ms: *at_ms as i64, client: client.clone(), - // 本地应答的探测请求没经过上游,也就没有旁证可言 - client_hint: None, + // 没经过上游,但请求是客户端发来的:旁证和来源照样有 + client_hint: client_hint.clone(), + peer: peer.clone(), session: None, provider: String::new(), model: String::new(), @@ -544,6 +550,7 @@ impl Recorder { at_ms: p.at_ms, client: p.client, client_hint: p.client_hint, + peer: p.peer, session: p.session, provider: p.provider, model: p.model, @@ -615,6 +622,7 @@ mod tests { pub(super) fn started(id: u64, model: &str) -> Event { Event::RequestStarted { + peer: None, id, client_hint: None, session_fp: None, @@ -891,6 +899,8 @@ mod tests { fn a_locally_answered_probe_is_marked_local() { let (_d, mut r) = rec(); r.on_event(&Event::LocallyAnswered { + client_hint: None, + peer: None, id: 9, client: "claude-code".into(), probe: "连通性检查".into(), @@ -1534,6 +1544,7 @@ mod cancellation_tests { fn a_cancelled_turn_says_so_in_its_session() { let (_d, mut r) = rec(); r.on_event(&Event::RequestStarted { + peer: None, id: 1, client: "claude-code".into(), client_hint: None, diff --git a/crates/tw-store/tests/m3_acceptance.rs b/crates/tw-store/tests/m3_acceptance.rs index fbab1e21..57819a5d 100644 --- a/crates/tw-store/tests/m3_acceptance.rs +++ b/crates/tw-store/tests/m3_acceptance.rs @@ -24,6 +24,7 @@ const NOW: i64 = 1_800_000_000_000; fn req(id: i64, at_ms: i64) -> RequestRow { RequestRow { + peer: None, id, at_ms, client: "claude-code".into(),