Skip to content

Commit da8520c

Browse files
committed
Add escape logic for header
1 parent c1d06e3 commit da8520c

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

gin.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"html/template"
1010
"net"
1111
"net/http"
12+
"net/url"
1213
"os"
1314
"path"
1415
"strings"
@@ -668,6 +669,9 @@ func redirectTrailingSlash(c *Context) {
668669
req := c.Request
669670
p := req.URL.Path
670671
if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." {
672+
prefix = url.QueryEscape(prefix)
673+
prefix = strings.ReplaceAll(prefix, "%2F", "/")
674+
671675
p = prefix + "/" + req.URL.Path
672676
}
673677
req.URL.Path = p + "/"

routes_test.go

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,13 +178,24 @@ func TestRouteRedirectTrailingSlash(t *testing.T) {
178178
w = PerformRequest(router, http.MethodPut, "/path4/")
179179
assert.Equal(t, http.StatusOK, w.Code)
180180

181-
w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "/api"})
182-
assert.Equal(t, "/api/path2/", w.Header().Get("Location"))
183-
assert.Equal(t, 301, w.Code)
181+
w = PerformRequest(router, http.MethodGet, "/path2/", header{Key: "X-Forwarded-Prefix", Value: "/api/"})
182+
assert.Equal(t, 200, w.Code)
184183

185184
w = PerformRequest(router, http.MethodGet, "/path2/", header{Key: "X-Forwarded-Prefix", Value: "/api/"})
186185
assert.Equal(t, 200, w.Code)
187186

187+
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "../../bug#?"})
188+
assert.Equal(t, "../../../bug%2523%253F/path", w.Header().Get("Location"))
189+
assert.Equal(t, 301, w.Code)
190+
191+
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "https://gin-gonic.com/#"})
192+
assert.Equal(t, "https%3A/gin-gonic.com/%23/https%253A/gin-gonic.com/%2523/path", w.Header().Get("Location"))
193+
assert.Equal(t, 301, w.Code)
194+
195+
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "#bug"})
196+
assert.Equal(t, "%23bug/%2523bug/path", w.Header().Get("Location"))
197+
assert.Equal(t, 301, w.Code)
198+
188199
router.RedirectTrailingSlash = false
189200

190201
w = PerformRequest(router, http.MethodGet, "/path/")

0 commit comments

Comments
 (0)