rewrite: fix strip_path_suffix decoding a literal '%' as an escape (#8005)

This commit is contained in:
Nguyen Thanh Dat 2026-11-03 13:31:54 +07:00 committed by GitHub
parent 0759b29fe0
commit c645c2b439
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 51 additions and 2 deletions

View file

@ -507,9 +507,12 @@ func trimPathSuffix(escapedPath, suffix string) string {
// if escapedPath uses a percent-encoding that ends at this position but
// the suffix pattern does not encode this position, decode escapedPath's
// escape so the comparison happens in normalized/unescaped space
// escape so the comparison happens in normalized/unescaped space.
// Walking right-to-left, the suffix is inside one of its own escapes
// either when an escape ends here (a '%' two bytes back) or when the
// cursor has reached that escape's introducing '%' itself.
pathHasEscape := iPath >= 3 && escapedPath[iPath-3] == '%'
suffixHasEscape := iSuffix >= 3 && suffix[iSuffix-3] == '%'
suffixHasEscape := (iSuffix >= 3 && suffix[iSuffix-3] == '%') || suffixCh == '%'
if pathHasEscape && !suffixHasEscape {
decoded, err := url.PathUnescape(escapedPath[iPath-3 : iPath])
if err != nil {

View file

@ -361,6 +361,52 @@ func TestRewrite(t *testing.T) {
input: newRequest(t, "GET", "/foo/bar/suffix"),
expect: newRequest(t, "GET", "/foo/bar/suffix"),
},
{
// the suffix pattern's own '%' must be compared literally: here the
// path's "%25" decodes to a literal '%', which is not the escape
// introducer the pattern asks for, so nothing may be stripped
rule: Rewrite{StripPathSuffix: "%41"},
input: newRequest(t, "GET", "/file%2541"), // decodes to "/file%41"
expect: newRequest(t, "GET", "/file%2541"),
},
{
rule: Rewrite{StripPathSuffix: "%2f"},
input: newRequest(t, "GET", "/file%252f"), // decodes to "/file%2f"
expect: newRequest(t, "GET", "/file%252f"),
},
{
rule: Rewrite{StripPathSuffix: "%25"},
input: newRequest(t, "GET", "/file%2525"), // decodes to "/file%25"
expect: newRequest(t, "GET", "/file%2525"),
},
{
// ...but a path that really does use the pattern's escape is stripped
rule: Rewrite{StripPathSuffix: "%41"},
input: newRequest(t, "GET", "/file%41"),
expect: newRequest(t, "GET", "/file"),
},
{
rule: Rewrite{StripPathSuffix: "%2f"},
input: newRequest(t, "GET", "/file%2f"),
expect: newRequest(t, "GET", "/file"),
},
{
rule: Rewrite{StripPathSuffix: "%25"},
input: newRequest(t, "GET", "/file%25"),
expect: newRequest(t, "GET", "/file"),
},
{
// an escaped suffix pattern must not match the decoded character
rule: Rewrite{StripPathSuffix: "%2f"},
input: newRequest(t, "GET", "/file/"),
expect: newRequest(t, "GET", "/file/"),
},
{
// a decoded suffix pattern still matches the path's escaped form
rule: Rewrite{StripPathSuffix: ".html"},
input: newRequest(t, "GET", "/a%2ehtml"), // %2e == '.'
expect: newRequest(t, "GET", "/a"),
},
{
rule: Rewrite{URISubstring: []substrReplacer{{Find: "findme", Replace: "replaced"}}},