Merge 814d0530ebef164ff7ffff48040a9de25164aae5 into 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646

This commit is contained in:
Arpit Jain 2026-11-05 11:24:55 -05:00 committed by GitHub
commit 37c5ed9166
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 14 additions and 3 deletions

5
gin.go
View File

@ -815,6 +815,11 @@ func redirectTrailingSlash(c *Context) {
prefix = removeRepeatedChar(prefix, '/')
p = prefix + "/" + req.URL.Path
// Keep the redirect target rooted at this server. Sanitizing can leave a
// prefix that is empty or has no leading slash, and then p starts with
// "//", which a client reads as a host, or with a path segment, which it
// resolves against the request path and so repeats the prefix.
p = "/" + strings.TrimLeft(p, "/")
}
req.URL.Path = p + "/"
if length := len(p); length > 1 && p[length-1] == '/' {

View File

@ -260,7 +260,7 @@ func TestRouteRedirectTrailingSlash(t *testing.T) {
assert.Equal(t, http.StatusMovedPermanently, w.Code)
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "api/../../"})
assert.Equal(t, "//path", w.Header().Get("Location"))
assert.Equal(t, "/path", w.Header().Get("Location"))
assert.Equal(t, http.StatusMovedPermanently, w.Code)
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "api/../../../"})
@ -276,11 +276,11 @@ func TestRouteRedirectTrailingSlash(t *testing.T) {
assert.Equal(t, http.StatusMovedPermanently, w.Code)
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "https://gin-gonic.com/#"})
assert.Equal(t, "https/gin-goniccom/https/gin-goniccom/path", w.Header().Get("Location"))
assert.Equal(t, "/https/gin-goniccom/path", w.Header().Get("Location"))
assert.Equal(t, http.StatusMovedPermanently, w.Code)
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "#api"})
assert.Equal(t, "api/api/path", w.Header().Get("Location"))
assert.Equal(t, "/api/path", w.Header().Get("Location"))
assert.Equal(t, http.StatusMovedPermanently, w.Code)
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "/nor-mal/#?a=1"})
@ -291,6 +291,12 @@ func TestRouteRedirectTrailingSlash(t *testing.T) {
assert.Equal(t, "/nor-mal/2e2e/path", w.Header().Get("Location"))
assert.Equal(t, http.StatusMovedPermanently, w.Code)
// A prefix that sanitizes to nothing must not leave a Location starting
// with "//", which a client reads as the start of a host.
w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: ".."})
assert.Equal(t, "/path2/", w.Header().Get("Location"))
assert.Equal(t, http.StatusMovedPermanently, w.Code)
router.RedirectTrailingSlash = false
w = PerformRequest(router, http.MethodGet, "/path/")