Use X-Forwarded-{Proto,Host,Uri} on redirect as last resort (#957)

This commit is contained in:
İlteriş Eroğlu
2021-01-01 15:23:11 -08:00
committed by GitHub
parent 91b3f5973e
commit 1d74a51cd7
6 changed files with 263 additions and 2 deletions
+19
View File
@@ -25,6 +25,15 @@ func GetCertPool(paths []string) (*x509.CertPool, error) {
return pool, nil
}
// GetRequestProto return the request host header or X-Forwarded-Proto if present
func GetRequestProto(req *http.Request) string {
proto := req.Header.Get("X-Forwarded-Proto")
if proto == "" {
proto = req.URL.Scheme
}
return proto
}
// GetRequestHost return the request host header or X-Forwarded-Host if present
func GetRequestHost(req *http.Request) string {
host := req.Header.Get("X-Forwarded-Host")
@@ -33,3 +42,13 @@ func GetRequestHost(req *http.Request) string {
}
return host
}
// GetRequestURI return the request host header or X-Forwarded-Uri if present
func GetRequestURI(req *http.Request) string {
uri := req.Header.Get("X-Forwarded-Uri")
if uri == "" {
// Use RequestURI to preserve ?query
uri = req.URL.RequestURI()
}
return uri
}
+26
View File
@@ -110,3 +110,29 @@ func TestGetRequestHost(t *testing.T) {
extHost := GetRequestHost(proxyReq)
g.Expect(extHost).To(Equal("external.example.com"))
}
func TestGetRequestProto(t *testing.T) {
g := NewWithT(t)
req := httptest.NewRequest("GET", "https://example.com", nil)
proto := GetRequestProto(req)
g.Expect(proto).To(Equal("https"))
proxyReq := httptest.NewRequest("GET", "https://internal.example.com", nil)
proxyReq.Header.Add("X-Forwarded-Proto", "http")
extProto := GetRequestProto(proxyReq)
g.Expect(extProto).To(Equal("http"))
}
func TestGetRequestURI(t *testing.T) {
g := NewWithT(t)
req := httptest.NewRequest("GET", "https://example.com/ping", nil)
uri := GetRequestURI(req)
g.Expect(uri).To(Equal("/ping"))
proxyReq := httptest.NewRequest("GET", "http://internal.example.com/bong", nil)
proxyReq.Header.Add("X-Forwarded-Uri", "/ping")
extURI := GetRequestURI(proxyReq)
g.Expect(extURI).To(Equal("/ping"))
}