package middleware import ( "context" "net" "net/http" "net/netip" "strings" ) // maxForwardedEntries bounds the X-Forwarded-For entries that are examined. A // longer chain is not a legitimate proxy chain here (edge, app Nginx, backend); // the entries beyond the bound, which sit furthest from this server, are // ignored. const maxForwardedEntries = 16 type clientAddrKey struct{} // ResolveClientAddr returns the address of the client that made a request, for // rate limiting and other in-memory decisions. It never logs or stores it. // // remoteAddr is the connecting peer (http.Request.RemoteAddr), forwardedFor // holds every X-Forwarded-For header line, and trusted lists the proxies this // server runs behind. The rules: // - A peer outside trusted is the client, and the header is ignored whole: // anyone can send it. // - For a trusted peer, the entries are read from the right, which is the // side that the nearest proxy wrote. Each trusted entry is another proxy // and is skipped; the first entry that is not trusted is the client. A // value a client put to the left of the first untrusted entry is never // reached. // - An entry that is not an IP address stops the walk, and the last // address that was already proven (the nearest trusted hop) is returned. // - When every entry is trusted, the leftmost one is returned. // // The result is unmapped (an IPv4-mapped IPv6 address becomes IPv4) and has // no zone. It is invalid only when remoteAddr is not an IP address. func ResolveClientAddr(remoteAddr string, forwardedFor []string, trusted []netip.Prefix) netip.Addr { peer, ok := parseAddr(hostOf(remoteAddr)) if !ok { return netip.Addr{} } if !isTrusted(peer, trusted) { return peer } entries := forwardedEntries(forwardedFor) hop := peer for index := len(entries) - 1; index >= 0; index-- { candidate, ok := parseAddr(entries[index]) if !ok { return hop } if !isTrusted(candidate, trusted) { return candidate } hop = candidate } return hop } // ClientIP resolves the client address with ResolveClientAddr and stores it in // the request context for ClientAddr. With no trusted proxies configured the // client is always the connecting peer. func ClientIP(trusted []netip.Prefix) func(http.Handler) http.Handler { trusted = append([]netip.Prefix(nil), trusted...) return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { addr := ResolveClientAddr(r.RemoteAddr, r.Header.Values("X-Forwarded-For"), trusted) next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), clientAddrKey{}, addr))) }) } } // ClientAddr returns the client address that the ClientIP middleware stored. // The second result is false when the middleware did not run or the peer // address was not an IP address; a caller must then fail closed, for example // by sharing one limiter bucket, instead of skipping its limit. func ClientAddr(ctx context.Context) (netip.Addr, bool) { addr, ok := ctx.Value(clientAddrKey{}).(netip.Addr) return addr, ok && addr.IsValid() } // LimiterKey is the key under which a rate limiter counts a client: an IPv4 // address as is and an IPv6 address reduced to its /64 network, because one // subscriber commonly controls a whole /64 and could otherwise pick a new // bucket per request. The key lives only in limiter memory (or a Redis key // with a window-length expiry); it must not be logged or stored longer. func LimiterKey(addr netip.Addr) string { addr = addr.Unmap() if addr.Is6() { prefix, err := addr.Prefix(64) if err == nil { return prefix.String() } } return addr.String() } func forwardedEntries(lines []string) []string { var entries []string for _, line := range lines { for part := range strings.SplitSeq(line, ",") { entries = append(entries, strings.TrimSpace(part)) } } if len(entries) > maxForwardedEntries { entries = entries[len(entries)-maxForwardedEntries:] } return entries } func hostOf(remoteAddr string) string { if host, _, err := net.SplitHostPort(remoteAddr); err == nil { return host } return remoteAddr } func parseAddr(value string) (netip.Addr, bool) { addr, err := netip.ParseAddr(strings.TrimSpace(value)) if err != nil { return netip.Addr{}, false } return addr.WithZone("").Unmap(), true } func isTrusted(addr netip.Addr, trusted []netip.Prefix) bool { for _, prefix := range trusted { if prefix.Contains(addr) { return true } } return false }