Skip to content

Commit

Permalink
rewrite: use escaped path, fix #5278 (#5504)
Browse files Browse the repository at this point in the history
* use escaped path while rewriting

Signed-off-by: TP-O <[email protected]>

* restore line break

---------

Signed-off-by: TP-O <[email protected]>
  • Loading branch information
TP-O authored May 16, 2023
1 parent e8352ae commit 13a3768
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
20 changes: 9 additions & 11 deletions modules/caddyhttp/rewrite/rewrite.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,16 +195,10 @@ func (rewr Rewrite) Rewrite(r *http.Request, repl *caddy.Replacer) bool {
var newPath, newQuery, newFrag string

if path != "" {
// Since the 'uri' placeholder performs a URL-encode,
// we need to intercept it so that it doesn't, because
// otherwise we risk a double-encode of the path.
uriPlaceholder := "{http.request.uri}"
if strings.Contains(path, uriPlaceholder) {
tmpUri := r.URL.Path
if r.URL.RawQuery != "" {
tmpUri += "?" + r.URL.RawQuery
}
path = strings.ReplaceAll(path, uriPlaceholder, tmpUri)
// replace the `path` placeholder to escaped path
pathPlaceholder := "{http.request.uri.path}"
if strings.Contains(path, pathPlaceholder) {
path = strings.ReplaceAll(path, pathPlaceholder, r.URL.EscapedPath())
}

newPath = repl.ReplaceAll(path, "")
Expand Down Expand Up @@ -232,7 +226,11 @@ func (rewr Rewrite) Rewrite(r *http.Request, repl *caddy.Replacer) bool {
// update the URI with the new components
// only after building them
if pathStart >= 0 {
r.URL.Path = newPath
if path, err := url.PathUnescape(newPath); err != nil {
r.URL.Path = newPath
} else {
r.URL.Path = path
}
}
if qsStart >= 0 {
r.URL.RawQuery = newQuery
Expand Down
12 changes: 11 additions & 1 deletion modules/caddyhttp/rewrite/rewrite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@ func TestRewrite(t *testing.T) {
input: newRequest(t, "GET", "/"),
expect: newRequest(t, "GET", "foo"),
},
{
rule: Rewrite{URI: "{http.request.uri}"},
input: newRequest(t, "GET", "/bar%3Fbaz?c=d"),
expect: newRequest(t, "GET", "/bar%3Fbaz?c=d"),
},
{
rule: Rewrite{URI: "{http.request.uri.path}"},
input: newRequest(t, "GET", "/bar%3Fbaz"),
expect: newRequest(t, "GET", "/bar%3Fbaz"),
},
{
rule: Rewrite{URI: "/foo{http.request.uri.path}"},
input: newRequest(t, "GET", "/bar"),
Expand Down Expand Up @@ -323,7 +333,7 @@ func TestRewrite(t *testing.T) {
input: newRequest(t, "GET", "/foo/findme%2Fbar"),
expect: newRequest(t, "GET", "/foo/replaced%2Fbar"),
},

{
rule: Rewrite{PathRegexp: []*regexReplacer{{Find: "/{2,}", Replace: "/"}}},
input: newRequest(t, "GET", "/foo//bar///baz?a=b//c"),
Expand Down

0 comments on commit 13a3768

Please sign in to comment.