简体   繁体   中英

How to access secrets in node.js with Hashicorp Vault

I have just set up Vault from Hashicorp on my Ubuntu 18.04 backend server. It runs a node.js backend server which used to use environment variables to store data for the MySQL database. However, I figured this was unsecure, hence why I changed to Vault. I have now stored all secrets inside the Vault and I can access it in my node.js application like this:

const rootKey = "hidden"
const unsealKey = "alsohidden"

var options = {
    apiVersion: 'v1',
    endpoint: 'https://url.com:8200',
    token: rootKey
};

var vault = require("node-vault")(options);
vault.unseal({ key: unsealKey })
    .then(() => {
        vault.read('secret/db_host')
          .then((res) => console.log("result:",res.data.value))
          .catch((err) => console.error("error:",err));
    });

This results in the correct host address printed in my console logs. However, this leaves me with two questions:

1. How can I use the retrieved information in my MySQL connection? I currently do this with the environment variables:

var pool = mysql.createPool({
    connectionLimit: 100,
    host: process.env.DB_HOST, // how can I call the vault variables here?
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_BASE,
    ssl      : {
          ca   : fs.readFileSync('hidden'),
          key  : fs.readFileSync('hidden'),
          cert : fs.readFileSync('hidden'),
    },
    dateStrings: true
});

2. If I store the rootKey and unsealKey as constants in my node.js application, what's the point of secrecy? I figure there should be a way to handle this properly, because there is not much different now as to just store the credentials in my .js file straight away..

You shouldn't use your root key to access secrets. Vault provides several authentication methods . For example - user-pass pairs, github authentication (using token), LDAP, k8s and more...

Using one of the authentication method you will get a vault token with a policy . This policy will allow you the access only your relevant secrets.

Another great place to read about Vault: Learn Vault

If you are using kubernetes you can read this guide and this one

edit: regarding the first question, it depends on how you decide to load the secrets - you can load them from file, from process.env or directly set them using node-vault package. I personally write them to file from a different process and load them to process.env with dotenv package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM