Skip to content

Commit dd28c5c

Browse files
authored
fix: close rejected HTTP/2 WebSocket handshake streams (#5873)
* fix: close rejected HTTP/2 WebSocket handshake streams Signed-off-by: Matteo Collina <[email protected]> * refactor: move WebSocket handshake failure cleanup to module scope Signed-off-by: Matteo Collina <[email protected]> --------- Signed-off-by: Matteo Collina <[email protected]>
1 parent 5e0a2f8 commit dd28c5c

3 files changed

Lines changed: 83 additions & 8 deletions

File tree

‎lib/web/websocket/connection.js‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -101,13 +101,13 @@ function establishWebSocketConnection (url, protocols, client, handler, options)
101101
// The presence of a session property on the socket indicates HTTP2
102102
// HTTP1
103103
if (response.socket?.session == null) {
104-
failWebsocketConnection(handler, 1002, 'Received network error or non-101 status code.', response.error)
104+
failHandshake(handler, response, 1002, 'Received network error or non-101 status code.', response.error)
105105
return
106106
}
107107

108108
// HTTP2
109109
if (response.status !== 200) {
110-
failWebsocketConnection(handler, 1002, 'Received network error or non-200 status code.', response.error)
110+
failHandshake(handler, response, 1002, 'Received network error or non-200 status code.', response.error)
111111
return
112112
}
113113
}
@@ -122,7 +122,7 @@ function establishWebSocketConnection (url, protocols, client, handler, options)
122122
// header list results in null, failure, or the empty byte
123123
// sequence, then fail the WebSocket connection.
124124
if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
125-
failWebsocketConnection(handler, 1002, 'Server did not respond with sent protocols.')
125+
failHandshake(handler, response, 1002, 'Server did not respond with sent protocols.')
126126
return
127127
}
128128

@@ -138,7 +138,7 @@ function establishWebSocketConnection (url, protocols, client, handler, options)
138138
// _Fail the WebSocket Connection_.
139139
// For H2, no upgrade header is expected.
140140
if (response.socket.session == null && response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
141-
failWebsocketConnection(handler, 1002, 'Server did not set Upgrade header to "websocket".')
141+
failHandshake(handler, response, 1002, 'Server did not set Upgrade header to "websocket".')
142142
return
143143
}
144144

@@ -148,7 +148,7 @@ function establishWebSocketConnection (url, protocols, client, handler, options)
148148
// MUST _Fail the WebSocket Connection_.
149149
// For H2, no connection header is expected.
150150
if (response.socket.session == null && response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
151-
failWebsocketConnection(handler, 1002, 'Server did not set Connection header to "upgrade".')
151+
failHandshake(handler, response, 1002, 'Server did not set Connection header to "upgrade".')
152152
return
153153
}
154154

@@ -165,7 +165,7 @@ function establishWebSocketConnection (url, protocols, client, handler, options)
165165
const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
166166
const digest = crypto.hash('sha1', keyValue + uid, 'base64')
167167
if (secWSAccept !== digest) {
168-
failWebsocketConnection(handler, 1002, 'Incorrect hash received in Sec-WebSocket-Accept header.')
168+
failHandshake(handler, response, 1002, 'Incorrect hash received in Sec-WebSocket-Accept header.')
169169
return
170170
}
171171
}
@@ -184,7 +184,7 @@ function establishWebSocketConnection (url, protocols, client, handler, options)
184184
extensions = parseExtensions(secExtension)
185185

186186
if (!extensions.has('permessage-deflate')) {
187-
failWebsocketConnection(handler, 1002, 'Sec-WebSocket-Extensions header does not match.')
187+
failHandshake(handler, response, 1002, 'Sec-WebSocket-Extensions header does not match.')
188188
return
189189
}
190190
}
@@ -205,7 +205,7 @@ function establishWebSocketConnection (url, protocols, client, handler, options)
205205
// the selected subprotocol values in its response for the connection to
206206
// be established.
207207
if (requestProtocols === null || !requestProtocols.includes(secProtocol)) {
208-
failWebsocketConnection(handler, 1002, 'Protocol was not set in the opening handshake.')
208+
failHandshake(handler, response, 1002, 'Protocol was not set in the opening handshake.')
209209
return
210210
}
211211
}
@@ -307,6 +307,16 @@ function closeWebSocketConnection (object, code, reason, validate = false) {
307307
}
308308
}
309309

310+
function failHandshake (handler, response, code, reason, cause) {
311+
// The H2 upgrade request has already completed and handed off its stream.
312+
// Aborting the request cannot close that stream after handshake validation fails.
313+
if (response.socket?.session != null && !response.socket.destroyed) {
314+
response.socket.destroy()
315+
}
316+
317+
failWebsocketConnection(handler, code, reason, cause)
318+
}
319+
310320
/**
311321
* @param {import('./websocket').Handler} handler
312322
* @param {number} code
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'use strict'
2+
3+
const assert = require('node:assert/strict')
4+
const { createSecureServer } = require('node:http2')
5+
const { once } = require('node:events')
6+
const { key, cert } = require('@metcoder95/https-pem')
7+
const { Agent, WebSocket } = require('../..')
8+
9+
async function main () {
10+
let session
11+
let receivedConnect = false
12+
const server = createSecureServer({ key, cert, settings: { enableConnectProtocol: true } })
13+
server.on('session', (s) => { session = s })
14+
server.on('stream', (stream) => {
15+
receivedConnect = true
16+
stream.on('error', () => {})
17+
// The status is accepted for H2, but the protocol is missing or unexpected.
18+
// Keep the stream open until after WebSocket has reported the failure.
19+
stream.respond(process.argv[2] === 'wrong-protocol'
20+
? { ':status': 200, 'sec-websocket-protocol': 'echo' }
21+
: { ':status': 200 })
22+
})
23+
24+
server.listen(0)
25+
await once(server, 'listening')
26+
27+
const dispatcher = new Agent({ allowH2: true, connect: { rejectUnauthorized: false } })
28+
const ws = new WebSocket(`wss://localhost:${server.address().port}`, { dispatcher, protocols: ['chat'] })
29+
ws.addEventListener('error', () => {})
30+
ws.addEventListener('open', () => { throw new Error('unexpected WebSocket open') })
31+
const [event] = await once(ws, 'close')
32+
assert.strictEqual(receivedConnect, true)
33+
assert.strictEqual(event.code, 1006)
34+
35+
// Closing the session must not surface an unhandled error on an orphaned stream.
36+
session.destroy()
37+
await new Promise((resolve) => server.close(resolve))
38+
await dispatcher.close()
39+
}
40+
41+
main().catch((err) => {
42+
console.error(err)
43+
process.exitCode = 1
44+
})
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'use strict'
2+
3+
const { test } = require('node:test')
4+
const { spawnSync } = require('node:child_process')
5+
const { join } = require('node:path')
6+
7+
// An unhandled ClientHttp2Stream 'error' exits the process, so test in a child.
8+
for (const response of ['missing-protocol', 'wrong-protocol']) {
9+
test(`a rejected H2 WebSocket handshake (${response}) does not crash when the session closes`, () => {
10+
const result = spawnSync(process.execPath, [join(__dirname, '../fixtures/websocket-h2-rejected-handshake.js'), response], {
11+
encoding: 'utf8',
12+
timeout: 10000
13+
})
14+
15+
if (result.error) throw result.error
16+
const { status, signal, stderr } = result
17+
if (signal !== null || status !== 0) {
18+
throw new Error(`child exited with status ${status}, signal ${signal}: ${stderr}`)
19+
}
20+
})
21+
}

0 commit comments

Comments
 (0)