diff --git a/pkg/middlewares/requestdecorator/request_decorator.go b/pkg/middlewares/requestdecorator/request_decorator.go index fcb6fb983..013cb12c3 100644 --- a/pkg/middlewares/requestdecorator/request_decorator.go +++ b/pkg/middlewares/requestdecorator/request_decorator.go @@ -49,11 +49,16 @@ func (r *RequestDecorator) ServeHTTP(rw http.ResponseWriter, req *http.Request, func parseHost(addr string) string { if !strings.Contains(addr, ":") { + // IPv4 without port or empty address return addr } + // IPv4 with port or IPv6 host, _, err := net.SplitHostPort(addr) if err != nil { + if addr[0] == '[' && addr[len(addr)-1] == ']' { + return addr[1 : len(addr)-1] + } return addr } return host diff --git a/pkg/middlewares/requestdecorator/request_decorator_test.go b/pkg/middlewares/requestdecorator/request_decorator_test.go index 15c5ee89e..03c8f4018 100644 --- a/pkg/middlewares/requestdecorator/request_decorator_test.go +++ b/pkg/middlewares/requestdecorator/request_decorator_test.go @@ -104,7 +104,7 @@ func TestRequestFlattening(t *testing.T) { } } -func TestRequestHostParseHost(t *testing.T) { +func Test_parseHost(t *testing.T) { testCases := []struct { desc string host string @@ -130,6 +130,46 @@ func TestRequestHostParseHost(t *testing.T) { host: "127.0.0.1:", expected: "127.0.0.1", }, + { + desc: "host with : and without port", + host: "fe80::215:5dff:fe20:cd6a", + expected: "fe80::215:5dff:fe20:cd6a", + }, + { + desc: "IPv6 host with : and with port", + host: "[fe80::215:5dff:fe20:cd6a]:123", + expected: "fe80::215:5dff:fe20:cd6a", + }, + { + desc: "IPv6 host with : and without port", + host: "[fe80::215:5dff:fe20:cd6a]:", + expected: "fe80::215:5dff:fe20:cd6a", + }, + { + desc: "IPv6 host without : and without port", + host: "[fe80::215:5dff:fe20:cd6a]", + expected: "fe80::215:5dff:fe20:cd6a", + }, + { + desc: "invalid IPv6: missing [", + host: "fe80::215:5dff:fe20:cd6a]", + expected: "fe80::215:5dff:fe20:cd6a]", + }, + { + desc: "invalid IPv6: missing ]", + host: "[fe80::215:5dff:fe20:cd6a", + expected: "[fe80::215:5dff:fe20:cd6a", + }, + { + desc: "empty address", + host: "", + expected: "", + }, + { + desc: "only :", + host: ":", + expected: "", + }, } for _, test := range testCases {