bun icon indicating copy to clipboard operation
bun copied to clipboard

mssql.connect generates error "socket must be an instance of net.Socket" / `node:tls` does not accept a custom stream for it's `.socket` param

Open dmcquay opened this issue 2 years ago • 26 comments

What version of Bun is running?

1.0.1+31aec4ebe325982fc0ef27498984b0ad9969162b

What platform is your computer?

Darwin 21.6.0 x86_64 i386

What steps can reproduce the bug?

bun init -y
bun add mssql

Create a file named index.js with the following contents:

import * as sql from 'mssql'

const main = async () => {
	await sql.connect({
		user: 'bogus',
		password: 'bogus',
		database: 'bogus',
		server: 'example.database.windows.net'
	})
}

main()

You can literally use that example server to reproduce. No need to set up your own SQL Server.

What is the expected behavior?

Connection error because the user/password is wrong:

ConnectionError: Cannot open server 'example' requested by the login. Client with IP address '136.38.114.139' is not allowed to access the server...

I am checking this by running the same file with node 20.5.0.

Of course in my real code, I can also connect to my server successfully, but I don't want to share my DB host publicly, so this was a more minimal reproduction I could share.

What do you see instead?

ConnectionError: Failed to connect to example.database.windows.net:1433 - socket must be an instance of net.Socket code: "ESOCKET"

Additional information

I think the error is thrown here: https://github.com/oven-sh/bun/blob/4c113d1866ef6463a5972d90a2b6bddceb56ef73/src/js/node/net.js#L437

But I haven't been able to figure out what line in mssql lib is triggering this.

dmcquay avatar Sep 12 '23 20:09 dmcquay

Also reproduced on bun 1.0.2 with correct user name and password, thus making it impossible to use bun with mssql.

petterbergman avatar Sep 17 '23 03:09 petterbergman

same issue :((

aliiadev avatar Sep 17 '23 07:09 aliiadev

Same issue here connecting to Azure SQL Server with sequelize.

jeremyd4500 avatar Sep 17 '23 17:09 jeremyd4500

Same issue here connecting to Azure SQL Server with sequelize !!!

andresverjan avatar Sep 19 '23 01:09 andresverjan

Same error. Can connect to the Azure service just fine from the same local machine with Visual Code + the SQL server plugin. Firewall rules allow access. Bun + Knex fails to connect with the same config/env vars and throws a ESOCKET error with message socket must be an instance of net.Socket.

ianzepp avatar Sep 29 '23 22:09 ianzepp

I had the same problem, it was not possible to connect to the SQL SERVER.

After updating to Bun 1.0.6, it apparently worked!

I'll do some more testing but it's possible that the team has already fixed the lack of net.Socket implementation.

Steps:

bun init . # confirm, confirm ...
bun add mssql
bun add knex

./index.ts

import knex from "knex";

const db = knex({
    client: "mssql",
    connection: {
        host: Bun.env["DB_DEV_HOST"],
        port: parseInt(Bun.env["DB_DEV_PORT"] || "1433"),
        user: Bun.env["DB_USER"],
        password: Bun.env["DB_PASS"],
        database: Bun.env["DB_DATABASE"],
    },
});

console.log(await db.table("example_table").first());

./package.json

{
    "name": "bot-bun",
    "module": "index.ts",
    "type": "module",
    "devDependencies": {
        "bun-types": "latest"
    },
    "peerDependencies": {
        "typescript": "^5.0.0"
    },
    "dependencies": {
        "knex": "^3.0.1",
        "mssql": "^10.0.1"
    }
}

Result: print-20231014

cgslivre avatar Oct 14 '23 11:10 cgslivre

It is still an issue with bun 1.0.11 Anyone found a fix?

mscoobby avatar Nov 10 '23 05:11 mscoobby

It is still an issue with bun 1.0.11 Anyone found a fix?

I tested it on 1.0.6 and it was OK.

I updated yesterday to 1.0.11, ran the test again, and it still seems OK!

image

cgslivre avatar Nov 10 '23 09:11 cgslivre

That is very strange, I am using sequelize and I am still getting the error.

package.json

{
  "name": "bun-sequelize",
  "module": "index.ts",
  "type": "module",
  "devDependencies": {
    "bun-types": "latest"
  },
  "peerDependencies": {
    "typescript": "^5.0.0"
  },
  "dependencies": {
    "sequelize": "^6.35.0",
    "tedious": "^16.6.0"
  }
}

index.ts

import { Sequelize } from 'sequelize'

const sequelize = new Sequelize('', '--', '--', {
    port: 1450,
    dialect: 'mssql',
})

try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');
} catch (error) {
    throw new Error(`Unable to connect to the database: ${error}`)
}

Result: image

The database is running in Docker and its 1433 port is exposed on 1450 image

And the exact same file but executed with node: image

mscoobby avatar Nov 15 '23 06:11 mscoobby

Same error in macOS sonoma. Everything works properly in node

Angelelz avatar Dec 03 '23 05:12 Angelelz

I am on Bun v1.0.20, and I am also getting this error when trying to connect to a MS SQL Server database using mssql. I also tried to connect with sequelize and same thing.

This seems to me to be a pretty big deal. Having no ability to connect to databases from a runtime that's suppose to run on servers, one of the most common things you would ever do on a server.

Is there possibly some other configuration needed to get this working?

EthanTuning avatar Dec 27 '23 17:12 EthanTuning

Can we get an update on this, how can bun be viable without even basic sql driver support?

ReeceXW avatar Jan 09 '24 16:01 ReeceXW

It looks like the issue is that our version of tls.connect assumes that the socket must be a Socket, where indeed it is possible for it to be a Duplex.

socket <stream.Duplex> Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of net.Socket, but any Duplex stream is allowed.

Electroid avatar Jan 09 '24 18:01 Electroid

dependency-free reproduction

import { connect } from 'node:tls';
import { Duplex } from 'node:stream';

let socket;
class DuplexSocket extends Duplex {
  constructor(options) {
    super(options);
  }
  _read() {
		console.log('pass');
		socket.destroy();
  }
  _write(chunk, encoding, callback) {
  }
  _final(callback) {
  }
}

socket = connect({
  host: "127.0.0.1",
  port: 1433,
  localAddress: undefined,
  family: 4,
	socket: new DuplexSocket()
});
const onError = err => {
	console.log('e', err);
};
const onConnect = () => {};
socket.on('error', onError);
socket.on('connect', onConnect);

paperclover avatar Jan 12 '24 07:01 paperclover

image DuplexSocket is not - a socket - bun's socket

this is defined in the node.js documentation and we should implement it. image

paperclover avatar Jan 12 '24 07:01 paperclover

We need to connect to a sqlserver database using node-mssql, it would be really good to be able to use bun at work. Please keep up the good work

Angelelz avatar Feb 03 '24 23:02 Angelelz

I recently came across this exact scenario and tried a number of things. Initially I tried just using mssql directly (without sequelize or knex), and got the same errors.

I suspected it might be a bun version thing, or a mssql version thing and tried multiple variations without success.

Then, upgrading to latest packages AND wrapping with knex solved for me:

  • bun: 1.0.26
  • mssql: 10.0.2
  • knex: 3.1.0

mvandervliet avatar Feb 06 '24 15:02 mvandervliet

Same issue on our side,

  • bun: 1.0.26
  • mssql: 10.0.2

We have an existing project we wanna migrate to bun. But this issue makes it completely impossible, reworking our full code base to use knex or maybe try prisma will take to long.

Developers needs to look into this issue... This really makes bun in my eyes useless. Databases are somewhat important.

JocularMarrow avatar Feb 21 '24 17:02 JocularMarrow

I am also getting blocked by this issue:

  • bun: 1.0.30
  • sequelize: 6.37.1
  • tedious: 17.0.0
  • knex: 3.1.0

Seconding @mvandervliet that Knex functions. We have an older project that we don't want to convert, so being able to use sequelize and tedious out of the box would be much nicer.

SamMorey avatar Mar 11 '24 22:03 SamMorey

Same issue here

bun: 1.0.35 typeorm: 0.3.20 mssql: 10.0.2

I need a fix for this issue to continue migrating to Bun.

yurisanp avatar Mar 25 '24 20:03 yurisanp

Still exists

Bun: 1.1.6 mssql: 10.0.2

anilcan-kara avatar Apr 29 '24 15:04 anilcan-kara

Still exists

Bun: 1.1.17 with tedious: 18.2.1 or mssql: 11.0.0

import sql from 'mssql';

try {
    await sql.connect('Server=.;Database=kysely_rnd;Trusted_Connection=True;Encrypt=true')
    const result = await sql.query`select * from kysely_rnd `
    console.dir(result)
} catch (err) {
    console.log(err)
}

Error:

bun .\src\mssql.ts

80 |         rejectOnce(err)
81 |         return
82 |       }
83 |       tedious.connect(err => {
84 |         if (err) {
85 |           err = new ConnectionError(err)
                     ^
ConnectionError: Failed to connect to localhost:1433 - socket must be an instance of net.Socket
 code: "ESOCKET"

      at with-db\node_modules\mssql\lib\tedious\connection-pool.js:85:17
      at onConnect (with-db\node_modules\tedious\lib\connection.js:1337:7)
      at native:1:1
      at emit (native:1:1)
      at socketError (with-db\node_modules\tedious\lib\connection.js:2133:7)
      at with-db\node_modules\tedious\lib\connection.js:2238:25
      at processTicksAndRejections (native:1:1)

pashaie avatar Jun 27 '24 15:06 pashaie

Is there any roadmap on when will this be prioritized?

The reality is that mssql is still widely used among corp clients and it really is pity that we cannot use bun (on win) to connect a mssql DB, given that bun is a such a great tool and makes life easier in so many other areas.

It would be great to at least get an information on if it's planned to be addressed any soon or it's treated a low prio thing. Thanks.

gjovanov avatar Jun 28 '24 11:06 gjovanov

same issue here, also interested in knowing if is there any roadmap taking this (very blocking) issue in consideration

simonechiarlo avatar Jul 01 '24 23:07 simonechiarlo

same here, this is a showstoper for us.
any updates on this?

arvanti avatar Jul 10 '24 07:07 arvanti

Unsecure workaround:

bun: 1.1.18 tedious: 18.2.4

I'm running SQL Server 2022 on localhost (on Linux) and I can do without TLS encryption. So I disabled ForceEncryption on the server:

/opt/mssql/bin/mssql-conf set network.forceencryption 0
systemctl restart mssql-server.service

Then you need to disable client encryption in the tedious connection config (encrypt: false):

import { config } from './config'
import { Request, TYPES, Connection } from 'tedious';
const mssqlconfig = {
	server: config.server, //localhost
	port: config.port,
	options: {
		encrypt: false,
		database: config.database,
	},
	authentication: {
		type: "default",
		options: {
			userName: config.user,
			password: config.pass,
		}
	}
};
var connection = new Connection(mssqlconfig);
...

That worked for me. Of course this is not recommended over remote connections.

itorica avatar Jul 18 '24 10:07 itorica

I have the same issue in Bun 1.1.20.

Still exists

Bun: 1.1.17 with tedious: 18.2.1 or mssql: 11.0.0

import sql from 'mssql';

try {
    await sql.connect('Server=.;Database=kysely_rnd;Trusted_Connection=True;Encrypt=true')
    const result = await sql.query`select * from kysely_rnd `
    console.dir(result)
} catch (err) {
    console.log(err)
}

Error:

bun .\src\mssql.ts

80 |         rejectOnce(err)
81 |         return
82 |       }
83 |       tedious.connect(err => {
84 |         if (err) {
85 |           err = new ConnectionError(err)
                     ^
ConnectionError: Failed to connect to localhost:1433 - socket must be an instance of net.Socket
 code: "ESOCKET"

      at with-db\node_modules\mssql\lib\tedious\connection-pool.js:85:17
      at onConnect (with-db\node_modules\tedious\lib\connection.js:1337:7)
      at native:1:1
      at emit (native:1:1)
      at socketError (with-db\node_modules\tedious\lib\connection.js:2133:7)
      at with-db\node_modules\tedious\lib\connection.js:2238:25
      at processTicksAndRejections (native:1:1)

is this PR going to fix it? https://github.com/oven-sh/bun/pull/12750 it seems quite far along and I would just wait for that fix before trying a workaround or nodejs

stgoerlitz avatar Jul 31 '24 11:07 stgoerlitz

Any updates on this error? I tested it again in version 1.1.21, and the issue still persists. It's a shame because it's a product with a lot of potential, but without resolving these kinds of errors, using Bun loses its purpose.

mpanichella avatar Aug 03 '24 17:08 mpanichella

maybe you can try for update database config options : { encrypt: false } , but i think is not secure for remote connections

synelokk avatar Aug 13 '24 10:08 synelokk

maybe you can try for update database config options : { encrypt: false } , but i think is not secure for remote connections

Not only it makes it less secure, but also it's completely unacceptable for azure, as it prevents you from editing the encryption settings on the db, enforcing encryption.

simonechiarlo avatar Aug 13 '24 10:08 simonechiarlo