Guest User

Untitled

a guest
Nov 9th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. process.env.DEBUG = "node-vault"; // switch on debug mode
  2.  
  3. require("dotenv").config();
  4. const mysql = require("promise-mysql");
  5. const Vault = require("node-vault");
  6.  
  7. const { VAULT_TOKEN } = process.env;
  8. const vault = Vault({ token: VAULT_TOKEN });
  9.  
  10. let credential;
  11.  
  12. async function issueCredential() {
  13. credential = await vault.read("database/creds/my-role");
  14. const { username, password } = credential.data;
  15. const leaseDuration = credential.lease_duration;
  16. lease_id = credential.lease_id;
  17.  
  18. const info = [
  19. `Got new credential!`,
  20. ` username: ${username}`,
  21. ` password: ${password}`,
  22. ` lease duration: ${leaseDuration}`
  23. ];
  24. console.log(info.join("\n"));
  25.  
  26. global.setTimeout(() => {
  27. console.log(`Credential will expire in ${leaseDuration / 2} seconds, rotate it.`);
  28. issueCredential();
  29. }, (leaseDuration * 1000) / 2);
  30. }
  31.  
  32. async function gracefulShutdown() {
  33. console.info("SIGTERM signal received.");
  34. await vault.revoke({ lease_id: credential.lease_id });
  35. process.exit(0);
  36. }
  37.  
  38. async function loop() {
  39. try {
  40. const { username, password } = credential.data;
  41. const conn = await mysql.createConnection({
  42. host: "localhost",
  43. user: username,
  44. password: password
  45. });
  46. const result = await conn.query("SELECT USER()");
  47. console.log(`Current user: ${result[0]["USER()"].split("@")[0]}`);
  48. conn.end();
  49. } catch (e) {
  50. console.error(e.sqlMessage);
  51. issueCredential();
  52. }
  53. }
  54.  
  55. function main() {
  56. issueCredential();
  57. global.setInterval(loop, 1000);
  58. process.on("SIGTERM", gracefulShutdown);
  59. }
  60.  
  61. if (require.main === module) {
  62. main();
  63. }
Add Comment
Please, Sign In to add comment