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
15 changes: 15 additions & 0 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ pub enum Event {
/// 说一句「来自 192.168.1.23」。几台机器共用一把密钥时,只有它分得开
#[serde(default, skip_serializing_if = "Option::is_none")]
peer: Option<String>,
/// 请求带的那把网关密钥打码后的样子(`tw-re…wb4e`)。**记的是请求那一刻
/// 用的那把** —— 密钥更换过之后,老记录上的尾巴照样对得上
#[serde(default, skip_serializing_if = "Option::is_none")]
key_masked: Option<String>,
provider: String,
/// 客户端要的模型名。**成本要靠它查价**,而它只在请求体里 ——
/// 少了这个字段,落库那一步就只能记一笔没有模型的账
Expand Down Expand Up @@ -469,6 +473,10 @@ pub enum Event {
/// 说一句「来自 192.168.1.23」。几台机器共用一把密钥时,只有它分得开
#[serde(default, skip_serializing_if = "Option::is_none")]
peer: Option<String>,
/// 请求带的那把网关密钥打码后的样子(`tw-re…wb4e`)。**记的是请求那一刻
/// 用的那把** —— 密钥更换过之后,老记录上的尾巴照样对得上
#[serde(default, skip_serializing_if = "Option::is_none")]
key_masked: Option<String>,

/// 哪一类辅助请求,和 `ProbeView.id` 同一个词表。字段叫 `probe` 而
/// 不是 `kind` —— 那个名字已经被枚举的 tag 占了
Expand Down Expand Up @@ -1936,6 +1944,9 @@ pub struct HistoryRow {
/// 非本机来的请求的来源地址。本机来的没有
#[serde(default, skip_serializing_if = "Option::is_none")]
pub peer: Option<String>,
/// 请求带的那把网关密钥打码后的样子(`tw-re…wb4e`),请求那一刻的
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_masked: Option<String>,
/// 这次请求在两项防护上留下的记录(和安全日志同一份)。没有就是空的。
///
/// **流量页的徽标靠它。**以前徽标只来自实时事件,关窗再开就没了 ——
Expand Down Expand Up @@ -2745,6 +2756,9 @@ pub struct SecurityEventView {
/// 非本机来的请求的来源地址。本机来的没有
#[serde(default, skip_serializing_if = "Option::is_none")]
pub peer: Option<String>,
/// 请求带的那把网关密钥打码后的样子(`tw-re…wb4e`),请求那一刻的
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_masked: Option<String>,
}

/// 安全日志的一页。**按时间倒序**,`more` 说后面还有没有。
Expand Down Expand Up @@ -2927,6 +2941,7 @@ mod tests {
// UI 靠 id 把四个事件缝成一行。
for e in [
Event::RequestStarted {
key_masked: None,
peer: None,
id: 7,
client: "c".into(),
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1004,6 +1004,7 @@ fn history_row(
session: r.session,
client_hint: r.client_hint,
peer: r.peer,
key_masked: r.key_masked,
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 {
key_masked: None,
peer: None,
id: 1,
at_ms: 1000,
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 {
key_masked: None,
peer: None,
id,
client: "我".into(),
Expand Down
3 changes: 3 additions & 0 deletions 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 {
key_masked: None,
peer: None,
id,
at_ms,
Expand Down Expand Up @@ -622,6 +623,7 @@ async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request(
let mut r = request(1, 1_000, "中转");
r.peer = Some("192.168.1.23".into());
r.client_hint = Some("claude-code".into());
r.key_masked = Some("tw-re…wb4e".into());
db.insert(&r).unwrap();
db.insert_security_event(&event(1, 1_001, "redact", "anthropic-api-key", "recorded"))
.unwrap();
Expand Down Expand Up @@ -654,6 +656,7 @@ async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request(
assert_eq!(events[1]["client"], "default");
assert_eq!(events[1]["client_hint"], "claude-code");
assert_eq!(events[1]["peer"], "192.168.1.23");
assert_eq!(events[1]["key_masked"], "tw-re…wb4e");
// 本机来的、还没落库的,都没有来源
assert!(events[0].get("peer").is_none(), "{}", events[0]);

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 {
key_masked: None,
peer: None,
id,
at_ms: 1000 + id,
Expand Down
35 changes: 28 additions & 7 deletions crates/tw-gateway/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1018,7 +1018,7 @@ async fn ws_upgrade(
headers: HeaderMap,
started: std::time::Instant,
live: crate::live::Pass,
peer: Option<String>,
from: Sender,
) -> Result<Response, GatewayError> {
// 升级请求没有体,所以性质里只有客户端名字 —— 按模型路由的规则
// 对它不适用,而那是对的:这条连接上会跑什么模型,现在还不知道
Expand Down Expand Up @@ -1076,7 +1076,8 @@ async fn ws_upgrade(
client: client_name,
client_hint: crate::hint::client_hint(&headers),
session_fp: None,
peer,
peer: from.peer,
key_masked: from.key,
provider: name.clone(),
model: String::new(),
method: "WS".to_string(),
Expand Down Expand Up @@ -1294,8 +1295,16 @@ async fn passthrough(
));
}
let (client_name, position) = state.identify(&headers, query.as_deref())?;
// 请求从哪台机器来。本机来的是 None
let from = crate::hint::peer_of(peer.ip());
// 除了密钥的名字,这条请求是谁发的
let from = Sender {
peer: crate::hint::peer_of(peer.ip()),
key: rt
.config
.clients
.iter()
.find(|c| c.name == client_name)
.map(|c| tw_secret::mask_secret(&c.key)),
};
// WebSocket 升级。**在鉴权之后、解体之前分叉** —— 鉴权
// 在前是因为一个不该连过来的地址不该有机会升级;解体之前是因为
// 升级要的是那条连接,而 `Bytes` 会把它读干净。
Expand Down Expand Up @@ -1416,6 +1425,16 @@ fn note_health(
});
}

/// 这条请求是谁发的:密钥的名字之外的两样。**记下的是请求那一刻的** ——
/// 密钥换过之后,老记录上的尾巴照样对得上。
#[derive(Debug, Clone, Default)]
struct Sender {
/// 这条连接对面的地址。本机来的是 None(见 `hint::peer_of`)
peer: Option<String>,
/// 请求带的那把网关密钥打码后的样子(`tw-re…wb4e`)
key: Option<String>,
}

#[allow(clippy::too_many_arguments)]
async fn pipeline(
state: AppState,
Expand All @@ -1429,7 +1448,7 @@ async fn pipeline(
dialect: crate::error::Dialect,
started: std::time::Instant,
live: crate::live::Pass,
peer: Option<String>,
from: Sender,
ending: &mut Option<crate::ending::Ending>,
) -> Result<Response, GatewayError> {
forward::check_body_size(&body, MAX_BODY)?;
Expand All @@ -1455,7 +1474,8 @@ async fn pipeline(
id,
client: client_name.clone(),
client_hint: crate::hint::client_hint(&headers),
peer: peer.clone(),
peer: from.peer.clone(),
key_masked: from.key.clone(),
probe: kind.slug().to_string(),
at_ms: now_ms(),
});
Expand Down Expand Up @@ -1654,7 +1674,8 @@ async fn pipeline(
// 认出「这几十个请求是同一次任务」。**认不出来就是
// None** —— 硬凑一个会把互不相干的请求并成一个「会话」
session_fp: parsed.as_ref().and_then(crate::session::fingerprint),
peer,
peer: from.peer,
key_masked: from.key,
provider: alive.first().map(|s| s.as_str()).unwrap_or("?").to_string(),
model: facts.model.clone(),
method: "POST".to_string(),
Expand Down
29 changes: 26 additions & 3 deletions crates/tw-gateway/tests/m5_toolwall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ fn with_policy(up: SocketAddr, inspect_tools: ToolPolicy) -> Config {
listen: Listen::default(),
clients: vec![Client {
name: "claude-code".into(),
key: "tw-testkey".into(),
// 真实长度的密钥:打码后该是 `tw-re…wb4e`,太短的会整串打掉
key: "tw-reh4xqqrzyvbutjacvjywb4e".into(),
..Default::default()
}],
providers: vec![Provider {
Expand Down Expand Up @@ -110,7 +111,7 @@ async fn run(cfg: Config) -> (String, tokio::sync::broadcast::Receiver<tw_api::E

let body = reqwest::Client::new()
.post(format!("http://{addr}/v1/messages"))
.header("x-api-key", "tw-testkey")
.header("x-api-key", "tw-reh4xqqrzyvbutjacvjywb4e")
.header("content-type", "application/json")
.body(r#"{"model":"claude-sonnet-4-5","max_tokens":64,"messages":[{"role":"user","content":"帮我看看构建配置"}],"stream":true}"#)
.send()
Expand Down Expand Up @@ -203,6 +204,28 @@ async fn observe_lets_it_through_but_still_says_something() {
assert_eq!(rule, "curl-pipe-sh");
}

#[tokio::test]
async fn the_start_event_names_the_key_masked_and_no_source_for_this_machine() {
// 密钥记打码后的样子,而且是请求那一刻用的那把;本机来的不记来源
let up = start_upstream(poisoned_stream()).await;
let (_, mut rx) = run(config(up, SecurityMode::Observe)).await;
let started = loop {
match tokio::time::timeout(Duration::from_secs(3), rx.recv()).await {
Ok(Ok(tw_api::Event::RequestStarted {
client,
key_masked,
peer,
..
})) => break (client, key_masked, peer),
Ok(Ok(_)) => continue,
other => panic!("没收到开始事件:{other:?}"),
}
};
assert_eq!(started.0, "claude-code");
assert_eq!(started.1.as_deref(), Some("tw-re…wb4e"));
assert_eq!(started.2, None, "本机来的不该有来源");
}

#[tokio::test]
async fn a_rule_that_only_records_never_cuts_even_in_enforce() {
// 处置按规则走:`rm -rf ~` 很吓人,但它毁的是你自己的文件,不会把机器
Expand Down Expand Up @@ -381,7 +404,7 @@ async fn run_whole(cfg: Config) -> (String, tokio::sync::broadcast::Receiver<tw_

let body = reqwest::Client::new()
.post(format!("http://{addr}/v1/messages"))
.header("x-api-key", "tw-testkey")
.header("x-api-key", "tw-reh4xqqrzyvbutjacvjywb4e")
.header("content-type", "application/json")
.body(r#"{"model":"claude-sonnet-4-5","max_tokens":64,"messages":[{"role":"user","content":"帮我看看构建配置"}]}"#)
.send()
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 {
key_masked: None,
peer: None,
id,
client: "c".into(),
Expand Down
23 changes: 19 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 = 15;
const SCHEMA: i64 = 16;

/// 这一行算不出钱,**因为价目表里没有这个模型**:用量是有的,缺的是单价。
///
Expand Down Expand Up @@ -82,6 +82,8 @@ pub struct RequestRow {
pub client_hint: Option<String>,
/// 非本机来的请求的来源地址(这条连接对面的地址)。本机来的是 None
pub peer: Option<String>,
/// 请求带的那把网关密钥打码后的样子,请求那一刻的
pub key_masked: Option<String>,
/// 这条属于哪一次任务。**指纹 + 起始时刻**,老记录是 None
pub session: Option<String>,
pub provider: String,
Expand Down Expand Up @@ -396,6 +398,12 @@ impl Db {
self.conn
.execute_batch("ALTER TABLE requests ADD COLUMN peer TEXT;")?;
}
if from < 16 {
// 用的是哪把密钥:打码后的样子。**名字会改、密钥会换**,只记名字的
// 话,更换之后老记录就对不上是哪一把了
self.conn
.execute_batch("ALTER TABLE requests ADD COLUMN key_masked TEXT;")?;
}
self.conn.pragma_update(None, "user_version", SCHEMA)?;
Ok(())
}
Expand All @@ -408,8 +416,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, 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)",
error_code, error_args, peer, key_masked)
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,?30)",
params![
r.id,
r.at_ms,
Expand Down Expand Up @@ -443,6 +451,7 @@ impl Db {
.filter(|e| !e.args.is_empty())
.map(|e| serde_json::to_string(&e.args).unwrap_or_default()),
r.peer,
r.key_masked,
],
)?;
Ok(())
Expand Down Expand Up @@ -1180,6 +1189,7 @@ fn row_from(r: &rusqlite::Row) -> rusqlite::Result<RequestRow> {
client: r.get("client")?,
client_hint: r.get("client_hint")?,
peer: r.get("peer")?,
key_masked: r.get("key_masked")?,
session: r.get("session")?,
provider: r.get("provider")?,
model: r.get("model")?,
Expand Down Expand Up @@ -1266,7 +1276,7 @@ const SECURITY_SELECT: &str =
COALESCE(NULLIF(r.client, ''), e.client),
COALESCE(r.model, ''),
e.tool, e.excerpt, e.count,
r.client_hint, r.peer
r.client_hint, r.peer, r.key_masked
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 @@ -1286,6 +1296,7 @@ fn security_view(r: &rusqlite::Row) -> rusqlite::Result<tw_api::SecurityEventVie
count: r.get(12)?,
client_hint: r.get(13)?,
peer: r.get(14)?,
key_masked: r.get(15)?,
})
}

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

pub(crate) fn row(id: i64, at_ms: i64) -> RequestRow {
RequestRow {
key_masked: None,
peer: None,
client_hint: None,
session: None,
Expand Down Expand Up @@ -1838,6 +1850,7 @@ pub(crate) mod tests {
db.conn
.execute_batch(
"DROP INDEX requests_session;
ALTER TABLE requests DROP COLUMN key_masked;
ALTER TABLE requests DROP COLUMN peer;
ALTER TABLE requests DROP COLUMN error_args;
ALTER TABLE requests DROP COLUMN error_code;
Expand Down Expand Up @@ -1885,11 +1898,13 @@ pub(crate) mod tests {
fresh.client_hint = Some("codex".into());
fresh.session = Some("abc-100".into());
fresh.peer = Some("192.168.1.23".into());
fresh.key_masked = Some("tw-re…wb4e".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"));
assert_eq!(back.key_masked.as_deref(), Some("tw-re…wb4e"));
}

#[test]
Expand Down
Loading
Loading