package server import ( "fmt" "net" "net/http" "net/netip" "slices" "strings" ) func newClientIPResolve(source string, trustedProxies []netip.Prefix) func(*http.Request) (string, error) { isTrusted := func(ip netip.Addr) bool { for _, prefix := range trustedProxies { if prefix.Contains(ip) { return true } } return false } return func(r *http.Request) (string, error) { host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return "", err } peer, err := netip.ParseAddr(host) if err != nil { return "", err } if source == "remote" || !isTrusted(peer) { return peer.String(), nil } switch source { case "cloudflare": value := r.Header.Values("CF-Connecting-IP") if len(value) != 1 { return "", fmt.Errorf("expected a single CF-Connecting-IP header") } ip, err := netip.ParseAddr(value[0]) if err != nil { return "", fmt.Errorf("invalid CF-Connecting-IP: %w", err) } return ip.Unmap().String(), nil case "xff": values := r.Header.Values("X-Forwarded-For") hops := strings.Split(strings.Join(values, ","), ",") // walk backwards (right to left), while skipping trusted proxies, the first untrusted ip will be assumed to be the client ip // https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-For#syntax for _, hop := range slices.Backward(hops) { if hop == "" { continue } ip, err := netip.ParseAddr(strings.TrimSpace(hop)) if err != nil { return "", fmt.Errorf("invalid X-Forwarded-For hop: %w", err) } ip = ip.Unmap() if !isTrusted(ip) { return ip.String(), nil } } return "", fmt.Errorf("no client ip in X-Forwarded-For") } return "", fmt.Errorf("unknown client ip source %q", source) } }