Elffuss BraidHub

kikocis/utopia public

dev · 4.6 KiBRawPermalink
1//! 请求来源捕获:把客户端 IP 与 User-Agent 放进 task-local,供审计写入时读取。
2//!
3//! 走 task-local 而非逐层传参,是因为 `audit::record` 有二十多个调用点,
4//! 它们分散在各个业务 handler 里;为了两个与业务无关的字段改遍所有签名,
5//! 只会让每个调用点都记得住这件与它无关的事。
6
7use axum::extract::ConnectInfo;
8use axum::extract::Request;
9use axum::http::HeaderMap;
10use axum::middleware::Next;
11use axum::response::Response;
12use std::net::SocketAddr;
13use utopia_store::audit::{ClientContext, CLIENT};
14
15/// 反向代理转发的原始客户端地址。取 X-Forwarded-For 的第一段(最靠近客户端的
16/// 那一跳),其次 X-Real-IP,都没有则用实际的 TCP 对端地址。
17///
18/// 这两个头是客户端可伪造的,直连部署时不该轻信;但直连时它们本来就不存在,
19/// 落回 TCP 对端地址即为真值。部署在代理之后时,代理应当覆写而非追加它们。
20fn client_ip(headers: &HeaderMap, peer: Option<SocketAddr>) -> Option<String> {
21 if let Some(xff) = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()) {
22 if let Some(first) = xff
23 .split(',')
24 .next()
25 .map(str::trim)
26 .filter(|s| !s.is_empty())
27 {
28 return Some(first.to_string());
29 }
30 }
31 if let Some(real) = headers.get("x-real-ip").and_then(|v| v.to_str().ok()) {
32 let real = real.trim();
33 if !real.is_empty() {
34 return Some(real.to_string());
35 }
36 }
37 peer.map(|a| a.ip().to_string())
38}
39
40/// User-Agent 截断到 256 字节:它由客户端完全控制,不该让一条请求头把台账撑爆。
41fn user_agent(headers: &HeaderMap) -> Option<String> {
42 headers
43 .get(axum::http::header::USER_AGENT)
44 .and_then(|v| v.to_str().ok())
45 .map(str::trim)
46 .filter(|s| !s.is_empty())
47 .map(|s| {
48 let mut end = s.len().min(256);
49 while end > 0 && !s.is_char_boundary(end) {
50 end -= 1;
51 }
52 s[..end].to_string()
53 })
54}
55
56pub async fn capture(req: Request, next: Next) -> Response {
57 let peer = req
58 .extensions()
59 .get::<ConnectInfo<SocketAddr>>()
60 .map(|ci| ci.0);
61 let ctx = ClientContext {
62 ip: client_ip(req.headers(), peer),
63 user_agent: user_agent(req.headers()),
64 };
65 CLIENT.scope(ctx, next.run(req)).await
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71
72 fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
73 let mut h = HeaderMap::new();
74 for (k, v) in pairs {
75 h.insert(
76 axum::http::HeaderName::from_bytes(k.as_bytes()).unwrap(),
77 v.parse().unwrap(),
78 );
79 }
80 h
81 }
82
83 #[test]
84 fn xff_wins_and_takes_the_client_hop() {
85 let h = headers(&[("x-forwarded-for", "203.0.113.7, 10.0.0.1, 10.0.0.2")]);
86 let peer = Some("10.0.0.9:5000".parse().unwrap());
87 assert_eq!(client_ip(&h, peer).as_deref(), Some("203.0.113.7"));
88 }
89
90 #[test]
91 fn falls_back_to_real_ip_then_peer() {
92 let h = headers(&[("x-real-ip", "198.51.100.4")]);
93 assert_eq!(client_ip(&h, None).as_deref(), Some("198.51.100.4"));
94
95 let peer = Some("192.0.2.5:443".parse().unwrap());
96 assert_eq!(
97 client_ip(&HeaderMap::new(), peer).as_deref(),
98 Some("192.0.2.5")
99 );
100 assert_eq!(client_ip(&HeaderMap::new(), None), None);
101 }
102
103 #[test]
104 fn blank_headers_do_not_shadow_the_peer() {
105 let h = headers(&[("x-forwarded-for", " "), ("x-real-ip", "")]);
106 let peer = Some("192.0.2.5:443".parse().unwrap());
107 assert_eq!(client_ip(&h, peer).as_deref(), Some("192.0.2.5"));
108 }
109
110 #[test]
111 fn user_agent_is_capped_at_256_bytes() {
112 let long = "Mozilla/5.0 ".repeat(50); // 600 字节,远超上限
113 let h = headers(&[("user-agent", long.as_str())]);
114 let got = user_agent(&h).unwrap();
115 assert_eq!(got.len(), 256);
116 assert!(long.starts_with(&got), "截断后仍是原串的前缀");
117 }
118
119 /// HeaderValue::to_str 只接受可见 ASCII,非 ASCII 的 UA 读不出来——
120 /// 记空好过记一段乱码。这也是上面按字节截断安全的原因:能读出来的一定是 ASCII。
121 #[test]
122 fn non_ascii_user_agent_is_dropped_rather_than_mangled() {
123 let mut h = HeaderMap::new();
124 h.insert(
125 axum::http::header::USER_AGENT,
126 axum::http::HeaderValue::from_bytes("浏览器".as_bytes()).unwrap(),
127 );
128 assert_eq!(user_agent(&h), None);
129 }
130}