Using ssl with node mysql and Cleardb - javascript

I have a free ClearDB account that I got through Heroku (as a resource)
It gives me the
CA certificate
Client cert
Client Key
These are all in .pem format
const fs = require('fs');
const ssl = {
ca: fs.readFileSync('cleardb-ca.pem', "utf-8"),
key: fs.readFileSync('cleardb-key.pem', "utf-8"),
cert: fs.readFileSync('cleardb-cert.pem', "utf-8")
};
const cleardb = mysql.createConnection({
host:"HOST",
user: "USER",
password: "PWD",
database: "DB",
ssl: ssl
});
cleardb.connect((err) => {
if (err) throw err;
console.log('connected!');
});
This keeps throwing
Error: 22928:error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1929:
and then the error stacktrace shows an Object like
library: 'SSL routines', function: 'ssl_choose_client_version', reason: 'unsupported protocol', code: 'HANDSHAKE_SSL_ERROR', fatal: true
The SSL routines:ssl_choose_client_version:unsupported error is the same exact error I get when I try connecting to this DB through the MySQL CLI.
I.e. mysql --host=HOST --ssl-capath=. --ssl-cert=cleardb-cert.pem --ssl-key=cleardb-key.pem --user=USER
I'm able to connect through both Node and the CLI if I do not use SSL.
Any idea what's going on here?
Should I really worry that much about using SSL? I've read that if the option for transport security exists, that you should elect to use it.

Related

GRPC client Error: 14 UNAVAILABLE: failed to connect to all addresses

Im trying to test my grpc client connection using below code.
I have .net core grpc server and using node js grpc client to connect. But getting "failed to connect to all addresses" error. BUt able to connect .net grpc server to .net grpc client. Any help much appreciated.
Not sure if im missing anything from below grpc client code.
'use strict';
//Same as the other projects we import fs for reading documents, in this case employees.js json
const fs = require('fs');
//Importing GRPC and the proto loader
const grpc = require('grpc');
const loader = require('#grpc/proto-loader');
//reads the proto
const packageDefinition = loader.loadSync('Repository.proto', {
keepCase: false,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
//Loads the proto file to be used in constant pkg
const pkg = grpc.loadPackageDefinition(packageDefinition);
//Creates server
const PORT = 5001;
//console.log(pkg);
const client = new pkg.repository.Repository('localhost:5001', grpc.credentials.createInsecure());
client.GetUpdates({}, function (err, response) {
console.log("----Response error----");
if (err) {
console.log(err);
} else {
console.log(response);
}
});
im getting below error:
{ Error: 14 UNAVAILABLE: failed to connect to all addresses
at Object.exports.createStatusError (/mnt/c/Users/ht9638/Desktop/workspace/current-workspace/gRPCNodeJS/firstService/node_modules/grpc/src/common.js:91:15)
at Object.onReceiveStatus (/mnt/c/Users/ht9638/Desktop/workspace/current-workspace/gRPCNodeJS/firstService/node_modules/grpc/src/client_interceptors.js:1209:28)
at InterceptingListener._callNext (/mnt/c/Users/ht9638/Desktop/workspace/current-workspace/gRPCNodeJS/firstService/node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.onReceiveStatus (/mnt/c/Users/ht9638/Desktop/workspace/current-workspace/gRPCNodeJS/firstService/node_modules/grpc/src/client_interceptors.js:618:8)
at callback (/mnt/c/Users/ht9638/Desktop/workspace/current-workspace/gRPCNodeJS/firstService/node_modules/grpc/src/client_interceptors.js:847:24)
code: 14,
metadata: Metadata { _internal_repr: {}, flags: 0 },
details: 'failed to connect to all addresses' }
Can someone please help me on this issue.
I have the same issue when I tried to follow gRPC nodejs tutorials from the official documentation
Root cause(for me): port 50051 are the default port used from the main documentation, when i check the list of the port being used on my laptop, turn out that port 50051 used by "NVIDIA Web Helper.exe".
How i find this out: I tried to change the port slightly to 50052 and console.log the err and it shows as expected

unable to connect to database from node script and there is no error thrown

I have been working with nodejs google cloud functions for a while. I have been facing a weird issue where I can't connect to database servers and there is no error logged not even timeout. I am using node v14.2.0 with pg as postgres library. My nodejs code is
const { Client } = require('pg');
let connectionSetting = {
host: "host",
user: "user",
database: "db_name",
password: "password",
};
const client = new Client(connectionSetting);
console.log(connectionSetting);
client.connect(err => {
if (err) {
console.error(`Error connecting to db -> ${err}`);
}
console.log("Connection established with PgSql DB ");
});
There are no console logs or whatever.
This same code is working on other systems. The database is remote database hosted on gcp and I'm able to connect to it using tablePlus as GUI client.
Any help appreciated.
I found the issue. It has to do with the node version. I was using node current 14.2.0 so I installed node lts 12 and then everything works fine.
Thanks for all help

Error: read ECONNRESET when connected to a mysql server with Node.js

I'm trying to establish a simple connection to my database with the mysql npm package. At first glance, everything works fine and I can get the information I need, however, if I leave the server running for some time I get the following error:
Error: read ECONNRESET
at TCP.onStreamRead
const express = require('express');
const app = express();`
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'XXXX.mysql.database.azure.com',
user: 'XXXXX',
password: 'XXXXX',
database: 'XXXXX'
})
db.connect((err)=>{
if(err){
console.log(err.message);
} else {
console.log('Connected to the database');
}
})
As far as I understand the problem stems from the database connection being in idle mode. Do I need to configure the Azure server or is there something else I need to do?
Couple of things to try:
You can try creating connection pool instead of **createConnection**
mysql.createPool({});
Modify your package.json like below:
"dependencies": {
"mysql": "git://github.com/mysqljs/mysql#e3e123e9af7c0829a6c1417d911572a75b4a5f95"
},
It is described in detail here:
Bad handshake or ECONNRESET Azure Mysql Nodejs
https://social.msdn.microsoft.com/Forums/en-US/c8fedbcc-909d-41ce-8c72-0374f76fdf82/cannot-connect-from-nodejs?forum=AzureDatabaseforMySQL
Hope it helps.

Why is Sequelize not authenticating against my MS Sql Database?

When attempting to connect to my local SQL Server instance I am receiving an error stating Authentication failed for login. However I am able to login directly to the server in SQL using the provided login.
Here is my code that is attempting to connect to the server.
var Sequelize = require('sequelize');
const sequelize = new Sequelize('GraphQLTests', 'gql', 'Password1', {
dialect: 'mssql',
host:'localhost'
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
I have printed to the console in the Sequelize code to verify that the correct credentials are getting passed but still receive this error.
name: 'SequelizeAccessDeniedError',
parent:
{ ConnectionError: Login failed for user ''.}
Please let me know if there is any other info I can provide.
try this
const sequelize = new Sequelize('DB Name', 'Username', 'Password', {
host: 'Host',
dialect: 'mssql',
dialectOptions: {
options: {
encrypt: true,
}
}
});
sequelize.authenticate().then((err) => {
console.log('Connection successful', err);
})
.catch((err) => {
console.log('Unable to connect to database', err);
});
Try this link as reference Connecting to MSSQL server with Sequelize
This is what worked for me, where I have put the server details in an YAML file. (this way, you can switch servers on the fly).
this is the sequelize code
//get the configure from the YAML file
const YAML = await fs.readFile(process.env.SEQUELIZE_CONNECT,'utf8');
//load the database parameters into our system
const params = jsyaml.safeLoad(YAML, 'utf8');
//initiate our database server details to connect to our underlying database system
//as described in the YAML file.
sequlz = new Sequelize(params.dbname, params.username, params.password, params.params);
Here is how my YAML file looks. (I have left my code comments as it is)
#this should work to whatever you are using anywhere.
#as per the YAML file title, I am using a MS SQL server hosted on Azure.
# you can edit values. as per your requirement.
# check the dialect help file of your server on the sequelize documentation
# https://sequelize.org/v5/file/lib/dialects/mssql/connection-manager.js.html
#change the values as per your server.
dbname: databasenamehere
username: usernamehere
password: passwordhere
params:
host: servernamehere.database.windows.net
dialect: mssql
dialectOptions:
{
options: {
encrypt: true,
requestTimeout: 10000
}
}
So, that worked for me. (I have remixed answers from above post, and also from the textbook and multiple online resources I was referring).
Note : The server is running on Azure with the Firewall IP address set to ALL IP address.

SequelizeConnectionError in Node.js application

I have strange problem and don't know in what place is the problem. I will be grateful for any help.
I have Node.js application which works fine in local windows 10 computer. I run this application successfully in Docker which is in CentOS server. This application works with remote MySQL and PostgreSQL databases. It worked correctly several days but yestoday I notice that I have error. Application can't connect to remote MySQL database anymore. In the same time I can connect to that remote MySQL database without any problem if I run application in my local computer or connect by DBeaver/dbForge tool.
MySQL.js:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'host',
dialect: 'mysql'
});
sequelize.authenticate().then(() => {
console.log('Connection to database has been established successfully.');
}).catch(err => {
console.error('Unable to connect to database:', err);
});
module.exports = sequelize;
routes.js:
const express = require('express');
const router = express.Router();
const sequelize = require('../configurations/MySQL');
const Sequelize = require('sequelize');
const passport = require('passport');
require('../configurations/password')(passport);
router.post('/search_by_name', passport.authenticate('jwt', {session: false}, null), function(req, res) {
const token = getToken(req.headers);
if (token) {
sequelize.query("LONG SQL QUERY", {
replacements: {
name: req.body.name,
},
type: Sequelize.QueryTypes.SELECT
}).then((locations) => {
res.status(200).send(locations)
}).catch((error) => {
res.status(400).send(error);
});
} else {
return res.status(401).send({
status: false,
description: "Unauthorized"
});
}
});
As you can see I use sequelize library to connect application to remote MySQL database. The same library I use to connect to remote PostgreSQL database. As I said before error happens only when I try to connect to remote MySQL database in Docker. There is no error with PostgreSQL connection in Docker. Is it possible that problem inside Docker/network?
Dependencies:
"sequelize": "^4.42.0"
"mysql2": "^1.6.4"
I also thought that the reason of the problem can be because of much pools/connections and sequelize library don't close them automatically. For thats why I restarted docker сontainer several times hoping to confirm the theory. Unfortunately the error do not disappear.
How do you think, what happens?
Error:
Unable to connect to the database: { SequelizeConnectionError: connect ETIMEDOUT
at Utils.Promise.tap.then.catch.err (/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:149:19)
at tryCatcher (/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/node_modules/bluebird/js/release/promise.js:690:18)
at _drainQueueStep (/node_modules/bluebird/js/release/async.js:138:12)
at _drainQueue (/node_modules/bluebird/js/release/async.js:131:9)
at Async._drainQueues (/node_modules/bluebird/js/release/async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (/node_modules/bluebird/js/release/async.js:17:14)
at processImmediate (timers.js:632:19)
name: 'SequelizeConnectionError',
parent:
{ Error: connect ETIMEDOUT
at Connection._handleTimeoutError (/node_modules/mysql2/lib/connection.js:173:17)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true },
original:
{ Error: connect ETIMEDOUT
at Connection._handleTimeoutError (/node_modules/mysql2/lib/connection.js:173:17)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true }}
Try to add pool option when new Sequelize. Reference document
Sequelize will setup a connection pool on initialization so you should
ideally only ever create one instance per database if you're
connecting to the DB from a single process. If you're connecting to
the DB from multiple processes, you'll have to create one instance per
process, but each instance should have a maximum connection pool size
of "max connection pool size divided by number of instances". So, if
you wanted a max connection pool size of 90 and you had 3 worker
processes, each process's instance should have a max connection pool
size of 30.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'host',
dialect: 'mysql',
pool: {
max: 15,
min: 5,
idle: 20000,
evict: 15000,
acquire: 30000
},
});
module.exports = sequelize;
Also, you can check more option at here
options.pool sequelize connection pool configuration
options.pool.max default: 5 Maximum number of connection in pool
options.pool.min default: 0 Minimum number of connection in pool
options.pool.idle default: 10000 The maximum time, in milliseconds,
that a connection can be idle before being released. Use with
combination of evict for proper working, for more details read
https://github.com/coopernurse/node-pool/issues/178#issuecomment-327110870
options.pool.acquire default: 10000 The maximum time, in milliseconds,
that pool will try to get connection before throwing error
options.pool.evict default: 10000 The time interval, in milliseconds,
for evicting stale connections. Set it to 0 to disable this feature.
options.pool.handleDisconnects default: true Controls if pool should
handle connection disconnect automatically without throwing errors
options.pool.validate A function that validates a connection. Called
with client. The default function checks that client is an object, and
that its state is not disconnected
In the simple terms i want to say that these type of error comes when your some configuration wrong entered. these are :
DB Name
Username
Password
so please cross verify your these things in your congif.json file
I would recommend to check the Database Hostname. Please try to resolve the hostname, if it is given IP address instead of domain. This would resolve the issue.

Categories