forge
Explore
Log in

Don't you dare go Hollow

in: read the client address from client_ip

Browse files at this commit

5991bfbfa1d91d2150e90e9497a92e67e582573fAhmet Kaan GümüşParent: 4efff35
topcoat 0.9 reports the client through client_ip once one proxy hop is trusted. The old helper read the first x-forwarded-for hop from any peer, which a client can spoof.
crates/in-web/src/main.rsmodified+2 -1
@@ -273,7 +273,8 @@ async fn main() {
273 .layer(BodyLimit::max(512 * 1024 * 1024).at("/api/service/files"))273 .layer(BodyLimit::max(512 * 1024 * 1024).at("/api/service/files"))
274 .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files"))274 .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files"))
275 .cookies()275 .cookies()
276- .assets(bundle),276+ .assets(bundle)
277+ .trusted_proxies(in_web::server::trusted_proxies()),
277 oidc,278 oidc,
278 )279 )
279 .app_context(in_web::server::App {280 .app_context(in_web::server::App {
crates/in-web/src/server.rsmodified+73 -15
@@ -19,7 +19,7 @@ use serde::{Deserialize, Serialize};
19 use sha2::Digest;19 use sha2::Digest;
20 use topcoat::asset::AssetBundle;20 use topcoat::asset::AssetBundle;
21 use topcoat::context::{Cx, app_context, memoize};21 use topcoat::context::{Cx, app_context, memoize};
22-use topcoat::router::request::headers;22+use topcoat::router::request::{client_ip, headers};
23 use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::{IntoResponse, Response}, route, to_bytes};23 use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::{IntoResponse, Response}, route, to_bytes};
24 24
25 /// The whole application context, put into the router by `main.rs`. One25 /// The whole application context, put into the router by `main.rs`. One
@@ -175,22 +175,23 @@ pub async fn share_link_url(cx: &Cx, link: &in_core::store::ShareLink) -> Option
175 Some(format!("{}/s/{token}", share_origin(cx).await))175 Some(format!("{}/s/{token}", share_origin(cx).await))
176 }176 }
177 177
178-/// A stable-enough label for the client, for rate limiting. A proxy header is178+/// One proxy hop in front of the process. `in` is reached through that hop,
179-/// only trusted because in is meant to sit behind one; the address bucket is179+/// so [`client_ip`] reads the address it appended rather than the hop's own.
180-/// the limit that actually protects the login round-trip either way.180+/// A direct connection, with no hop in front, is its own address.
181+pub fn trusted_proxies() -> topcoat::router::TrustedProxies {
182+ topcoat::router::TrustedProxies::new().nearest(1)
183+}
184+
185+/// A stable-enough label for the client, for rate limiting.
181 ///186 ///
182-/// topcoat 0.6.2 exposes no peer address; x-forwarded-for or nothing.187+/// [`client_ip`] under [`trusted_proxies`]: the address the one trusted hop
188+/// reported, or the peer when the request did not come through it. `unknown`
189+/// when neither is there. A client-supplied `x-forwarded-for` is not read
190+/// unless that hop appended it.
183 pub fn client_label(cx: &Cx) -> String {191 pub fn client_label(cx: &Cx) -> String {
184- let Some(forwarded) = headers(cx).get("x-forwarded-for") else {192+ client_ip(cx)
185- return "unknown".to_string();193+ .map(|ip| ip.to_string())
186- };194+ .unwrap_or_else(|| "unknown".to_string())
187- let Ok(raw) = forwarded.to_str() else {
188- return "unknown".to_string();
189- };
190- match raw.split(',').next() {
191- Some(first) if !first.trim().is_empty() => first.trim().to_string(),
192- _ => "unknown".to_string(),
193- }
194 }195 }
195 196
196 /// The stylesheet this binary serves must be the one compiled into it.197 /// The stylesheet this binary serves must be the one compiled into it.
@@ -790,3 +791,60 @@ async fn cache_directives(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Resul
790 .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));791 .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
791 Ok(Response::from_parts(parts, body))792 Ok(Response::from_parts(parts, body))
792 }793 }
794+
795+#[cfg(test)]
796+mod client_label_tests {
797+ use std::net::SocketAddr;
798+
799+ use topcoat::router::response::IntoResponse;
800+ use topcoat::router::{
801+ Body, Method, RemoteAddr, RouteFn, RouteFuture, Router, request::Request, to_bytes,
802+ };
803+
804+ use super::{client_label, trusted_proxies};
805+
806+ fn echo(cx: &topcoat::context::Cx, _body: Body) -> RouteFuture<'_> {
807+ Box::pin(async move { client_label(cx).into_response(cx) })
808+ }
809+
810+ fn router(trust_one_hop: bool) -> Router {
811+ let builder = Router::builder().route(RouteFn::new(Method::GET, "/label", echo));
812+ if trust_one_hop {
813+ builder.trusted_proxies(trusted_proxies()).build()
814+ } else {
815+ builder.build()
816+ }
817+ }
818+
819+ async fn label(trust_one_hop: bool, peer: &str, forwarded: Option<&str>) -> String {
820+ let mut builder = Request::builder()
821+ .method(Method::GET)
822+ .uri("/label")
823+ .extension(RemoteAddr(peer.parse::<SocketAddr>().unwrap()));
824+ if let Some(value) = forwarded {
825+ builder = builder.header("x-forwarded-for", value);
826+ }
827+ let response = router(trust_one_hop)
828+ .handle(builder.body(Body::empty()).unwrap())
829+ .await;
830+ String::from_utf8(to_bytes(response.into_body(), 64).await.unwrap().to_vec()).unwrap()
831+ }
832+
833+ #[tokio::test]
834+ async fn one_trusted_hop_reports_the_client_not_the_proxy() {
835+ let got = label(true, "10.0.0.1:4242", Some("198.51.100.1")).await;
836+ assert_eq!(got, "198.51.100.1");
837+ }
838+
839+ #[tokio::test]
840+ async fn a_missing_header_falls_back_to_the_peer() {
841+ let got = label(true, "203.0.113.9:4242", None).await;
842+ assert_eq!(got, "203.0.113.9");
843+ }
844+
845+ #[tokio::test]
846+ async fn an_untrusted_peer_cannot_spoof_the_forwarded_header() {
847+ let got = label(false, "203.0.113.9:4242", Some("198.51.100.1")).await;
848+ assert_eq!(got, "203.0.113.9");
849+ }
850+}
crates/in-web/tests/http.rsmodified+2 -1
@@ -453,7 +453,8 @@ impl TestApp {
453 .assets(453 .assets(
454 AssetBundle::load_dir(asset_dir())454 AssetBundle::load_dir(asset_dir())
455 .expect("run `topcoat asset bundle` before the http suite"),455 .expect("run `topcoat asset bundle` before the http suite"),
456- ),456+ )
457+ .trusted_proxies(in_web::server::trusted_proxies()),
457 client.clone(),458 client.clone(),
458 )459 )
459 .app_context(App {460 .app_context(App {