Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

caddyhttp: Smarter path matching and rewriting #4948

Merged
merged 15 commits into from
Aug 16, 2022
Merged
6 changes: 3 additions & 3 deletions modules/caddyhttp/caddyhttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,17 +255,17 @@ func CleanPath(p string, collapseSlashes bool) string {

// replace repeated slashes with an invalid/impossible URI character
// to avoid collisions; then clean the path, then replace them back
const tmpSlash = 0xff
var tmpSlash = string("\xff/")
var sb strings.Builder
for i, ch := range p {
if ch == '/' && i > 0 && p[i-1] == '/' {
sb.WriteByte(tmpSlash)
sb.WriteString(tmpSlash)
continue
}
sb.WriteRune(ch)
}
halfCleaned := cleanPath(sb.String())
halfCleaned = strings.ReplaceAll(halfCleaned, string([]byte{tmpSlash}), "/")
halfCleaned = strings.ReplaceAll(halfCleaned, "/\xff", "/")
mholt marked this conversation as resolved.
Show resolved Hide resolved

return halfCleaned
}
Expand Down
57 changes: 57 additions & 0 deletions modules/caddyhttp/caddyhttp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,60 @@ func TestSanitizedPathJoin(t *testing.T) {
}
}
}

func TestCleanPath(t *testing.T) {
for i, tc := range []struct {
input string
mergeSlashes bool
expect string
}{
{
input: "/foo",
expect: "/foo",
},
{
input: "/foo/",
expect: "/foo/",
},
{
input: "//foo",
expect: "//foo",
},
{
input: "//foo",
mergeSlashes: true,
expect: "/foo",
},
{
input: "/foo//bar/",
mergeSlashes: true,
expect: "/foo/bar/",
},
{
input: "/foo/./.././bar",
expect: "/bar",
},
{
input: "/foo//./..//./bar",
expect: "/foo//bar",
},
{
input: "/foo///./..//./bar",
expect: "/foo///bar",
},
{
input: "/foo///./..//.",
expect: "/foo//",
},
{
input: "/foo//./bar",
expect: "/foo//bar",
},
} {
actual := CleanPath(tc.input, tc.mergeSlashes)
if actual != tc.expect {
t.Errorf("Test %d [input='%s' mergeSlashes=%t]: Got '%s', expected '%s'",
i, tc.input, tc.mergeSlashes, actual, tc.expect)
}
}
}