I have a NODEJS code to connect to 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 a ip, username and password used for connecting to a database so that is not visible in the code or configuration file?
Install env module by : npm install --save dotenv
Create .env file at root folder and write down the code
DB_CONLIMIT=50
DB_HOST=ip
DB_USER=username
DB_PASSWORD=pass
DB_DATABASE=mydb
In your js 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
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With