Anonymous view counting uses the trusted-proxy client address

4fa4298 · gmorell · 2026-12-03 03:18

6 files +71 -12
Message
{commit_body(@commit)}

Files changed

modified src/client_ip.rs
+31 −2
@@ -163,20 +163,49 @@ impl<S: Send + Sync> FromRequestParts<S> for ClientIp {
163 163 }
164 164 }
165 165
166 −/// Resolve the client once and attach it ([`ClientIp`]). Outermost, so the
167 −/// auth middlewares see it too.
166 +/// Internal request header carrying the resolved client address to code that
167 +/// only has the headers (the anonymous view throttle). [`layer`] always
168 +/// removes any copy a client sent before setting it, so it can't be forged.
169 +pub const RESOLVED_HEADER: &str = "x-recourse-client-ip";
170 +
171 +/// Resolve the client once and attach it ([`ClientIp`], and
172 +/// [`RESOLVED_HEADER`]). Outermost, so the auth middlewares see it too.
168 173 pub async fn layer(State(trusted): State<Arc<TrustedProxies>>, mut request: Request, next: Next) -> Response {
169 174 let peer = request.extensions().get::<ConnectInfo<SocketAddr>>().map(|c| c.0.ip());
170 175 let ip = trusted.resolve(peer, request.headers());
176 + stamp(request.headers_mut(), ip);
171 177 request.extensions_mut().insert(ClientIp(ip));
172 178 next.run(request).await
173 179 }
174 180
181 +/// Replace whatever the client sent as [`RESOLVED_HEADER`] with the resolved
182 +/// address (or nothing).
183 +fn stamp(headers: &mut axum::http::HeaderMap, ip: Option<IpAddr>) {
184 + headers.remove(RESOLVED_HEADER);
185 + if let Some(v) = ip.and_then(|ip| axum::http::HeaderValue::from_str(&ip.to_string()).ok()) {
186 + headers.insert(RESOLVED_HEADER, v);
187 + }
188 +}
189 +
175 190 #[cfg(test)]
176 191 mod tests {
177 192 use super::*;
178 193 use axum::http::HeaderValue;
179 194
195 + #[test]
196 + fn the_resolved_header_cannot_be_forged() {
197 + let mut m = HeaderMap::new();
198 + m.insert(RESOLVED_HEADER, HeaderValue::from_static("6.6.6.6"));
199 + stamp(&mut m, Some("203.0.113.7".parse().unwrap()));
200 + assert_eq!(m.get_all(RESOLVED_HEADER).iter().count(), 1);
201 + assert_eq!(m.get(RESOLVED_HEADER).unwrap(), "203.0.113.7");
202 + // Unknown client: the forged value is still dropped.
203 + let mut m = HeaderMap::new();
204 + m.insert(RESOLVED_HEADER, HeaderValue::from_static("6.6.6.6"));
205 + stamp(&mut m, None);
206 + assert!(m.get(RESOLVED_HEADER).is_none());
207 + }
208 +
180 209 fn h(pairs: &[(&'static str, &str)]) -> HeaderMap {
181 210 let mut m = HeaderMap::new();
182 211 for (k, v) in pairs {
modified src/handlers/forum.rs
+6 −10
@@ -71,19 +71,15 @@ pub(crate) fn sort_topics(rows: &mut [(topics::Model, Option<users::Model>)], so
71 71 });
72 72 }
73 73
74 −/// Best-effort client IP for throttling anonymous viewers (proxy headers, else
75 −/// a shared fallback bucket).
74 +/// The client address for throttling anonymous viewers: the one the
75 +/// trusted-proxy layer resolved ([`crate::client_ip::RESOLVED_HEADER`]),
76 +/// never a client-supplied X-Forwarded-For / X-Real-IP, so a visitor can't
77 +/// mint fresh views by forging those. Unknown: one shared bucket.
76 78 fn client_ip(headers: &HeaderMap) -> String {
77 79 headers
78 − .get("x-forwarded-for")
80 + .get(crate::client_ip::RESOLVED_HEADER)
79 81 .and_then(|v| v.to_str().ok())
80 − .map(|s| s.split(',').next().unwrap_or(s).trim().to_string())
81 − .or_else(|| {
82 − headers
83 − .get("x-real-ip")
84 − .and_then(|v| v.to_str().ok())
85 − .map(|s| s.trim().to_string())
86 − })
82 + .map(|s| s.trim().to_string())
87 83 .filter(|s| !s.is_empty())
88 84 .unwrap_or_else(|| "anon".to_string())
89 85 }
modified tests/moderation_db.rs
+34 −0
@@ -890,3 +890,37 @@ async fn off_site_links_go_through_the_signed_out_page() {
890 890 let (_, html) = app.page(&format!("/out?u={}&s={}", "https%3A%2F%2Fxn--bcher-kva.example%2Fkauf", links.signer().sign(idn)), None).await;
891 891 assert!(html.contains("data-idn") && html.contains("bücher.example") && html.contains("xn--bcher-kva.example"), "{html}");
892 892 }
893 +
894 +#[tokio::test]
895 +async fn anonymous_views_cannot_be_inflated_with_forged_forwarding_headers() {
896 + let Some(app) = app().await else { return };
897 + let alice = app.who("alice", 2, false).await;
898 + let c = app.category(None, None, None).await;
899 + let (topic, _) = app.topic(&alice, &c, "Count me once").await;
900 + let views = |app: &App| {
901 + let id = topic.id;
902 + let db = app.db().clone();
903 + async move { topics::Entity::find_by_id(id).one(&db).await.unwrap().unwrap().views }
904 + };
905 + let before = views(&app).await;
906 + let n = (Uuid::now_v7().as_u128() % 200) as u8 + 20;
907 + let visitor = format!("192.0.2.{n}");
908 +
909 + // A direct, untrusted visitor sends a different forged X-Forwarded-For
910 + // and X-Real-IP each time: still one viewer, one view this window.
911 + for i in 0..5 {
912 + let fake = format!("6.6.6.{i}");
913 + let req = Request::builder().uri(format!("/t/{}", topic.id)).body(Body::empty()).unwrap();
914 + let (s, _, _) = app
915 + .send(from_peer(req, &visitor, &[("x-forwarded-for", &fake), ("x-real-ip", &fake), ("x-recourse-client-ip", &fake)]))
916 + .await;
917 + assert_eq!(s, StatusCode::OK);
918 + }
919 + assert_eq!(views(&app).await, before + 1, "forged headers must not mint views");
920 +
921 + // A genuinely different client (through a trusted proxy) is a new viewer.
922 + let other = format!("198.51.{n}.33");
923 + let req = Request::builder().uri(format!("/t/{}", topic.id)).body(Body::empty()).unwrap();
924 + app.send(from_peer(req, "10.0.3.4", &[("x-forwarded-for", &other)])).await;
925 + assert_eq!(views(&app).await, before + 2);
926 +}

Parents: 7250478