Skip to content

Commit 22ad092

Browse files
authored
Merge pull request #174 from Nextra/allow-ports
Allow request IP candidates to contain ports
2 parents 861f17b + b6a8b3d commit 22ad092

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

http/http.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,11 @@ func ipFromRequest(headers []string, r *http.Request, customIP bool) (net.IP, er
9999
}
100100
}
101101
if remoteIP == "" {
102-
host, _, err := net.SplitHostPort(r.RemoteAddr)
102+
remoteIP = r.RemoteAddr
103+
}
104+
sep := strings.Index(remoteIP, ":")
105+
if sep != -1 {
106+
host, _, err := net.SplitHostPort(remoteIP)
103107
if err != nil {
104108
return nil, err
105109
}

http/http_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,13 @@ func TestIPFromRequest(t *testing.T) {
227227
{"127.0.0.1:9999", "X-Forwarded-For", "", []string{"X-Forwarded-For"}, "127.0.0.1"}, // Empty header
228228
{"127.0.0.1:9999?ip=1.2.3.4", "", "", nil, "1.2.3.4"}, // passed in "ip" parameter
229229
{"127.0.0.1:9999?ip=1.2.3.4", "X-Forwarded-For", "1.3.3.7,4.2.4.2", []string{"X-Forwarded-For"}, "1.2.3.4"}, // ip parameter wins over X-Forwarded-For with multiple entries
230+
231+
{"127.0.0.1:9999", "X-Real-IP", "1.3.3.7:1337", []string{"X-Real-IP", "X-Forwarded-For"}, "1.3.3.7"}, // Trusted header matches (with port)
232+
{"127.0.0.1:9999", "X-Forwarded-For", "1.3.3.7:1337", []string{"X-Real-IP", "X-Forwarded-For"}, "1.3.3.7"}, // Second trusted header matches (with port)
233+
{"127.0.0.1:9999", "X-Forwarded-For", "1.3.3.7:1337,4.2.4.2:4242", []string{"X-Forwarded-For"}, "1.3.3.7"}, // X-Forwarded-For with multiple entries (commas separator, with port)
234+
{"127.0.0.1:9999", "X-Forwarded-For", "1.3.3.7:1337, 4.2.4.2:4242", []string{"X-Forwarded-For"}, "1.3.3.7"}, // X-Forwarded-For with multiple entries (space+comma separator, with port)
235+
{"127.0.0.1:9999?ip=1.2.3.4:1234", "", "", nil, "1.2.3.4"}, // passed in "ip" parameter (with port)
236+
{"127.0.0.1:9999?ip=1.2.3.4:1234", "X-Forwarded-For", "1.3.3.7:1337,4.2.4.2:4242", []string{"X-Forwarded-For"}, "1.2.3.4"}, // ip parameter wins over X-Forwarded-For with multiple entries (with port)
230237
}
231238
for _, tt := range tests {
232239
u, err := url.Parse("http://" + tt.remoteAddr)

0 commit comments

Comments
 (0)