|
| 1 | +'use strict' |
| 2 | +const net = require('net') |
| 3 | +const helper = require('./../test-helper') |
| 4 | + |
| 5 | +const suite = new helper.Suite() |
| 6 | + |
| 7 | +const options = { |
| 8 | + host: 'localhost', |
| 9 | + port: Math.floor(Math.random() * 2000) + 2000, |
| 10 | + connectionTimeoutMillis: 2000, |
| 11 | + user: 'not', |
| 12 | + database: 'existing', |
| 13 | +} |
| 14 | + |
| 15 | +// This is the content of the packets sent by a MySQL server during the handshake. |
| 16 | +// Those were captured with the `mysql:8.0.33` docker image. |
| 17 | +const MySqlHandshake = Buffer.from( |
| 18 | + 'SgAAAAo4LjAuMjgAHwAAAB4dKyUJZ2p6AP///wIA/98VAAAAAAAAAAAA' + |
| 19 | + 'AAo1YiNJajgKKGkpfgBjYWNoaW5nX3NoYTJfcGFzc3dvcmQAIQAAAf+EBC' + |
| 20 | + 'MwOFMwMUdvdCBwYWNrZXRzIG91dCBvZiBvcmRlcg==', |
| 21 | + 'base64' |
| 22 | +) |
| 23 | + |
| 24 | +const serverWithInvalidResponse = (port, callback) => { |
| 25 | + const sockets = new Set() |
| 26 | + |
| 27 | + const server = net.createServer((socket) => { |
| 28 | + socket.write(MySqlHandshake) |
| 29 | + |
| 30 | + // This server sends an invalid response which should throw in pg-protocol |
| 31 | + sockets.add(socket) |
| 32 | + }) |
| 33 | + |
| 34 | + let closing = false |
| 35 | + const closeServer = (done) => { |
| 36 | + if (closing) return |
| 37 | + closing = true |
| 38 | + |
| 39 | + server.close(done) |
| 40 | + for (const socket of sockets) { |
| 41 | + socket.destroy() |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + server.listen(port, options.host, () => callback(closeServer)) |
| 46 | +} |
| 47 | + |
| 48 | +suite.test('client should fail to connect', (done) => { |
| 49 | + serverWithInvalidResponse(options.port, (closeServer) => { |
| 50 | + const client = new helper.Client(options) |
| 51 | + |
| 52 | + client |
| 53 | + .connect() |
| 54 | + .then(() => { |
| 55 | + done(new Error('Expected client.connect() to fail')) |
| 56 | + }) |
| 57 | + .catch((err) => { |
| 58 | + assert(err) |
| 59 | + assert(err.message.includes('invalid response')) |
| 60 | + closeServer(done) |
| 61 | + }) |
| 62 | + }) |
| 63 | +}) |
0 commit comments