Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(websocket): handle errors in handleUpgrade #823

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/http-proxy-middleware.ts
Expand Up @@ -95,10 +95,16 @@ export class HttpProxyMiddleware<TReq, TRes> {
};

private handleUpgrade = async (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => {
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
const activeProxyOptions = await this.prepareProxyRequest(req);
this.proxy.ws(req, socket, head, activeProxyOptions);
debug('server upgrade event received. Proxying WebSocket');
try {
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
const activeProxyOptions = await this.prepareProxyRequest(req);
this.proxy.ws(req, socket, head, activeProxyOptions);
debug('server upgrade event received. Proxying WebSocket');
}
} catch (err) {
// This error does not include the URL as the fourth argument as we won't
// have the URL if `this.prepareProxyRequest` throws an error.
this.proxy.emit('error', err, req, socket);
}
};

Expand Down
26 changes: 20 additions & 6 deletions src/plugins/default/error-response-plugin.ts
@@ -1,19 +1,33 @@
import type * as http from 'http';
import type { Socket } from 'net';
import { getStatusCode } from '../../status-code';
import { Plugin } from '../../types';

function isResponseLike(obj: any): obj is http.ServerResponse {
return obj && typeof obj.writeHead === 'function';
}

function isSocketLike(obj: any): obj is Socket {
return obj && typeof obj.write === 'function' && !('writeHead' in obj);
}
Comment on lines +10 to +12
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can't just check for instanceof Socket since per the documentation, the user may be able to provide a different socket implementation:

This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.


export const errorResponsePlugin: Plugin = (proxyServer, options) => {
proxyServer.on('error', (err, req, res, target?) => {
// Re-throw error. Not recoverable since req & res are empty.
if (!req && !res) {
throw err; // "Error: Must provide a proper URL as target"
}

if ('writeHead' in res && !res.headersSent) {
const statusCode = getStatusCode((err as unknown as any).code);
res.writeHead(statusCode);
}
if (isResponseLike(res)) {
if (!res.headersSent) {
const statusCode = getStatusCode((err as unknown as any).code);
res.writeHead(statusCode);
}

const host = req.headers && req.headers.host;
res.end(`Error occurred while trying to proxy: ${host}${req.url}`);
const host = req.headers && req.headers.host;
res.end(`Error occurred while trying to proxy: ${host}${req.url}`);
} else if (isSocketLike(res)) {
res.destroy();
}
});
};
40 changes: 32 additions & 8 deletions test/e2e/websocket.spec.ts
Expand Up @@ -97,15 +97,14 @@ describe('E2E WebSocket proxy', () => {

describe('with router and pathRewrite', () => {
beforeEach(() => {
// override
proxyServer = createApp(
const proxyMiddleware = createProxyMiddleware({
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was a bug with the existing tests: because it didn't reassign proxyMiddleware, the proxyMiddleware.upgrade access a few lines after this was reading from the wrong object.

// cSpell:ignore notworkinghost
createProxyMiddleware({
target: 'ws://notworkinghost:6789',
router: { '/socket': `ws://localhost:${WS_SERVER_PORT}` },
pathRewrite: { '^/socket': '' },
})
).listen(SERVER_PORT);
target: 'ws://notworkinghost:6789',
router: { '/socket': `ws://localhost:${WS_SERVER_PORT}` },
pathRewrite: { '^/socket': '' },
});

proxyServer = createApp(proxyMiddleware).listen(SERVER_PORT);

proxyServer.on('upgrade', proxyMiddleware.upgrade);
});
Expand All @@ -124,4 +123,29 @@ describe('E2E WebSocket proxy', () => {
ws.send('foobar');
});
});

describe('with error in router', () => {
beforeEach(() => {
const proxyMiddleware = createProxyMiddleware({
// cSpell:ignore notworkinghost
target: `http://notworkinghost:6789`,
router: async () => {
throw new Error('error');
},
});

proxyServer = createApp(proxyMiddleware).listen(SERVER_PORT);

proxyServer.on('upgrade', proxyMiddleware.upgrade);
});

it('should handle error', (done) => {
ws = new WebSocket(`ws://localhost:${SERVER_PORT}/socket`);

ws.on('error', (err) => {
expect(err).toBeTruthy();
done();
});
});
});
});