Skip to content

RealIP middleware incompatible with Cloudflare/CDN setups - returns edge server IP instead of client IP #40

@umputun

Description

@umputun

Problem

rest.RealIP extracts client IP using the rightmost IP in the X-Forwarded-For chain (RFC 7239 security model). This doesn't work with Cloudflare and similar CDNs.

With Cloudflare, the X-Forwarded-For header looks like:

X-Forwarded-For: <original-client>, <cloudflare-edge-server>

The rightmost IP is a Cloudflare edge server which:

  1. Varies per request - Cloudflare routes through different edges
  2. Is not the actual client IP

Example

Same client making requests gets different "client IPs":

172.71.203.9    (Cloudflare edge)
172.70.231.89   (different edge)
104.23.190.60   (another edge)

Should have been: 203.0.113.195 (actual client) for all requests.

Proposed Solution

Add RealIPFromCDN middleware with CDN-friendly header priority:

  1. X-Real-IP - trusted proxy (reproxy/nginx) sets this to actual client
  2. CF-Connecting-IP - Cloudflare's dedicated header for original client
  3. X-Forwarded-For (leftmost public IP) - original client in CDN chain
  4. RemoteAddr - fallback for direct connections

Key: filter out private/loopback IPs from headers before accepting.

API

// new middleware
func RealIPFromCDN(next http.Handler) http.Handler

// new function in realip package  
func GetFromCDN(r *http.Request) (string, error)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions