@marcel91200 / caddy Mirror · read-only / commits / 13a37688
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 13, 01:45 UTC

rewrite: use escaped path, fix #5278 (#5504)

* use escaped path while rewriting Signed-off-by: TP-O <letranphong2k1@gmail.com> * restore line break --------- Signed-off-by: TP-O <letranphong2k1@gmail.com>

Tran Phong committed May 16, 2023 at 22:16 UTC 13a37688dcdc1ffa8e9322dad0bffac0c0c9893a
2 files changed +20 -12
modules/caddyhttp/rewrite/rewrite.go
+9 -11
@@ -195,16 +195,10 @@ func (rewr Rewrite) Rewrite(r *http.Request, repl *caddy.Replacer) bool {
195 var newPath, newQuery, newFrag string
196
197 if path != "" {
198 - // Since the 'uri' placeholder performs a URL-encode,
199 - // we need to intercept it so that it doesn't, because
200 - // otherwise we risk a double-encode of the path.
201 - uriPlaceholder := "{http.request.uri}"
202 - if strings.Contains(path, uriPlaceholder) {
203 - tmpUri := r.URL.Path
204 - if r.URL.RawQuery != "" {
205 - tmpUri += "?" + r.URL.RawQuery
206 - }
207 - path = strings.ReplaceAll(path, uriPlaceholder, tmpUri)
198 + // replace the `path` placeholder to escaped path
199 + pathPlaceholder := "{http.request.uri.path}"
200 + if strings.Contains(path, pathPlaceholder) {
201 + path = strings.ReplaceAll(path, pathPlaceholder, r.URL.EscapedPath())
202 }
203
204 newPath = repl.ReplaceAll(path, "")
@@ -232,7 +226,11 @@ func (rewr Rewrite) Rewrite(r *http.Request, repl *caddy.Replacer) bool {
226 // update the URI with the new components
227 // only after building them
228 if pathStart >= 0 {
235 - r.URL.Path = newPath
229 + if path, err := url.PathUnescape(newPath); err != nil {
230 + r.URL.Path = newPath
231 + } else {
232 + r.URL.Path = path
233 + }
234 }
235 if qsStart >= 0 {
236 r.URL.RawQuery = newQuery
modules/caddyhttp/rewrite/rewrite_test.go
+11 -1
@@ -59,6 +59,16 @@ func TestRewrite(t *testing.T) {
59 input: newRequest(t, "GET", "/"),
60 expect: newRequest(t, "GET", "foo"),
61 },
62 + {
63 + rule: Rewrite{URI: "{http.request.uri}"},
64 + input: newRequest(t, "GET", "/bar%3Fbaz?c=d"),
65 + expect: newRequest(t, "GET", "/bar%3Fbaz?c=d"),
66 + },
67 + {
68 + rule: Rewrite{URI: "{http.request.uri.path}"},
69 + input: newRequest(t, "GET", "/bar%3Fbaz"),
70 + expect: newRequest(t, "GET", "/bar%3Fbaz"),
71 + },
72 {
73 rule: Rewrite{URI: "/foo{http.request.uri.path}"},
74 input: newRequest(t, "GET", "/bar"),
@@ -323,7 +333,7 @@ func TestRewrite(t *testing.T) {
333 input: newRequest(t, "GET", "/foo/findme%2Fbar"),
334 expect: newRequest(t, "GET", "/foo/replaced%2Fbar"),
335 },
326 -
336 +
337 {
338 rule: Rewrite{PathRegexp: []*regexReplacer{{Find: "/{2,}", Replace: "/"}}},
339 input: newRequest(t, "GET", "/foo//bar///baz?a=b//c"),