Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ pub enum Event {
/// 而「隔了多久」要看上一条是什么时候,那是 recorder 的活。
#[serde(default, skip_serializing_if = "Option::is_none")]
session_fp: Option<String>,
/// 请求从哪台机器来:**这条连接对面的地址**,不可伪造。本机(回环)
/// 来的不记 —— 那是绝大多数请求,写上只是噪音;局域网来的才值得
/// 说一句「来自 192.168.1.23」。几台机器共用一把密钥时,只有它分得开
#[serde(default, skip_serializing_if = "Option::is_none")]
peer: Option<String>,
provider: String,
/// 客户端要的模型名。**成本要靠它查价**,而它只在请求体里 ——
/// 少了这个字段,落库那一步就只能记一笔没有模型的账
Expand Down Expand Up @@ -456,6 +461,15 @@ pub enum Event {
LocallyAnswered {
id: u64,
client: String,
/// 请求头透出来的旁证,同 `RequestStarted`
#[serde(default, skip_serializing_if = "Option::is_none")]
client_hint: Option<String>,
/// 请求从哪台机器来:**这条连接对面的地址**,不可伪造。本机(回环)
/// 来的不记 —— 那是绝大多数请求,写上只是噪音;局域网来的才值得
/// 说一句「来自 192.168.1.23」。几台机器共用一把密钥时,只有它分得开
#[serde(default, skip_serializing_if = "Option::is_none")]
peer: Option<String>,

/// 哪一类辅助请求,和 `ProbeView.id` 同一个词表。字段叫 `probe` 而
/// 不是 `kind` —— 那个名字已经被枚举的 tag 占了
probe: String,
Expand Down Expand Up @@ -1915,6 +1929,13 @@ pub struct HistoryRow {
/// 认不出会话的请求(拼不出指纹的、老记录)是 `None`。
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session: Option<String>,
/// 按请求头推测是哪个应用发的(`claude-code`、`codex`…)。**可以伪造**,
/// 只用来显示;身份是 `client` 那把密钥
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_hint: Option<String>,
/// 非本机来的请求的来源地址。本机来的没有
#[serde(default, skip_serializing_if = "Option::is_none")]
pub peer: Option<String>,
/// 这次请求在两项防护上留下的记录(和安全日志同一份)。没有就是空的。
///
/// **流量页的徽标靠它。**以前徽标只来自实时事件,关窗再开就没了 ——
Expand Down Expand Up @@ -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<String>,
/// 非本机来的请求的来源地址。本机来的没有
#[serde(default, skip_serializing_if = "Option::is_none")]
pub peer: Option<String>,
}

/// 安全日志的一页。**按时间倒序**,`more` 说后面还有没有。
Expand Down Expand Up @@ -2899,6 +2927,7 @@ mod tests {
// UI 靠 id 把四个事件缝成一行。
for e in [
Event::RequestStarted {
peer: None,
id: 7,
client: "c".into(),
client_hint: None,
Expand Down
2 changes: 2 additions & 0 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/adopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/in_flight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down
13 changes: 12 additions & 1 deletion crates/tw-control/tests/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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"))
Expand Down Expand Up @@ -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(
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
24 changes: 24 additions & 0 deletions crates/tw-gateway/src/hint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,16 @@ pub fn client_hint(headers: &HeaderMap) -> Option<String> {
None
}

/// 请求从哪台机器来。**本机(回环)来的不记** —— 那是绝大多数请求,写上
/// 只是噪音;局域网来的才值得说一句「来自 192.168.1.23」。
///
/// 和上面的旁证不是一类东西:它是这条 TCP 连接对面的地址,**不能伪造**。
/// 几台机器共用一把网关密钥时,只有它分得开是哪台发的。
pub fn peer_of(ip: std::net::IpAddr) -> Option<String> {
let ip = ip.to_canonical();
(!ip.is_loopback()).then(|| ip.to_string())
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -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::<std::net::IpAddr>().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")
);
}
}
10 changes: 10 additions & 0 deletions crates/tw-gateway/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1018,6 +1018,7 @@ async fn ws_upgrade(
headers: HeaderMap,
started: std::time::Instant,
live: crate::live::Pass,
peer: Option<String>,
) -> Result<Response, GatewayError> {
// 升级请求没有体,所以性质里只有客户端名字 —— 按模型路由的规则
// 对它不适用,而那是对的:这条连接上会跑什么模型,现在还不知道
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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` 会把它读干净。
Expand All @@ -1306,6 +1310,7 @@ async fn passthrough(
headers,
started,
live,
from,
)
.await;
}
Expand Down Expand Up @@ -1342,6 +1347,7 @@ async fn passthrough(
dialect,
started,
live,
from,
&mut ending,
)
.await;
Expand Down Expand Up @@ -1423,6 +1429,7 @@ async fn pipeline(
dialect: crate::error::Dialect,
started: std::time::Instant,
live: crate::live::Pass,
peer: Option<String>,
ending: &mut Option<crate::ending::Ending>,
) -> Result<Response, GatewayError> {
forward::check_body_size(&body, MAX_BODY)?;
Expand All @@ -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(),
});
Expand Down Expand Up @@ -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(),
Expand Down
1 change: 1 addition & 0 deletions crates/tw-observe/src/bus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
27 changes: 23 additions & 4 deletions crates/tw-store/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use rusqlite::{Connection, OptionalExtension, params};
use tw_api::Msg;

/// 当前 schema 版本。**加字段就加一,并在 `migrate` 里补一步。**
const SCHEMA: i64 = 14;
const SCHEMA: i64 = 15;

/// 这一行算不出钱,**因为价目表里没有这个模型**:用量是有的,缺的是单价。
///
Expand Down Expand Up @@ -80,6 +80,8 @@ pub struct RequestRow {
/// 请求头透出来的旁证。**可以伪造** —— 只用来显示和判断接管有没有
/// 生效,从不参与鉴权、路由或配额
pub client_hint: Option<String>,
/// 非本机来的请求的来源地址(这条连接对面的地址)。本机来的是 None
pub peer: Option<String>,
/// 这条属于哪一次任务。**指纹 + 起始时刻**,老记录是 None
pub session: Option<String>,
pub provider: String,
Expand Down Expand Up @@ -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(())
}
Expand All @@ -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,
Expand Down Expand Up @@ -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(())
Expand Down Expand Up @@ -1170,6 +1179,7 @@ fn row_from(r: &rusqlite::Row) -> rusqlite::Result<RequestRow> {
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")?,
Expand Down Expand Up @@ -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<tw_api::SecurityEventView> {
Expand All @@ -1273,6 +1284,8 @@ fn security_view(r: &rusqlite::Row) -> rusqlite::Result<tw_api::SecurityEventVie
tool: r.get(10)?,
excerpt: r.get(11)?,
count: r.get(12)?,
client_hint: r.get(13)?,
peer: r.get(14)?,
})
}

Expand All @@ -1291,6 +1304,7 @@ pub(crate) mod tests {

pub(crate) fn row(id: i64, at_ms: i64) -> RequestRow {
RequestRow {
peer: None,
client_hint: None,
session: None,
id,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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]
Expand Down
Loading
Loading