Skip to content

Commit b1a8947

Browse files
Fail gracefully when connecting to other database (#3026)
* Fail gracefully when connecting to other SGDB vendor * Make test more flexible. Adjust error wording to match native better. --------- Co-authored-by: Brian Carlson <[email protected]>
1 parent d21cc09 commit b1a8947

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed

Diff for: packages/pg-protocol/src/parser.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ export class Parser {
199199
case MessageCodes.CopyData:
200200
return this.parseCopyData(offset, length, bytes)
201201
default:
202-
assert.fail(`unknown message code: ${code.toString(16)}`)
202+
return new DatabaseError('received invalid response: ' + code.toString(16), length, 'error')
203203
}
204204
}
205205

Diff for: packages/pg/test/integration/gh-issues/2627-tests.js

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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

Comments
 (0)