Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
12 changes: 8 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -116,9 +122,7 @@ function validateDestination (dest) {
throw invalidDestination()
}

decoded = decoded.replaceAll('\\', '/')

if (decoded.split('/').includes('..')) {
if (decoded.includes('\\') || decoded.split('/').includes('..')) {
throw invalidDestination()
}
}
Expand Down
6 changes: 2 additions & 4 deletions test/http-prefix-rewrite.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Expand Down Expand Up @@ -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)
})
Expand Down
62 changes: 51 additions & 11 deletions test/ws-prefix-rewrite.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -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))
}
})
}
Expand Down Expand Up @@ -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 => {
Expand Down
Loading