Bun.serve routes: matching uses the raw request-target but req.url is dot-segment-normalised (`..` reaches a :param route; `#` lands in params)
What version of Bun is running?
1.4.3-canary.1+5f554969b
What platform is your computer?
Linux 7.0.0-31-generic x86_64
What steps can reproduce the bug?
Save as repro.ts and run bun repro.ts. It sends raw request-targets over a socket, because fetch() normalises the path before sending.
import net from "node:net";
const server = Bun.serve({
port: 0,
routes: {
"/public/:file": (req) => Response.json({ route: "/public/:file", params: req.params, url: new URL(req.url).pathname }),
"/admin": () => Response.json({ route: "/admin" }),
},
fetch: (req) => Response.json({ route: "fetch", url: new URL(req.url).pathname }),
});
function raw(path: string): Promise<string> {
return new Promise((resolve) => {
const socket = net.connect(server.port!, "127.0.0.1");
let data = "";
socket.on("data", (chunk) => (data += chunk));
socket.on("end", () => resolve(data.split("\r\n\r\n")[1]));
socket.write(`GET ${path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n`);
});
}
console.log(`Bun ${Bun.version} (${Bun.revision}) ${process.platform} ${process.arch}`);
for (const path of ["/public/..", "/public/%2e%2e", "/public/../admin", "/public/a.txt#frag"]) {
console.log(`GET ${path.padEnd(20)} -> ${await raw(path)}`);
}
server.stop(true);Output:
GET /public/.. -> {"route":"/public/:file","params":{"file":".."},"url":"/"}
GET /public/%2e%2e -> {"route":"/public/:file","params":{"file":".."},"url":"/"}
GET /public/../admin -> {"route":"fetch","url":"/admin"}
GET /public/a.txt#frag -> {"route":"/public/:file","params":{"file":"a.txt#frag"},"url":"/public/a.txt"}What is the expected behavior?
The route that is chosen and the req.url the handler receives describe the same path. Either routes match the normalised path (so /public/../admin reaches the /admin route, and /public/.. does not reach /public/:file), or req.url keeps the raw path. A #fragment in the request-target should not end up inside a param.
What do you see instead?
routes matches the raw request-target, while req.url is dot-segment-normalised (.. and %2e%2e removed):
/public/..and/public/%2e%2ereach the/public/:filehandler withparams.file === "..", whilereq.urlis/./public/../admindoes not reach the/adminroute; it falls through tofetchwithreq.url/admin.- A raw
#fragis included in the last param ("a.txt#frag") but not inreq.url.
A handler that trusts req.params sees .. as a filename, while one that trusts req.url sees a different path from the one it was routed on.
Additional information
Related but different: #37603 (literal segments match raw bytes while :param segments are percent-decoded). This issue is about dot-segments and fragments, and about req.url disagreeing with the matched route.
Source: oven-sh/bun