import std/bytes import std/http.{type Request, Request} import std/io import std/net.{type SocketAddress, SocketAddress} // The client's address (issue #308), on requests built by hand: the // server puts the peer first, as the `:peer` pseudo-header; `peer` // finds it anywhere in the list (issue #313). fn request :: peer: SocketAddress headers: List<(String, String)> -> Request { http.with_peer Request("GET", "/", headers, bytes.empty ()) peer } fn shown :: o: Option -> String { match o { Some(s) -> s, None -> "none" } } pub fn main :: -> () / { // No peer: a request built by hand. let plain = Request("GET", "/", [("Host", "x")], bytes.empty ()) io.println (shown (http.client_address plain [])) //> none match http.peer (request SocketAddress("::1", 4242) []) { Some(SocketAddress(host, port)) -> io.println (host <> " " <> show port) , None -> io.println "no peer" } //> ::1 4242 // `:peer` not first (issue #313): still found, anywhere in the list. let buried = Request( "GET" , "/" , [("Host", "x"), (":peer", "10.0.0.2:1")] , bytes.empty () ) match http.peer buried { Some(SocketAddress(host, port)) -> io.println (host <> " " <> show port) , None -> io.println "no peer" } //> 10.0.0.2 1 io.println (shown (http.client_address buried [])) //> 10.0.0.2 // A direct client: its X-Forwarded-For, which anyone can send, is // ignored. let spoofed = request SocketAddress("198.51.100.4", 5000) [("X-Forwarded-For", "1.2.3.4")] io.println (shown (http.client_address spoofed ["10.0.0.2"])) //> 198.51.100.4 // Behind a trusted proxy: the right-most untrusted entry. let proxied = request SocketAddress("10.0.0.2", 5000) [ ("X-Forwarded-For", "1.2.3.4, 203.0.113.7") , ("X-Forwarded-For", "10.0.0.3") ] io.println (shown (http.client_address proxied ["10.0.0.2", "10.0.0.3"])) //> 203.0.113.7 // Every entry trusted: the left-most one. io.println ( shown ( http.client_address proxied ["10.0.0.2", "10.0.0.3", "203.0.113.7", "1.2.3.4"] ) ) //> 1.2.3.4 // A trusted proxy without X-Forwarded-For: the proxy itself. io.println ( shown ( http.client_address (request SocketAddress("10.0.0.2", 1) []) ["10.0.0.2"] ) ) //> 10.0.0.2 // Wire headers leave the pseudo-header out. io.println (show (http.wire_headers proxied)) //> [(X-Forwarded-For, 1.2.3.4, 203.0.113.7), (X-Forwarded-For, 10.0.0.3)] }