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 7 commits into
base: master
Choose a base branch
from
Open
14 changes: 10 additions & 4 deletions src/http-proxy-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,16 @@ export class HttpProxyMiddleware {
};

private handleUpgrade = async (req: Request, socket, head) => {
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
27 changes: 20 additions & 7 deletions src/plugins/default/error-response-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,32 @@
import type { Socket } from 'net';
import { getStatusCode } from '../../status-code';
import { Plugin, Response } from '../../types';

function isResponseLike(obj: any): obj is Response {
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: Response, target?) => {
proxyServer.on('error', (err, req, res: Response | Socket, 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 (res.writeHead && !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
Original file line number Diff line number Diff line change
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();
});
});
});
});