Joe
Joe

Reputation: 13091

How can I securely store the IP address, username and password of a database using Node.js?

I have Node.js code to connect to a MySQL database:

var mysql = require('mysql')
var express = require('express')
var app = express()

var connection = mysql.createPool({
    connectionLimit: 50,
      host     : 'ip',
    user     : 'username',
      password : 'pass',
      database : 'mydb'
});


app.get('/', function(req, resp) {
    connection.getConnection(function(error, tempCont) {
        if(!!error) {
            tempCont.release();
            console.log('Error');
        } else {
            console.log('Connected!');

            tempCont.query("select * from table", function(error, rows, fields) {
                tempCont.release();
                if(!!error) {
                    console.log('Error in the query');
                } else {
                    resp.json(rows);
                }
            });
        }
    })
})

console.log("listening requests...")
app.listen(1337);

How do I secure an IP address, username and password used for connecting to a database so that is not visible in the code or configuration file?

Upvotes: 13

Views: 15799

Answers (2)

Anil Gupta
Anil Gupta

Reputation: 377

Install the dotenv module by: npm install --save dotenv

Create a .env file at the root folder and write down the code:

DB_CONLIMIT=50
DB_HOST=ip
DB_USER=username
DB_PASSWORD=pass
DB_DATABASE=mydb

In your JavaScript file:

var mysql = require('mysql');
var express = require('express');
var app = express();
const dotenv = require('dotenv').config();

var connection = mysql.createPool({

     connectionLimit : process.env.DB_CONLIMIT,
     host            : process.env.DB_HOST,
     user            : process.env.DB_USER ,
     password        : process.env.DB_PASSWORD ,
     database        : process.env.DB_DATABASE
});

Upvotes: 28

jakedipity
jakedipity

Reputation: 900

You should be configuring your systems so that your service runs as its own user with its own protected files. This offers some protection so that even if another service is compromised, the intruding user's access is isolated from other components of your system. Don't run things as root.

As for how secrets are stored and accessed, that's up to you. You can have a configuration file if you want. Another option is to use environment variables. Ultimately; however, your secrets are going to have to be stored in plaintext somewhere for your system to read and use.

Another method worth mentioning is you could possibly separate your secrets from your applications by having a dedicated secrets service. All your applications would have to know about this service and from there they could request the secrets they need for their regular operation. This has the obvious caveat of all your applications depend on the secrets service on start up - if that goes down your applications won't be able to start or restart.

Upvotes: 3

Related Questions