Fix quadratic percent decoding in FindMyWay (#10619)

This commit is contained in:
effect-bot
2026-11-13 18:54:46 +01:00
committed by GitHub
parent 94fe28e8c5
commit 77fa72ae50
3 changed files with 30 additions and 3 deletions
@@ -0,0 +1,5 @@
---
"effect": patch
---
Fix slow `FindMyWay` and `HttpRouter` lookups for request paths containing many encoded percent signs.
@@ -954,6 +954,8 @@ function safeDecodeURI(path: string) {
let shouldDecodeParam = false
let querystring = ""
let escaped = ""
let escapedEnd = 0
for (let i = 1; i < path.length; i++) {
const charCode = path.charCodeAt(i)
@@ -966,11 +968,13 @@ function safeDecodeURI(path: string) {
shouldDecode = true
} else {
shouldDecodeParam = true
// %25 - encoded % char. We need to encode one more time to prevent double decoding
// %25 - encoded % char. We need to encode one more time to prevent double decoding.
// Append the escaped text instead of rewriting `path`, which copies the whole path
// for every escape (find-my-way PR #455).
if (highCharCode === 50 && lowCharCode === 53) {
shouldDecode = true
path = path.slice(0, i + 1) + "25" + path.slice(i + 1)
i += 2
escaped += path.slice(escapedEnd, i) + "%2525"
escapedEnd = i + 3
}
i += 2
}
@@ -983,6 +987,9 @@ function safeDecodeURI(path: string) {
break
}
}
if (escapedEnd > 0) {
path = escaped + path.slice(escapedEnd)
}
const decodedPath = shouldDecode ? decodeURI(path) : path
return { path: decodedPath, querystring, shouldDecodeParam } as const
}
@@ -44,3 +44,18 @@ it("normalizes duplicate path slashes without changing query slashes", () => {
assert.deepStrictEqual(result?.params, { id: "1" })
assert.deepStrictEqual(result?.searchParams, { u: "https://x.com/y" })
})
it("decodes percent-heavy parameters exactly once without changing query boundaries", () => {
const router = Router.make<boolean>({ maxParamLength: 200_000 })
router.on("GET", "/test/:id", true)
const encoded = "%25".repeat(50_000) + "%252F%2f%C3%A9%20%25"
const decoded = "%".repeat(50_000) + "%2F/é %"
for (const delimiter of ["?", "#", ";"]) {
const result = router.find("GET", "/test/" + encoded + delimiter + "value=%2525")
assert.strictEqual(result?.handler, true)
assert.deepStrictEqual(result?.params, { id: decoded })
assert.deepStrictEqual(result?.searchParams, { value: "%25" })
}
assert.deepStrictEqual(router.find("GET", "/test/" + encoded)?.params, { id: decoded })
assert.strictEqual(router.find("GET", "/test/" + encoded + "%zz"), undefined)
})