fix(ws): reject malformed upgrades instead of crashing the server
The Node 'upgrade' listener matched the raw request path without the normalization HTTP runs. A bad percent escape in a param segment threw URIError synchronously inside the listener, an uncaught exception that ends the process, and '//' silently matched a route HTTP refuses. Upgrades now normalize the path first: malformed escapes and repeated slashes get a 400, an unknown route a written 404 instead of a bare destroy, and any other throw in the listener a 500. app.upgrade (Deno/Bun/edge) closes 1008 'invalid request path' rather than 1011. On Deno the adapter's socket is still CONNECTING when an early 1008 is sent, and that close was a no-op that left the peer hanging; eventSocket now defers such a close to 'open'. Closes #104 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
10 files changed
+309
-23
No files matched your search
@@ -12,7 +12,16 @@ class Rt {
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
@Route('/room')
|
||||
class Room {
|
||||
@Ws('/:name')
|
||||
join(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `room:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt, Room] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
@@ -96,4 +105,18 @@ describe('app.upgrade', () => {
|
||||
await app.upgrade(req, socket);
|
||||
expect(closedCode).toBe(1008);
|
||||
});
|
||||
|
||||
it.each(['/rt/%E0%A4%A', '/room/%E0%A4%A', '//rt//echo'])(
|
||||
'closes 1008 on the malformed path %s instead of rejecting (#104)',
|
||||
async (url) => {
|
||||
const { socket } = fakeSocket();
|
||||
let closed: [number | undefined, string | undefined] | undefined;
|
||||
socket.close = (c, r) => {
|
||||
closed = [c, r];
|
||||
};
|
||||
const req: WsRequest = { url, headers: {}, protocol: 'http', ip: '' };
|
||||
await app.upgrade(req, socket);
|
||||
expect(closed).toEqual([1008, 'invalid request path']);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -20,6 +20,13 @@ class Rt {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
|
||||
@Ws('/room/:name')
|
||||
room(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `room:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
class M {}
|
||||
@@ -47,3 +54,22 @@ test('serveBun: HTTP + WebSocket round-trip', async () => {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011.
|
||||
test('serveBun: a malformed upgrade path closes 1008 and the server keeps serving', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await serveBun(app, { port: 0 });
|
||||
const port = server.port;
|
||||
try {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`);
|
||||
const closed = await new Promise<{ code: number; reason: string }>((resolve) => {
|
||||
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
|
||||
});
|
||||
expect(closed).toEqual({ code: 1008, reason: 'invalid request path' });
|
||||
|
||||
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
||||
expect(httpRes.status).toBe(200);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
@@ -28,6 +28,13 @@ class Rt {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
|
||||
@Ws('/room/:name')
|
||||
room(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `room:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
@@ -69,3 +76,32 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () =
|
||||
await server.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011.
|
||||
Deno.test('serveDeno: a malformed upgrade path closes 1008 and the server keeps serving', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
let port = 0;
|
||||
const server = await serveDeno(app, {
|
||||
port: 0,
|
||||
onListen: (addr) => {
|
||||
port = addr.port;
|
||||
},
|
||||
});
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
try {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`);
|
||||
const closed = await new Promise<{ code: number; reason: string }>((resolve) => {
|
||||
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
|
||||
});
|
||||
assertEquals(closed, { code: 1008, reason: 'invalid request path' });
|
||||
|
||||
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
||||
assertEquals(httpRes.status, 200);
|
||||
await httpRes.body?.cancel();
|
||||
} finally {
|
||||
await server.shutdown();
|
||||
}
|
||||
});
|
||||
@@ -84,6 +84,19 @@ async function main() {
|
||||
});
|
||||
assert.equal(got, 'echo:hi');
|
||||
|
||||
// #104: a malformed escape in a param segment closes 1008 instead of 1011, and HTTP still serves.
|
||||
const badRes = await mf.dispatchFetch('http://localhost/rt/room/%E0%A4%A', {
|
||||
headers: { Upgrade: 'websocket' },
|
||||
});
|
||||
const bad = badRes.webSocket;
|
||||
assert.ok(bad, 'expected a client webSocket on the 101 response');
|
||||
const closed = new Promise<{ code: number; reason: string }>((resolve) =>
|
||||
bad.addEventListener('close', (e: { code: number; reason: string }) => resolve({ code: e.code, reason: e.reason })),
|
||||
);
|
||||
bad.accept();
|
||||
assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' });
|
||||
assert.equal((await mf.dispatchFetch('http://localhost/rt/hello')).status, 200);
|
||||
|
||||
console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi — PASS');
|
||||
} finally {
|
||||
await mf.dispose();
|
||||
|
||||
@@ -17,6 +17,13 @@ class Rt {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
|
||||
@Ws('/room/:name')
|
||||
room(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `room:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';
|
||||
import net from 'net';
|
||||
import type http from 'http';
|
||||
import WebSocket from 'ws';
|
||||
import { createApp, Route, Get, Ws, Module, ctx } from '../src/index';
|
||||
|
||||
// Regression for #104: these drive the real Node `'upgrade'` listener through a `listen(0)` server,
|
||||
// not `app.upgrade`. The requests are written by hand over a raw socket because a WebSocket client
|
||||
// refuses or re-encodes the malformed URLs this is about.
|
||||
|
||||
@Route('/rt')
|
||||
class Rt {
|
||||
@Ws('/echo')
|
||||
echo(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
|
||||
// A param route is what makes the bad escape fatal: only param segments are decoded on match.
|
||||
@Ws('/room/:name')
|
||||
room(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `room:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Route('/health')
|
||||
class Health {
|
||||
@Get('/')
|
||||
ok() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt, Health] })
|
||||
class M {}
|
||||
|
||||
/** Writes a raw upgrade request for `path` and resolves with everything the server sent before closing. */
|
||||
function rawUpgrade(port: number, path: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = net.connect(port, '127.0.0.1');
|
||||
let data = '';
|
||||
socket.on('connect', () =>
|
||||
socket.write(
|
||||
`GET ${path} HTTP/1.1\r\nHost: 127.0.0.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
|
||||
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n',
|
||||
),
|
||||
);
|
||||
socket.on('data', (chunk) => (data += chunk.toString()));
|
||||
socket.on('close', () => resolve(data));
|
||||
socket.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
describe('Node upgrade listener rejects malformed upgrades (#104)', () => {
|
||||
let server: http.Server;
|
||||
let port: number;
|
||||
const uncaught: unknown[] = [];
|
||||
const onUncaught = (err: unknown) => uncaught.push(err);
|
||||
|
||||
beforeAll(async () => {
|
||||
process.on('uncaughtException', onUncaught);
|
||||
process.on('unhandledRejection', onUncaught);
|
||||
const app = createApp({ modules: [M] });
|
||||
server = await app.listen(0);
|
||||
port = (server.address() as { port: number }).port;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
process.off('uncaughtException', onUncaught);
|
||||
process.off('unhandledRejection', onUncaught);
|
||||
await new Promise((r) => server.close(r));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// T6: a normal request on a new connection succeeds after every rejected upgrade.
|
||||
const res = await fetch(`http://127.0.0.1:${port}/health`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(uncaught).toEqual([]);
|
||||
});
|
||||
|
||||
it('T1: malformed percent-encoding gets a 400 and the socket closes', async () => {
|
||||
expect(await rawUpgrade(port, '/rt/%E0%A4%A')).toMatch(/^HTTP\/1\.1 400 /);
|
||||
});
|
||||
|
||||
it('T1: malformed percent-encoding in a param segment gets a 400 instead of crashing', async () => {
|
||||
expect(await rawUpgrade(port, '/rt/room/%E0%A4%A')).toMatch(/^HTTP\/1\.1 400 /);
|
||||
});
|
||||
|
||||
it('T2: invalid hex in a percent escape gets a 400', async () => {
|
||||
expect(await rawUpgrade(port, '/rt/room/%ZZ')).toMatch(/^HTTP\/1\.1 400 /);
|
||||
});
|
||||
|
||||
it('T3: a repeated slash gets a 400 instead of matching /rt/echo', async () => {
|
||||
expect(await rawUpgrade(port, '//rt//echo')).toMatch(/^HTTP\/1\.1 400 /);
|
||||
});
|
||||
|
||||
it('T4: a long path below the header limit takes the normal miss path (404)', async () => {
|
||||
expect(await rawUpgrade(port, `/rt/${'a'.repeat(8 * 1024)}`)).toMatch(/^HTTP\/1\.1 404 /);
|
||||
});
|
||||
|
||||
it('T5: an unknown ws route gets a written 404, then close', async () => {
|
||||
expect(await rawUpgrade(port, '/nope')).toMatch(/^HTTP\/1\.1 404 /);
|
||||
});
|
||||
|
||||
it('T7: a valid upgrade still echoes', async () => {
|
||||
const client = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`);
|
||||
await new Promise((r) => client.on('open', r));
|
||||
const got = new Promise<string>((r) => client.on('message', (d) => r(d.toString())));
|
||||
client.send('hi');
|
||||
expect(await got).toBe('echo:hi');
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user