identity.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. //! Request identity for rate limiting: peer IP and `client_id`, both hashed.
  2. //!
  3. //! The raw identity never becomes key material — [`counter_key`] hashes it —
  4. //! and `client_id` is recovered from the query string or, for form posts, a
  5. //! buffered-and-restored body so the downstream handler still sees it.
  6. use std::net::{IpAddr, SocketAddr};
  7. use axum::body::Body;
  8. use axum::extract::ConnectInfo;
  9. use axum::http::{Request, header};
  10. use sha2::{Digest, Sha256};
  11. use crate::config::types::TrustedProxyNet;
  12. /// Largest form body buffered to recover a `client_id`; anything larger is
  13. /// left untouched and simply yields no client identity.
  14. const MAX_FORM_BYTES: usize = 64 * 1024;
  15. /// Largest `X-Forwarded-For` chain honored for rate-limit attribution; only
  16. /// the rightmost entries are considered so header growth cannot grow the
  17. /// parse or let a planted leftmost claim survive the cap.
  18. const MAX_XFF_ENTRIES: usize = 32;
  19. /// The peer address recorded by axum's `ConnectInfo` (present whenever the
  20. /// listener is served with `into_make_service_with_connect_info`).
  21. pub(super) fn peer_ip(request: &Request<Body>) -> Option<IpAddr> {
  22. request
  23. .extensions()
  24. .get::<ConnectInfo<SocketAddr>>()
  25. .map(|info| info.0.ip())
  26. }
  27. /// The client IP attributed to a request for rate-limit bucket selection
  28. /// (T3-C3; paired T6-X2 decision).
  29. ///
  30. /// The verified TCP peer is always the identity unless it belongs to the
  31. /// configured `trusted_proxies` allowlist. Only then is the `X-Forwarded-For`
  32. /// chain consulted, and only its rightmost-untrusted entry is used: addresses appended by downstream trusted proxies are skipped so a
  33. /// spoofed leftmost claim planted before the first trusted hop cannot pick a
  34. /// foreign bucket. A header from an untrusted peer is ignored outright, and
  35. /// an absent header — or one with no parseable bare-IP entry — falls back
  36. /// to the verified peer — the
  37. /// request is still counted, never passed unattributed.
  38. ///
  39. /// This trust is narrowly scoped to rate-limit IP attribution: it never
  40. /// authenticates a client and never carries a client certificate (mTLS still
  41. /// requires L4/TCP passthrough). RFC 7239 `Forwarded` is never consulted.
  42. pub(super) fn client_ip(request: &Request<Body>, trusted: &[TrustedProxyNet]) -> Option<IpAddr> {
  43. let peer = peer_ip(request)?;
  44. if !trusted.iter().any(|net| net.contains(peer)) {
  45. return Some(peer);
  46. }
  47. let Some(chain) = forwarded_chain(request) else {
  48. return Some(peer);
  49. };
  50. Some(rightmost_untrusted(&chain, trusted))
  51. }
  52. /// Parse the `X-Forwarded-For` header into its address chain, leftmost-first.
  53. /// `None` when the header is absent or holds no bare-IP entry: unparseable
  54. /// entries (ports, brackets, `unknown`, garbage) are skipped — never trusted
  55. /// entry-by-entry — and only the rightmost [`MAX_XFF_ENTRIES`] raw entries
  56. /// are considered. Trusted proxies must emit bare IPs.
  57. fn forwarded_chain(request: &Request<Body>) -> Option<Vec<IpAddr>> {
  58. let header = request.headers().get("x-forwarded-for")?.to_str().ok()?;
  59. let raw: Vec<&str> = header.split(',').map(|entry| entry.trim()).collect();
  60. let tail = if raw.len() > MAX_XFF_ENTRIES {
  61. &raw[raw.len() - MAX_XFF_ENTRIES..]
  62. } else {
  63. raw.as_slice()
  64. };
  65. let chain: Vec<IpAddr> = tail
  66. .iter()
  67. .filter(|entry| !entry.is_empty())
  68. .filter_map(|entry| entry.parse::<IpAddr>().ok())
  69. .collect();
  70. if chain.is_empty() { None } else { Some(chain) }
  71. }
  72. /// The rightmost chain entry outside the trusted set; when every hop is
  73. /// trusted, the leftmost entry (the originating client as seen through
  74. /// trusted hops only).
  75. fn rightmost_untrusted(chain: &[IpAddr], trusted: &[TrustedProxyNet]) -> IpAddr {
  76. let is_trusted = |ip: &IpAddr| trusted.iter().any(|net| net.contains(*ip));
  77. chain
  78. .iter()
  79. .rev()
  80. .find(|ip| !is_trusted(ip))
  81. .copied()
  82. .unwrap_or(chain[0])
  83. }
  84. /// Recover a `client_id` from the query string, or (for form posts) the body.
  85. ///
  86. /// A form body is buffered and restored so the handler still sees it; a body
  87. /// that cannot be read yields `None` (the IP bucket still applies).
  88. pub(super) async fn extract_client_id(request: &mut Request<Body>) -> Option<String> {
  89. if let Some(client_id) = query_param(request.uri().query(), "client_id") {
  90. return Some(client_id);
  91. }
  92. let is_form = request
  93. .headers()
  94. .get(header::CONTENT_TYPE)
  95. .and_then(|value| value.to_str().ok())
  96. .is_some_and(|value| value.starts_with("application/x-www-form-urlencoded"));
  97. if !is_form {
  98. return None;
  99. }
  100. let body = std::mem::replace(request.body_mut(), Body::empty());
  101. let bytes = axum::body::to_bytes(body, MAX_FORM_BYTES).await.ok()?;
  102. let client_id = std::str::from_utf8(&bytes)
  103. .ok()
  104. .and_then(|text| find_param(text, "client_id"));
  105. *request.body_mut() = Body::from(bytes);
  106. client_id
  107. }
  108. /// `{prefix}{kind}:{sha256-hex}` — the raw identity never reaches Redis.
  109. ///
  110. /// The `raw` value for a client bucket is built with [`client_bucket_raw`]:
  111. /// the composite is hashed as one unit, so the separator never reaches Redis
  112. /// either.
  113. pub(super) fn counter_key(prefix: &str, kind: &str, raw: &str) -> String {
  114. format!("{prefix}{kind}:{}", sha256_hex(raw.as_bytes()))
  115. }
  116. /// Composite raw identity for the per-client bucket: `(peer_ip, client_id)`.
  117. ///
  118. /// `client_id` is recovered before client authentication (T3-C2), so it must
  119. /// never select a global bucket on its own: an attacker could exhaust a
  120. /// victim client's budget or rotate fake ids to evade the limit. Joining the
  121. /// peer IP with a NUL separator keeps each peer's client accounting distinct
  122. /// while the per-IP bucket stays the primary control. The separator is
  123. /// unambiguous even though `%00` form-decodes to NUL inside a `client_id`:
  124. /// the IP rendering never contains NUL, so the first NUL always delimits the
  125. /// IP and distinct pairs always render distinctly.
  126. pub(super) fn client_bucket_raw(ip: &IpAddr, client_id: &str) -> String {
  127. format!("{ip}\0{client_id}")
  128. }
  129. /// Lowercase hex of the SHA-256 digest.
  130. fn sha256_hex(input: &[u8]) -> String {
  131. const HEX: &[u8; 16] = b"0123456789abcdef";
  132. let digest = Sha256::digest(input);
  133. let mut out = String::with_capacity(digest.len() * 2);
  134. for byte in digest {
  135. out.push(HEX[(byte >> 4) as usize] as char);
  136. out.push(HEX[(byte & 0x0f) as usize] as char);
  137. }
  138. out
  139. }
  140. /// First value of `name` in a `&`-separated query or form string.
  141. fn query_param(query: Option<&str>, name: &str) -> Option<String> {
  142. query.and_then(|query| find_param(query, name))
  143. }
  144. /// Parse `key=value` pairs (percent- and `+`-decoded) and return the first
  145. /// value whose key matches `name`.
  146. fn find_param(input: &str, name: &str) -> Option<String> {
  147. input.split('&').find_map(|pair| {
  148. let (key, value) = pair.split_once('=')?;
  149. (decode_component(key) == name).then(|| decode_component(value))
  150. })
  151. }
  152. /// Minimal `application/x-www-form-urlencoded` component decoder.
  153. fn decode_component(raw: &str) -> String {
  154. let bytes = raw.as_bytes();
  155. let mut out = Vec::with_capacity(bytes.len());
  156. let mut index = 0;
  157. while index < bytes.len() {
  158. match bytes[index] {
  159. b'+' => {
  160. out.push(b' ');
  161. index += 1;
  162. }
  163. b'%' if index + 2 < bytes.len() => {
  164. match (hex_value(bytes[index + 1]), hex_value(bytes[index + 2])) {
  165. (Some(high), Some(low)) => {
  166. out.push(high * 16 + low);
  167. index += 3;
  168. }
  169. _ => {
  170. out.push(b'%');
  171. index += 1;
  172. }
  173. }
  174. }
  175. byte => {
  176. out.push(byte);
  177. index += 1;
  178. }
  179. }
  180. }
  181. String::from_utf8_lossy(&out).into_owned()
  182. }
  183. /// Hexadecimal digit value, or `None` for a non-hex byte.
  184. fn hex_value(byte: u8) -> Option<u8> {
  185. match byte {
  186. b'0'..=b'9' => Some(byte - b'0'),
  187. b'a'..=b'f' => Some(byte - b'a' + 10),
  188. b'A'..=b'F' => Some(byte - b'A' + 10),
  189. _ => None,
  190. }
  191. }
  192. #[cfg(test)]
  193. mod identity_tests {
  194. use std::error::Error;
  195. use std::net::{IpAddr, SocketAddr};
  196. use std::str::FromStr as _;
  197. use axum::body::Body;
  198. use axum::extract::ConnectInfo;
  199. use axum::http::Request;
  200. use super::client_ip;
  201. use crate::config::types::TrustedProxyNet;
  202. /// Test body result (no `unwrap`/`expect` under the deny lints).
  203. type TestResult = Result<(), Box<dyn Error>>;
  204. /// Request carrying `peer` as the recorded TCP peer plus an optional
  205. /// `X-Forwarded-For` header.
  206. fn request_with(
  207. peer: Option<SocketAddr>,
  208. xff: Option<&str>,
  209. ) -> Result<Request<Body>, Box<dyn Error>> {
  210. let mut builder = Request::builder().uri("/token");
  211. if let Some(value) = xff {
  212. builder = builder.header("x-forwarded-for", value);
  213. }
  214. let mut request = builder.body(Body::empty())?;
  215. if let Some(addr) = peer {
  216. request.extensions_mut().insert(ConnectInfo(addr));
  217. }
  218. Ok(request)
  219. }
  220. /// Parse-to-trusted helper for the test allowlists below.
  221. fn trusted(entries: &[&str]) -> Result<Vec<TrustedProxyNet>, Box<dyn Error>> {
  222. entries
  223. .iter()
  224. .map(|entry| TrustedProxyNet::from_str(entry).map_err(Box::<dyn Error>::from))
  225. .collect()
  226. }
  227. /// A trusted peer yields the client IP from `X-Forwarded-For`.
  228. #[test]
  229. fn ratelimit_trusted_proxy_honors_xff_from_trusted_peer() -> TestResult {
  230. let allow = trusted(&["10.0.0.0/8"])?;
  231. let peer = SocketAddr::from(([10, 0, 0, 1], 40_000));
  232. let request = request_with(Some(peer), Some("198.51.100.7"))?;
  233. assert_eq!(
  234. client_ip(&request, &allow),
  235. Some(IpAddr::from_str("198.51.100.7")?)
  236. );
  237. Ok(())
  238. }
  239. /// A spoofed header from an untrusted peer is ignored: the peer owns the
  240. /// bucket, so rotating the header cannot evade the limit.
  241. #[test]
  242. fn ratelimit_trusted_proxy_ignores_xff_from_untrusted_peer() -> TestResult {
  243. let allow = trusted(&["10.0.0.0/8"])?;
  244. let peer = SocketAddr::from(([127, 0, 0, 1], 40_000));
  245. let request = request_with(Some(peer), Some("198.51.100.7"))?;
  246. assert_eq!(client_ip(&request, &allow), Some(peer.ip()));
  247. Ok(())
  248. }
  249. /// A header with no parseable bare-IP entry from a trusted peer fails
  250. /// closed onto the verified peer: the request is still counted, never
  251. /// passed unattributed. Partially valid chains attribute their valid
  252. /// entries (see the skip tests below).
  253. #[test]
  254. fn ratelimit_trusted_proxy_malformed_xff_falls_back_to_peer() -> TestResult {
  255. let allow = trusted(&["10.0.0.1"])?;
  256. let peer = SocketAddr::from(([10, 0, 0, 1], 40_000));
  257. for xff in ["not-an-ip", "", "unknown", "1.2.3.4:5678", "[2001:db8::1]"] {
  258. let request = request_with(Some(peer), Some(xff))?;
  259. assert_eq!(client_ip(&request, &allow), Some(peer.ip()), "xff={xff:?}");
  260. }
  261. Ok(())
  262. }
  263. /// Rightmost-untrusted selection: trusted hops appended by downstream
  264. /// proxies are skipped, the first untrusted address wins.
  265. #[test]
  266. fn ratelimit_trusted_proxy_selects_rightmost_untrusted() -> TestResult {
  267. let allow = trusted(&["10.0.0.0/8"])?;
  268. let peer = SocketAddr::from(([10, 0, 0, 1], 40_000));
  269. let request = request_with(Some(peer), Some("198.51.100.7, 10.0.0.5, 10.0.0.9"))?;
  270. assert_eq!(
  271. client_ip(&request, &allow),
  272. Some(IpAddr::from_str("198.51.100.7")?)
  273. );
  274. Ok(())
  275. }
  276. /// An all-trusted chain yields its leftmost entry (the originating client
  277. /// as seen through trusted hops only).
  278. #[test]
  279. fn ratelimit_trusted_proxy_all_trusted_chain_yields_leftmost() -> TestResult {
  280. let allow = trusted(&["10.0.0.0/8"])?;
  281. let peer = SocketAddr::from(([10, 0, 0, 1], 40_000));
  282. let request = request_with(Some(peer), Some("10.0.0.5, 10.0.0.6"))?;
  283. assert_eq!(
  284. client_ip(&request, &allow),
  285. Some(IpAddr::from_str("10.0.0.5")?)
  286. );
  287. Ok(())
  288. }
  289. /// Default empty allowlist: every header is ignored, the peer is used.
  290. #[test]
  291. fn ratelimit_trusted_proxy_empty_allowlist_ignores_xff() -> TestResult {
  292. let allow: Vec<TrustedProxyNet> = Vec::new();
  293. let peer = SocketAddr::from(([203, 0, 113, 9], 40_000));
  294. let request = request_with(Some(peer), Some("198.51.100.7"))?;
  295. assert_eq!(client_ip(&request, &allow), Some(peer.ip()));
  296. Ok(())
  297. }
  298. /// No recorded peer means no identity: `None` so the caller fails closed.
  299. #[test]
  300. fn ratelimit_trusted_proxy_missing_peer_yields_no_identity() -> TestResult {
  301. let allow = trusted(&["10.0.0.0/8"])?;
  302. let request = request_with(None, Some("198.51.100.7"))?;
  303. assert_eq!(client_ip(&request, &allow), None);
  304. Ok(())
  305. }
  306. /// A partially spoofable chain still attributes its valid entries: bad
  307. /// entries are skipped, rightmost-untrusted wins over what remains.
  308. #[test]
  309. fn ratelimit_trusted_proxy_partial_chain_skips_bad_entry() -> TestResult {
  310. let allow = trusted(&["10.0.0.0/8"])?;
  311. let peer = SocketAddr::from(([10, 0, 0, 1], 40_000));
  312. let request = request_with(Some(peer), Some("198.51.100.7, not-an-ip"))?;
  313. assert_eq!(
  314. client_ip(&request, &allow),
  315. Some(IpAddr::from_str("198.51.100.7")?)
  316. );
  317. let request = request_with(Some(peer), Some("not-an-ip, 198.51.100.8"))?;
  318. assert_eq!(
  319. client_ip(&request, &allow),
  320. Some(IpAddr::from_str("198.51.100.8")?)
  321. );
  322. Ok(())
  323. }
  324. /// Entries carrying a port, brackets, or `unknown` are not bare IPs and are
  325. /// skipped; the remaining valid entry still attributes (previously the
  326. /// whole chain collapsed to the peer).
  327. #[test]
  328. fn ratelimit_trusted_proxy_xff_with_port_still_attributes() -> TestResult {
  329. let allow = trusted(&["10.0.0.0/8"])?;
  330. let peer = SocketAddr::from(([10, 0, 0, 1], 40_000));
  331. let request = request_with(Some(peer), Some("198.51.100.7:4123, 198.51.100.8"))?;
  332. assert_eq!(
  333. client_ip(&request, &allow),
  334. Some(IpAddr::from_str("198.51.100.8")?)
  335. );
  336. let request = request_with(Some(peer), Some("[2001:db8::1], 198.51.100.9"))?;
  337. assert_eq!(
  338. client_ip(&request, &allow),
  339. Some(IpAddr::from_str("198.51.100.9")?)
  340. );
  341. let request = request_with(Some(peer), Some("unknown, 198.51.100.10"))?;
  342. assert_eq!(
  343. client_ip(&request, &allow),
  344. Some(IpAddr::from_str("198.51.100.10")?)
  345. );
  346. Ok(())
  347. }
  348. /// An oversize chain is capped to the rightmost 32 entries: a leading
  349. /// entry pushed past the cap cannot select the bucket.
  350. #[test]
  351. fn ratelimit_trusted_proxy_oversize_chain_capped() -> TestResult {
  352. let allow = trusted(&["10.0.0.0/8"])?;
  353. let peer = SocketAddr::from(([10, 0, 0, 1], 40_000));
  354. let mut chain = vec!["198.51.100.7".to_string()];
  355. for _ in 0..40 {
  356. chain.push("10.0.0.5".to_string());
  357. }
  358. let header = chain.join(", ");
  359. let request = request_with(Some(peer), Some(header.as_str()))?;
  360. assert_eq!(
  361. client_ip(&request, &allow),
  362. Some(IpAddr::from_str("10.0.0.5")?)
  363. );
  364. Ok(())
  365. }
  366. #[test]
  367. fn ratelimit_trusted_proxy_exact_ip_entry_trusts_only_that_peer() -> TestResult {
  368. let allow = trusted(&["10.0.0.1"])?;
  369. let trusted_peer = SocketAddr::from(([10, 0, 0, 1], 40_000));
  370. let other_peer = SocketAddr::from(([10, 0, 0, 2], 40_000));
  371. let expected = IpAddr::from_str("198.51.100.7")?;
  372. let via_trusted = request_with(Some(trusted_peer), Some("198.51.100.7"))?;
  373. assert_eq!(client_ip(&via_trusted, &allow), Some(expected));
  374. let via_other = request_with(Some(other_peer), Some("198.51.100.7"))?;
  375. assert_eq!(client_ip(&via_other, &allow), Some(other_peer.ip()));
  376. Ok(())
  377. }
  378. }