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
-2
@@ -39,7 +39,7 @@ import type { MeshControl } from '../http';
|
||||
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
||||
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
||||
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
|
||||
import { compilePattern } from '../http/router';
|
||||
import { compilePattern, normalizeRequestPath } from '../http/router';
|
||||
|
||||
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
|
||||
|
||||
@@ -1290,7 +1290,17 @@ function buildAppUpgrade(
|
||||
|
||||
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
||||
|
||||
const path = request.url.split('?')[0];
|
||||
let path: string;
|
||||
|
||||
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
|
||||
// otherwise reject out of the matcher and close with 1011, a server-error code for a client error.
|
||||
try {
|
||||
path = normalizeRequestPath(request.url.split('?')[0]);
|
||||
} catch {
|
||||
ready.close(1008, 'invalid request path');
|
||||
return;
|
||||
}
|
||||
|
||||
const meshControl = getMeshControl();
|
||||
|
||||
// The reserved mesh path, checked before route matching: this is what lets a teapot export
|
||||
|
||||
+13
-1
@@ -10,6 +10,7 @@ import { nodeRequire } from '../node-require';
|
||||
*/
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
const CONNECTING = 0; // WebSocket.CONNECTING
|
||||
const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient
|
||||
|
||||
/** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */
|
||||
@@ -69,7 +70,18 @@ export function eventSocket(host: EventfulSocket): WsSocket {
|
||||
ac.abort();
|
||||
});
|
||||
|
||||
return neutralSocket(host, inbound, ac);
|
||||
const socket = neutralSocket(host, inbound, ac);
|
||||
const closeNow = socket.close;
|
||||
|
||||
// Deno hands the socket over still CONNECTING: its 101 has not gone out yet, and a close in
|
||||
// that state is a no-op, so a route that refuses straight away (1008) left the peer hanging.
|
||||
// Deferring to 'open' is what lets that close reach the client at all.
|
||||
return Object.assign(socket, {
|
||||
close: (code?: number, reason?: string) => {
|
||||
if (host.readyState === CONNECTING) host.addEventListener('open', () => closeNow(code, reason));
|
||||
else closeNow(code, reason);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+54
-19
@@ -3,6 +3,7 @@ import { channel } from '../channel';
|
||||
import type { Bus } from '../bus';
|
||||
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
|
||||
import type { WsRouteDef, MeshControl } from './types';
|
||||
import { normalizeRequestPath } from './router';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
|
||||
@@ -16,9 +17,9 @@ function loadWss(): any | null {
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes a 501 Not Implemented status to the raw socket and destroys it. */
|
||||
function reject501(socket: any): void {
|
||||
socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n');
|
||||
/** Writes a bodyless HTTP status to the raw socket and destroys it. */
|
||||
function rejectUpgrade(socket: any, status: number, text: string): void {
|
||||
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
@@ -35,7 +36,7 @@ function handleMeshUpgrade(
|
||||
if (path !== meshControl.path) return false;
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
rejectUpgrade(socket, 501, 'Not Implemented');
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -102,24 +103,58 @@ export function attachWs(
|
||||
const WebSocketServer = loadWss();
|
||||
const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const path = (req.url ?? '/').split('?')[0];
|
||||
// A peer that resets mid-rejection must not raise an unhandled 'error' on a socket nobody
|
||||
// else is listening to yet: that is as fatal as a throw.
|
||||
socket.on('error', () => {});
|
||||
|
||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
|
||||
|
||||
const route = matchWsRoute(wsRoutes, path);
|
||||
|
||||
if (!route) {
|
||||
socket.destroy();
|
||||
return;
|
||||
// Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an
|
||||
// uncaught exception that takes the whole process down, not a 500 for one client.
|
||||
try {
|
||||
routeUpgrade(wss, wsRoutes, req, socket, head, bus, meshControl, streams);
|
||||
} catch {
|
||||
if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
|
||||
else socket.destroy();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
return;
|
||||
}
|
||||
/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
|
||||
function routeUpgrade(
|
||||
wss: any,
|
||||
wsRoutes: WsRouteDef[],
|
||||
req: http.IncomingMessage,
|
||||
socket: any,
|
||||
head: Buffer,
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
streams?: Set<() => void>,
|
||||
): void {
|
||||
let path: string;
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
|
||||
});
|
||||
// The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed
|
||||
// escape reaches `decodeURIComponent` in the matcher and throws, and `//` silently matches.
|
||||
try {
|
||||
path = normalizeRequestPath((req.url ?? '/').split('?')[0]);
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, 'Bad Request');
|
||||
return;
|
||||
}
|
||||
|
||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
|
||||
|
||||
const route = matchWsRoute(wsRoutes, path);
|
||||
|
||||
if (!route) {
|
||||
rejectUpgrade(socket, 404, 'Not Found');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!wss) {
|
||||
rejectUpgrade(socket, 501, 'Not Implemented');
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user