diff --git a/req_resp.go b/req_resp.go index 557829f..d48fc19 100644 --- a/req_resp.go +++ b/req_resp.go @@ -223,15 +223,9 @@ func apiGatewayV2Headers(r *http.Request) map[string]string { if _, ok := headers["host"]; !ok { headers["host"] = r.Host } - if _, ok := headers["x-forwarded-proto"]; !ok { - headers["x-forwarded-proto"] = requestScheme(r) - } - if _, ok := headers["x-forwarded-for"]; !ok { - headers["x-forwarded-for"] = requestSourceIP(r) - } - if _, ok := headers["x-forwarded-port"]; !ok { - headers["x-forwarded-port"] = requestPort(r) - } + headers["x-forwarded-proto"] = requestScheme(r) + headers["x-forwarded-for"] = requestSourceIP(r) + headers["x-forwarded-port"] = requestPort(r) return headers } @@ -276,8 +270,10 @@ func requestScheme(r *http.Request) string { } func requestPort(r *http.Request) string { - if _, port, err := net.SplitHostPort(r.Host); err == nil { - return port + if localAddr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr); ok { + if _, port, err := net.SplitHostPort(localAddr.String()); err == nil && port != "" { + return port + } } if requestScheme(r) == "https" { return "443" diff --git a/req_resp_test.go b/req_resp_test.go index 751da99..b86cbfa 100644 --- a/req_resp_test.go +++ b/req_resp_test.go @@ -5,6 +5,7 @@ import ( "encoding/base64" "encoding/json" "io" + "net" "net/http" "net/http/httptest" "strings" @@ -61,6 +62,28 @@ func TestNewRequestForFormatAPIGatewayV2(t *testing.T) { } } +func TestAPIGatewayV2HeadersOverwriteSpoofedForwardedHeaders(t *testing.T) { + r := httptest.NewRequest(http.MethodGet, "http://example.test/", nil) + r.RemoteAddr = "192.0.2.1:1234" + r.Header.Set("X-Forwarded-For", "203.0.113.42") + r.Header.Set("X-Forwarded-Proto", "https") + r.Header.Set("X-Forwarded-Port", "8443") + r.Host = "example.test:8443" + r = r.WithContext(context.WithValue(r.Context(), http.LocalAddrContextKey, &net.TCPAddr{Port: 80})) + + headers := apiGatewayV2Headers(r) + + if got, want := headers["x-forwarded-for"], "192.0.2.1"; got != want { + t.Errorf("x-forwarded-for = %q, want %q", got, want) + } + if got, want := headers["x-forwarded-proto"], "http"; got != want { + t.Errorf("x-forwarded-proto = %q, want %q", got, want) + } + if got, want := headers["x-forwarded-port"], "80"; got != want { + t.Errorf("x-forwarded-port = %q, want %q", got, want) + } +} + func TestRequestSourceIPUsesCaddyClientIP(t *testing.T) { r := httptest.NewRequest(http.MethodGet, "/", nil) r.RemoteAddr = "192.0.2.1:1234"