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

Enable on headers handler to reject connection modifying headers param #1966

Closed
Closed
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
7 changes: 7 additions & 0 deletions lib/websocket-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,13 @@ class WebSocketServer extends EventEmitter {
socket.write(headers.concat('\r\n').join('\r\n'));
socket.removeListener('error', socketOnError);

if (headers.length==0 || !headers[0].startsWith('HTTP/1.1 101 ')) {
//An error status and headers were just send. Terminate the connection
socket.end();
//as the socket is not writable the code will not be used
return abortHandshake(socket, 500);
}

ws.setSocket(socket, head, {
maxPayload: this.options.maxPayload,
skipUTF8Validation: this.options.skipUTF8Validation
Expand Down
53 changes: 53 additions & 0 deletions test/onheaeder-httperr.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^ws$" }] */

'use strict';

const WebSocket = require('..');


describe('WebSocketServer', () => {
it('successfully rejects a connection via error heders in on headers handler', (done) => {
const wss = new WebSocket.Server(
{
port: 0
},
() => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
wss.on('connection', (ws) => {
done(new Error("WSS: on connection?! We should not be here!"));
ws.close();
wss.close();
});
wss.on('headers', (headers,req)=>{
headers.length=0;
headers.push('HTTP/1.1 418 I\'m a teapot');
headers.push('Connection: close');
});

ws.on('open', () => {
done(new Error("WS: on connection?! We should not be here!"));
ws.close();
wss.close();
});
ws.on('error',(err)=>{
if (err instanceof Error) {
if (err.message.endsWith(' 418')) {
//end with no error
done();
ws.close();
wss.close();
} else {
done(new Error("WS: on err but err is not as expected!"));
ws.close();
wss.close();
}
} else {
done(new Error("WS: on err but err is not instance of Error!"));
ws.close();
wss.close();
}
});
}
);

})});