diff --git a/README.md b/README.md index c5a4437..ced27a2 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,8 @@ Rewrite the prefix to the specified string. Default: `''`. Destination paths containing dot-segments that could escape the rewritten prefix are rejected with a `400` response. This check also accounts for percent-encoded `/` and `\` path separators. +Destination paths containing a backslash (`\`), raw or percent-encoded as `%5C`, are rejected with a `400` response for both HTTP requests and WebSocket upgrades. Backslashes in the query string are forwarded unchanged. + When `prefix`/`rewritePrefix` contain route parameters (e.g. `/:tenantId/public-avatar`), the already URL-decoded parameter values are re-encoded before being spliced into the rewritten prefix. This prevents a decoded `/`, `#`, or `?` (e.g. sent as `%2f`, `%23`, `%3f`) from injecting additional upstream path segments or amputating a mandatory suffix such as `/public-avatar`. ### `preHandler` diff --git a/index.js b/index.js index b825e27..65ddd37 100644 --- a/index.js +++ b/index.js @@ -97,13 +97,19 @@ function invalidDestination () { } function validateDestination (dest) { + // Backslashes, raw or percent-encoded, are rejected anywhere in the path: + // URL parsers treat them as separators, and @fastify/reply-from refuses them + // too, so HTTP and WebSocket requests behave the same. + if (dest.includes('\\')) { + throw invalidDestination() + } + const normalizedReference = dest .replaceAll('\t', '') .replaceAll('\n', '') .replaceAll('\r', '') .replaceAll('\0', '') .trimStart() - .replaceAll('\\', '/') if (absoluteUrlPattern.test(normalizedReference) || normalizedReference.startsWith('//')) { throw invalidDestination() @@ -116,9 +122,7 @@ function validateDestination (dest) { throw invalidDestination() } - decoded = decoded.replaceAll('\\', '/') - - if (decoded.split('/').includes('..')) { + if (decoded.includes('\\') || decoded.split('/').includes('..')) { throw invalidDestination() } } diff --git a/test/http-prefix-rewrite.js b/test/http-prefix-rewrite.js index 295c67b..d1f4000 100644 --- a/test/http-prefix-rewrite.js +++ b/test/http-prefix-rewrite.js @@ -67,8 +67,7 @@ test('HTTP paths cannot escape rewritePrefix', async t => { t.assert.strictEqual(regular.statusCode, 200) t.assert.strictEqual(regular.body, 'internal:/internal/foo') - // @fastify/reply-from rejects decoded backslashes in the destination path - // since v12.8.1, so a percent-encoded backslash is no longer forwarded. + // Backslashes, raw or percent-encoded, are rejected anywhere in the path. const encodedBackslash = await request(port, '/pub/foo%5Cbar') t.assert.strictEqual(encodedBackslash.statusCode, 400) }) @@ -167,8 +166,7 @@ test('reply.fromParameters cannot escape rewritePrefix', async t => { t.assert.strictEqual(regular.statusCode, 200) t.assert.strictEqual(regular.body, 'internal:/internal/foo') - // @fastify/reply-from rejects decoded backslashes in the destination path - // since v12.8.1, so a percent-encoded backslash is no longer forwarded. + // Backslashes, raw or percent-encoded, are rejected anywhere in the path. const encodedBackslash = await request(port, '/pub/foo%5Cbar') t.assert.strictEqual(encodedBackslash.statusCode, 400) }) diff --git a/test/ws-prefix-rewrite.js b/test/ws-prefix-rewrite.js index 839ef74..2be66fa 100644 --- a/test/ws-prefix-rewrite.js +++ b/test/ws-prefix-rewrite.js @@ -81,7 +81,7 @@ async function proxyServer (t, backendURL, backendPath, proxyOptions, wrapperOpt } } -async function processRequest (t, frontendURL, path, expected, httpExpected = expected) { +async function processRequest (t, frontendURL, path, expected) { const url = new URL(path, frontendURL) const wsUrl = url.href.replace('http:', 'ws:') const ws = new WebSocket(wsUrl) @@ -114,10 +114,10 @@ async function processRequest (t, frontendURL, path, expected, httpExpected = ex } t.assert.strictEqual(wsResult, expected) - t.assert.strictEqual(gotResult, httpExpected) + t.assert.strictEqual(gotResult, expected) } -async function handleProxy (info, { backendPath, proxyOptions, wrapperOptions, httpExpected }, expected, ...paths) { +async function handleProxy (info, { backendPath, proxyOptions, wrapperOptions }, expected, ...paths) { test(info, async function (t) { const backend = Fastify({ logger: { level } }) const resources = { frontend: null } @@ -149,7 +149,7 @@ async function handleProxy (info, { backendPath, proxyOptions, wrapperOptions, h resources.frontend = frontend for (const path of paths) { - await processRequest(t, frontendURL, path, expected(path), httpExpected ? httpExpected(path) : expected(path)) + await processRequest(t, frontendURL, path, expected(path)) } }) } @@ -218,16 +218,56 @@ handleProxy( ) handleProxy( - 'percent-encoded backslashes remain path data', + 'percent-encoded backslashes in the path are rejected for HTTP and WebSocket', { backendPath: '/internal', - proxyOptions: { websocket: true, prefix: '/pub' }, - // Plain HTTP requests go through @fastify/reply-from, which rejects - // decoded backslashes in the destination path since v12.8.1. - httpExpected: () => 'error' + proxyOptions: { websocket: true, prefix: '/pub' } }, - () => '/internal/foo%5C..bar', - '/pub/foo%5C..bar' + () => 'error', + '/pub/foo%5C..bar', + '/pub/foo%5Cbar', + '/pub/foo%5cbar' +) + +test('raw backslashes without dot segments in WebSocket paths are rejected', async t => { + const backend = Fastify({ logger: { level } }) + const frontend = Fastify({ logger: { level } }) + + t.after(async () => { + await closeFastify(frontend) + await closeFastify(backend) + }) + + await backend.register(fastifyWebSocket) + + let upstreamHit = false + backend.get('/internal/*', { websocket: true }, socket => { + upstreamHit = true + socket.close() + }) + await backend.listen({ port: 0, host: '127.0.0.1' }) + + frontend.register(proxy, { + upstream: `ws://127.0.0.1:${backend.server.address().port}`, + websocket: true, + prefix: '/pub', + rewritePrefix: '/internal' + }) + await frontend.listen({ port: 0, host: '127.0.0.1' }) + + const statusLine = await rawWebSocketUpgrade(frontend.server.address().port, '/pub/foo\\bar') + t.assert.strictEqual(statusLine, 'HTTP/1.1 400 Bad Request') + t.assert.strictEqual(upstreamHit, false) +}) + +handleProxy( + 'percent-encoded backslashes in the query string are forwarded', + { + backendPath: '/internal', + proxyOptions: { websocket: true, prefix: '/pub' } + }, + (path) => path.replace('/pub', '/internal'), + '/pub/foo?path=C%3A%5Ctemp' ) test('preRewrite cannot override the WebSocket upstream origin', async t => {