Skip to content

Commit

Permalink
Fix gorilla#227: correct whitespace handling in XFF header parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
adam-p committed Mar 27, 2022
1 parent 3e03024 commit 2462333
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
6 changes: 3 additions & 3 deletions proxy_headers.go
Expand Up @@ -69,13 +69,13 @@ func getIP(r *http.Request) string {

if fwd := r.Header.Get(xForwardedFor); fwd != "" {
// Only grab the first (client) address. Note that '192.168.0.1,
// 10.1.1.1' is a valid key for X-Forwarded-For where addresses after
// 10.1.1.1' is a valid value for X-Forwarded-For where addresses after
// the first may represent forwarding proxies earlier in the chain.
s := strings.Index(fwd, ", ")
s := strings.Index(fwd, ",")
if s == -1 {
s = len(fwd)
}
addr = fwd[:s]
addr = strings.TrimSpace(fwd[:s])
} else if fwd := r.Header.Get(xRealIP); fwd != "" {
// X-Real-IP should only contain one IP address (the client making the
// request).
Expand Down
6 changes: 5 additions & 1 deletion proxy_headers_test.go
Expand Up @@ -17,6 +17,8 @@ func TestGetIP(t *testing.T) {
{xForwardedFor, "8.8.8.8", "8.8.8.8"}, // Single address
{xForwardedFor, "8.8.8.8, 8.8.4.4", "8.8.8.8"}, // Multiple
{xForwardedFor, "[2001:db8:cafe::17]:4711", "[2001:db8:cafe::17]:4711"}, // IPv6 address
{xForwardedFor, "8.8.8.8,8.8.4.4", "8.8.8.8"}, // No space after comma
{xForwardedFor, "8.8.8.8 , 8.8.4.4", "8.8.8.8"}, // Space before comma
{xForwardedFor, "", ""}, // None
{xRealIP, "8.8.8.8", "8.8.8.8"}, // Single address
{xRealIP, "8.8.8.8, 8.8.4.4", "8.8.8.8, 8.8.4.4"}, // Multiple
Expand All @@ -27,6 +29,8 @@ func TestGetIP(t *testing.T) {
{forwarded, `for=192.0.2.60;proto=http;by=203.0.113.43`, `192.0.2.60`}, // Multiple params
{forwarded, `for=192.0.2.43, for=198.51.100.17`, "192.0.2.43"}, // Multiple params
{forwarded, `for="workstation.local",for=198.51.100.17`, "workstation.local"}, // Hostname
{forwarded, `for=192.0.2.43,for=198.51.100.17`, "192.0.2.43"}, // No space after comma
{forwarded, `for=192.0.2.43 , for=198.51.100.17`, "192.0.2.43"}, // Space before comma
}

for _, v := range headers {
Expand All @@ -36,7 +40,7 @@ func TestGetIP(t *testing.T) {
}}
res := getIP(req)
if res != v.expected {
t.Fatalf("wrong header for %s: got %s want %s", v.key, res,
t.Fatalf("wrong header for %s: got %q want %q", v.key, res,
v.expected)
}
}
Expand Down

0 comments on commit 2462333

Please sign in to comment.