How to connect to Cloud SQL instance using nodejs and pem keyfile

2k views Asked by At

I'm trying to connect to Cloud SQL instance from nodejs application using pem file key.

var fs = require('fs');
var Sequelize = require('sequelize');

var sequelize = new Sequelize('database', 'root', '', {
    host: '<ip>',
    dialect: 'mysql',
    ssl: {
       ca: fs.readFileSync(__dirname + '/server-ca.pem'),
       key: fs.readFileSync(__dirname + '/cert.pem')
    }
});
sequelize.query('select * from Users').then(function (users) {
    console.log(users);
});

I got Possibly unhandled SequelizeAccessDeniedError: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'<ip>' (using password: NO).

What am I doing wrong?

2

There are 2 answers

0
Nick On

I just looked up a quick google search of mysql access denied using password no, and the MySQL docs themselves say that this error message comes when you tried to log in without using a password. (CTRL + F for "you tried to log in without a password"). This is likely to be the source of the issue.

Otherwise, have you followed the instructions from the Cloud SQL docs on how to connect from an external application? Specifically, you'll want to ensure that your box's IP or IP range is allowed by your instance. Be aware that if you're behind a firewall that does NAT, a corporate proxy, an open proxy, or any other private proxy you/your ISP owns, you'll need to ensure that the IP of that network node is allowed, as your IP packets will appear to originate from there. You can test this by running dig +short myip.opendns.com @resolver1.opendns.com, which will use an external service to tell you what your IP appears to be.

You may also want to double-check the docs on TLS and Cloud SQL to ensure everything you've done is good in that regard.

0
David On

It looks like your ssl options are not correct. You have put a "cert" file in the key parameter. Your ssl config should look like:

  ssl: {
     ca: fs.readFileSync(__dirname + '/server-ca.pem'),
     cert: fs.readFileSync(__dirname + '/client-cert.pem'),
     key: fs.readFileSync(__dirname + '/client-key.pem')
  }

Where client-key.pem is the private key corresponding to client-cert.pem. You should get all three of these files when you follow the Cloud SQL SSL instructions.