From c2ae4ed8c391fb0ea64d44435dbd3750a2675517 Mon Sep 17 00:00:00 2001 From: Vano Devium Date: Fri, 6 Oct 2023 16:15:57 +0300 Subject: [PATCH 1/2] clientIP for Cloudflare --- httpbin/helpers.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/httpbin/helpers.go b/httpbin/helpers.go index 8b04ca6a..fd5df682 100644 --- a/httpbin/helpers.go +++ b/httpbin/helpers.go @@ -50,6 +50,11 @@ func getClientIP(r *http.Request) string { return clientIP } + // Special case Cloudflare for the value directly. + if cfClientIP := r.Header.Get("CF-Connecting-IP"); cfClientIP != "" { + return cfClientIP + } + // Try to pull a reasonable value from the X-Forwarded-For header, if // present, by taking the first entry in a comma-separated list of IPs. if forwardedFor := r.Header.Get("X-Forwarded-For"); forwardedFor != "" { From 7686ee230f0a70c254dd79bb9f8dfcf2d45d61e6 Mon Sep 17 00:00:00 2001 From: Vano Devium Date: Fri, 6 Oct 2023 17:34:35 +0300 Subject: [PATCH 2/2] Cloudflare header CF-Connecting-IP --- httpbin/helpers.go | 6 ++---- httpbin/helpers_test.go | 10 ++++++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/httpbin/helpers.go b/httpbin/helpers.go index fd5df682..c1e170f8 100644 --- a/httpbin/helpers.go +++ b/httpbin/helpers.go @@ -49,10 +49,8 @@ func getClientIP(r *http.Request) string { if clientIP := r.Header.Get("Fly-Client-IP"); clientIP != "" { return clientIP } - - // Special case Cloudflare for the value directly. - if cfClientIP := r.Header.Get("CF-Connecting-IP"); cfClientIP != "" { - return cfClientIP + if clientIP := r.Header.Get("CF-Connecting-IP"); clientIP != "" { + return clientIP } // Try to pull a reasonable value from the X-Forwarded-For header, if diff --git a/httpbin/helpers_test.go b/httpbin/helpers_test.go index 71525c66..82a14ea3 100644 --- a/httpbin/helpers_test.go +++ b/httpbin/helpers_test.go @@ -235,6 +235,16 @@ func TestGetClientIP(t *testing.T) { }, want: "9.9.9.9", }, + "custom cloudflare header take precedence": { + given: &http.Request{ + Header: makeHeaders(map[string]string{ + "CF-Connecting-IP": "9.9.9.9", + "X-Forwarded-For": "1.1.1.1,2.2.2.2,3.3.3.3", + }), + RemoteAddr: "0.0.0.0", + }, + want: "9.9.9.9", + }, "x-forwarded-for is parsed": { given: &http.Request{ Header: makeHeaders(map[string]string{