Skip to content

Commit fd9f98e

Browse files
committed
Fix gin-gonic#3500 Add escape logic for header
1 parent 81ac7d5 commit fd9f98e

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

gin.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@ import (
99
"html/template"
1010
"net"
1111
"net/http"
12-
"net/url"
1312
"os"
1413
"path"
14+
"regexp"
1515
"strings"
1616
"sync"
1717

@@ -669,8 +669,8 @@ func redirectTrailingSlash(c *Context) {
669669
req := c.Request
670670
p := req.URL.Path
671671
if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." {
672-
prefix = url.QueryEscape(prefix)
673-
prefix = strings.ReplaceAll(prefix, "%2F", "/")
672+
reg := regexp.MustCompile("[^a-zA-Z0-9/-]+")
673+
prefix = reg.ReplaceAllString(prefix, "")
674674

675675
p = prefix + "/" + req.URL.Path
676676
}

routes_test.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -186,15 +186,19 @@ func TestRouteRedirectTrailingSlash(t *testing.T) {
186186
assert.Equal(t, 200, w.Code)
187187

188188
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "../../bug#?"})
189-
assert.Equal(t, "../../../bug%2523%253F/path", w.Header().Get("Location"))
189+
assert.Equal(t, "//bug//path", w.Header().Get("Location"))
190190
assert.Equal(t, 301, w.Code)
191191

192192
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "https://gin-gonic.com/#"})
193-
assert.Equal(t, "https%3A/gin-gonic.com/%23/https%253A/gin-gonic.com/%2523/path", w.Header().Get("Location"))
193+
assert.Equal(t, "https/gin-goniccom/https/gin-goniccom/path", w.Header().Get("Location"))
194194
assert.Equal(t, 301, w.Code)
195195

196196
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "#bug"})
197-
assert.Equal(t, "%23bug/%2523bug/path", w.Header().Get("Location"))
197+
assert.Equal(t, "bug/bug/path", w.Header().Get("Location"))
198+
assert.Equal(t, 301, w.Code)
199+
200+
w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "/nor-mal/#?a=1"})
201+
assert.Equal(t, "/nor-mal/a1/path", w.Header().Get("Location"))
198202
assert.Equal(t, 301, w.Code)
199203

200204
router.RedirectTrailingSlash = false

0 commit comments

Comments
 (0)