Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

hashi-vault-js

rod4n4m155.4kMIT0.4.16TypeScript support: included

A node.js module to interact with the Hashicorp Vault API.

kyndryl, hashicorp, nodejs, promises, api, async, vault

readme

Hashi Vault JS

GitHub issues GitHub code size in bytes GitHub repo file count GitHub top language GitHub contributors GitHub package.json dependency version (prod) npm NPM

This module provides a set of functions to help JavaScript Developers working with HashiCorp Vault to authenticate and access API endpoints using JavaScript promises.

This package is NOT affected by the log4shell CVE-2021-44228 vulnerability!

Requirements (MacOS/Windows)

  • NodeJs
    • Minimum: v18.x
    • Recommended: v20.x
  • npm
    • Tested on: v10.8.x
  • HashiCorp Vault
    • Minimum: v1.15.x
    • Accepted: v1.16.x
    • Recommended: v1.17.x

Note: Depending on your Windows setup windows-build-tools may need to be installed first. Also, for MacOS users, you should have xcode-select or entire Xcode App installed.

Table of Contents

Install

npm install hashi-vault-js --save

Uninstall

npm uninstall hashi-vault-js

Release notes and versions

Change log

Class Constructor

{
  // Indicates if the HTTP request to the Vault server should use
  // HTTPS (secure) or HTTP (non-secure) protocol
  https: true,
  // If https is true, then provide client certificate, client key and
  // the root CA cert
  // Client cert and key are optional now
  cert: './client.crt',
  key: './client.key',
  cacert: './ca.crt',
  // Indicate the server name/IP, port and API version for the Vault,
  // all paths are relative to this one
  baseUrl: 'https://127.0.0.1:8200/v1',
  // Sets the root path after the base URL, it translates to a
  // partition inside the Vault where the secret engine / auth method was enabled
  // Can be passed individually on each function through mount parameter
  rootPath: 'secret',
  // HTTP request timeout in milliseconds
  timeout: 1000,
  // If should use a proxy or not by the HTTP request
  // Example:
  // proxy: { host: proxy.ip, port: proxy.port }
  proxy: false,
  // Namespace (multi-tenancy) feature available on all Vault Enterprise versions
  namespace: 'admin'
}

Module usage

Note: This package covers some auth methods and secret engines. Check Limitations section for more details.

  • Production
const Vault = require('hashi-vault-js');

const vault = new Vault( {
    https: true,
    cert: './client.crt',
    key: './client.key',
    cacert: './ca.crt',
    baseUrl: 'https://127.0.0.1:8200/v1',
    rootPath: 'secret',
    timeout: 2000,
    proxy: false,
    // Only for Vault Enterprise
    namespace: 'ns1'
});
  • Development
const Vault = require('hashi-vault-js');

const vault = new Vault( {
    https: true,
    baseUrl: 'https://127.0.0.1:8200/v1',
    rootPath: 'secret',
    timeout: 5000,
    proxy: false
});

Check health status of the Vault server:

const status = await vault.healthCheck();

Perform a login on the Vault with role-id/secret-id pair, (AppRole login) and get a valid client token:

const token = await vault.loginWithAppRole(RoleId, SecretId).client_token;

Perform a login on the Vault with LDAP username/password pair, and get a valid client token:

const token = await vault.loginWithLdap(Username, Password).client_token;

Perform a login on the Vault with Userpass username/password pair, and get a valid client token:

const token = await vault.loginWithUserpass(Username, Password).client_token;

Perform a login on the Vault with Kubernetes service accounts token, and get a valid client token:

const token = await vault.loginWithK8s(Role, Token).client_token;

Perform a login on the Vault with TLS certificate and key, and get a valid client token:

const token = await vault.loginWithCert(certName, Token).client_token;

Define a function to return secret engine information from the Vault:

const secretEngineInfo = function(token) {
  vault.readKVEngineConfig(token).then(function(result){
    return result;
  }).catch(function(error){
    return error;
  });
};

Create a new secret in the Vault:

const Item={
  name: "slack",
  data: {
    bot_token1: "xoxb-123456789012-1234567890123-1w1lln0tt3llmys3cr3tatm3",
    bot_token2: "xoxb-123456789013-1234567890124-1w1lln0tt3llmys3cr3tatm3"
  }
};

const data = await vault.createKVSecret(token, Item.name , Item.data);

Read a secret from the Vault:

const secrets = await vault.readKVSecret(token, Item.name);

Update secret version 1 in the Vault:

const data = await vault.updateKVSecret(token, Item.name , newData, 1);

TypeScript

hashi-vault-js includes TypeScript definitions in the Vault.d.ts.

let response: ReadKVSecretResponse = null;
try {
  const { data } = await vault.readKVSecret(token, Item.name);
  response = data;
}

Mount points

Most of the Vault Server API endpoints can be mounted on non-default path. For that reason, there's a last parameter in the related functions to allow using a custom mount path.

For instance, if you want to enable KV v2 on a different path, you can do so:

vault secrets enable -path=knight kv-v2

Now you call this helper library functions with the correct mount path:

const config = await vault.readKVEngineConfig(token, "knight")

Error handling

This package extends the error stack to differentiate if the exception occurred on the Vault API layer or not. Also, adds a help message from the Vault API docs.

try {
  vault.function(...);
}
// An exception happened and it was thrown
catch(err) {
  if(err.isVaultError) {
    // This an error from Vault API
    // Check Vault hint on this error
    console.log(err.vaultHelpMessage);
  }
  else {
    // Here is still the full Axios error, e.g. err.isAxiosError, err.response, err.request
    // This allows handling of network/tls related issues
    // Or just re-kthrow if you don't care
    throw err;
  }
}

Check below docs for more information on specific function groups.

Available functions

Group Type Default mount point Link
Active Directory (AD) - deprectated Secret engine /ad Doc file
AppRole Auth method /auth/approle Doc file
LDAP Auth method /auth/ldap Doc file
Kubernetes Auth method /auth/kubernetes Doc file
KV v2 Secret engine /kv Doc file
PKI Secret engine /pki Doc file
System Backend System General operations Doc file
System Backend System SEAL operations Doc file
TLS Certificate Auth method /auth/cert Doc file
Token Auth method /auth/token Doc file
TOTP Secret engine /totp Doc file
Userpass Auth method /auth/userpass Doc file
|

Coverage and limitations

The following HashiCorp Vault API endpoints are currently covered:

Method Coverage status
AppRole Partially
LDAP All endpoints
Userpass All endpoints
Kubernetes All endpoints
TLS Cert Partially
Token Most of them
  • Secret engines:
Engine Coverage status
Active Directory (AD) Most of them, currently in deprecation notice
KV Version 2 All endpoints
PKI Most of them
TOTP Few of them

Test environment

  • Follow the detailed instructions from this doc

References

  • HashiCorp Vault Using KV engine doc

  • HashiCorp Vault Docker Hub page

  • Ruan Bekker's Blog post

Contributing

If you want to contribute to the module and make it better, your help is very welcome. You can do so submitting a Pull Request. It will be reviewed and merged to main branch if accepted.

By contributing to this public repository, you fully agree with the following Developer's Certificate of Origin document.

Reporting an issue

If you have found what you believe to be an issue with hashi-vault-js please do not hesitate to file an issue on the GitHub repository here.

Suggesting a new feature

If you want to see new features or enhancements to the current ones, we would love to hear them. Please submit an issue on the GitHub repository here.

Authors

Written by Rod Anami rod.anami@kyndryl.com, June 2020.

Contributors

License

This project is licensed under the MIT license.

HashiCorp Vault is licensed under the Business Source License 1.1.

changelog

Hashi Vault JS

Change Log

  • 0.4.16 (latest)

    • Updated Axios dependency to 1.7.4 #51
    • Upgraded development env to Vault server 1.17.3
  • 0.4.15

    • Upgraded development env to Vault server 1.16.3
    • Improved AD secret management documentation
    • Upgraded all dependencies to the latest
    • Added TOTP secret engine functions:
      • createTOTPKey and readTOTPKey
  • 0.4.14

    • Updated HashiCorp Vault license
    • Upgraded all dependencies to the latest
    • Upgraded development env to Vault server 1.14.2
    • Refactored TypeScript types to generate .d.ts files using JSDoc syntax - issue [#40,#38]
    • Added KV secret engine - metadata functions - issue [#42]:
      • createKVSecretMeta, updateKVSecretMeta, and readKVSecretMeta
  • 0.4.13

    • Added SBOM generator script
    • Upgraded all dependencies to the latest
    • Refactored TypeScript types to get them linted and verified - issue #35
    • Fixed package.json to accept node engine v14 - issue #32
    • Fixed TypeScript types to match main code and allow contructor without certificates - issue #31
    • Upgraded development env to Vault server 1.13.0 and podman
  • 0.4.12

    • Turned CA certificate optional (contribution from @josedev-union)
    • Upgraded all dependencies (Axios, Jest, random-words, and @type/node)
    • Upgraded development env to Vault server 1.12.2
    • Changed licence from EPL-2.0 to MIT
    • Added workflow for releasing and publishing
    • Fixed bug on deleteLatestVerKVSecret
  • 0.4.11

    • Added support to TypeScript (contribution from @phr3nzy)
    • Improved AD secret engine config functions interfaces
    • Added AD secret engine - Role functions:
      • listADRoles, createADRole, updateADRole, readADRole, deleteADRole, getADRoleCred, and rotateADRoleCred
    • Added AD secret engine - Library functions:
      • listADLibraries, createADLibrary, updateADLibrary, readADLibrary, deleteADLibrary, checkADCredOut, checkADCredIn, and getADCredSatus
  • 0.4.10

    • Upgraded development env to Vault server 1.11.0
    • Upgraded all dependencies (Axios and Jest)
    • Improved KV secret engine assertions
    • Added AD secret engine functions:
      • setADConfig
      • readADConfig
      • updateADConfig
      • deleteADConfig
  • 0.4.9

    • Upgraded development env to Vault server 1.10.2
    • Added mockup LDAP server to expand LDAP auth method functions
    • Added LDAP auth method functions:
      • setLdapConfig
      • readLdapConfig
  • 0.4.8

    • Fixed security vulnerability (npm audit fix)
    • Improved documentation
    • Upgraded development env to Vault server 1.9.2 and node engine v16
    • Upgraded all dependencies (Axios and Jest)
  • 0.4.7

    • Upgraded development env to Vault server 1.8.5
    • Added TLS Certificate auth method function:
      • loginWithCert
  • 0.4.6

    • Added support for namespaces (multi-tenancy), a Vault Enterprise feature
    • Added KV v2 secret engine function:
      • eliminateKVSecret
    • Upgraded development env to Vault server 1.8.0
    • Change constructor to allow instantiation without client certificates
  • 0.4.5

    • Added Kubernetes (K8s) auth method functions
      • loginWithK8s, updateK8sConfig, readK8sConfig, createK8sRole, readK8sRole, listK8sRoles, and deleteK8sRole
      • Improved general documentation
  • 0.4.4

    • Duplicated
  • 0.4.3

    • Added KV v2 secret engine function:
      • updateKVEngineConfig
    • Upgraded development env to Vault server 1.7.2
    • Fixed security vulnerability (npm audit fix)
  • 0.4.2

    • Fixed security vulnerabilities (npm audit fix)
    • hosted-git-info and lodash vulnerabilities
  • 0.4.1

    • Added mount optional parameter to auth methods and secret engines that might be mounted on a custom path
      • LDAP auth method functions
      • Userpass auth method functions
      • AppRole auth method functions
    • Added error handling documentation to README
    • Updated dev environment to Vault 1.6.3
    • Split AppRole and KV test suite into 2 distinct isolated tests
    • Improved KV v2 secret engine unit test
  • 0.4.0

    • Refactored createToken function to accept an object as parameter (Issue#6)
    • Merged Pull Request Make createToken more friendly to use #8
    • Implemented a new Axios error parse to fix and improve stack trace (Issue#7)
  • 0.3.22

    • Updated development env to Vault server 1.6.1
    • Moved CHANGELOG to root directory
  • 0.3.21

    • Re-fixed bug on createToken function related to typeof never returning undefined (Issue#5)
  • 0.3.20

    • Updated package.json to force using `axios@0.21.1` (or higher) due to CVE-2020-28168
  • 0.3.19

    • Fixed bug on createToken function related to using logical OR operator with attribution on boolean params, this causes the params to be always true (Issue#5)
    • Also, removed unnecessary null conditional attribution to params on renewToken, renewSelfToken, and renewAccessor functions (Refactoring)
    • Updated development env to `axios@0.21.1andjest@26.6.3`
    • Mentioned Richard (richie765) as contributor
  • 0.3.18

    • Enhanced promises rejection to follow best practice (Issue#4)
    • Removed Axios call wrapping with a new promise (Issue#4)
    • Refactored KV V2 functions to accept a mount point
    • Updated development environment to Vault 1.6.0
  • 0.3.17

    • Quick fix on KV v2 Function listKVSecrets when folder is defined
  • 0.3.16

    • Changed software license to EPL-2.0
    • Improved documentation about creating your test environment with HTTPS
    • Fixed and renamed KV v2 Function listKVSecrets to use the proper method
  • 0.3.15

    • Added PKI secret engine role functions:
      • createPkiRole (updatePkiRole), readPkiRole, listPkiRoles, and deletePkiRole
  • 0.3.14

    • Fixed package name typo in readme
    • Upgraded axios to 0.21.0 and jest to 26.6.1
    • Set jest async callback timeout on PKI test suite
  • 0.3.12

    • Added PKI secret engine certificate functions:
      • genPkiCertificate, and revokePkiCertificate
    • Added PKI secret engine CA functions:
      • genIntermediateCA, setIntermediateCA, and signIntermediateCA
      • deleteRootCA, and generateRootCA
    • Added PKI secret engine CRL functions: rotatePkiCrl
    • Restructured documentation
    • Improved PKI test suite
    • Fixed parameters mismatch for setPkiUrls
    • Added to PKI functions support for RootPath from the constructor
    • Added mount as parameter for PKI functions
  • 0.3.10

    • Added PKI secret engine certificate functions: genPkiCertificate, revokePkiCertificate, setIntermediateCA, signIntermediateCA, genIntermediateCA, deleteRootCA, and generateRootCA
    • Added PKI secret engine CRL Functions: rotatePkiCrl
  • 0.3.9

    • Added PKI secret engine functions
      • setCACertificate, readCACertificate, readCAChain, listCertificates, and readCertificate
      • setCrlConfig, readCrlConfig, setPkiUrls, readPkiUrls, and readPkiCrl
  • 0.3.8

    • Added Userpass auth method functions
      • loginWithUserpass
      • createUserpassUser (updateUserpassUser), readUserpassUser, deleteUserpassUser, updateUserpassPassword, updateUserpassPolicies, and listUserpassUsers
  • 0.3.7

    • Added LDAP auth method functions
      • loginWithLdap
      • createLdapUser (updateLdapUser), readLdapUser, deleteLdapUser, and listLdapUsers
      • createLdapGroup (updateLdapGroup), readLdapGroup, deleteLdapGroup, and listLdapGroup
    • Fixed Axios parsing order for error and response handling
    • Upgraded Axios to 0.20.0
  • 0.3.6

    • Upgraded dev environment to node.js v12.x
    • Fixed functions' interfaces documentation
  • 0.3.3

    • Added token auth method functions:
      • createToken (createSToken, createBToken, createOrphanSToken, createOrphanBToken)
      • listAccessors, lookupAccessor, renewAccessor, and revokeAccessor
      • renewToken and renewTokenSelf
      • lookupToken and lookupSelfToken
      • revokeToken and revokeSelfToken
      • listAccessors, lookupAccessor, renewAccessor and revokeAccessor
    • Refactored Axios options, and response parsing, and returned error parsing
  • 0.3.1

    • Added System backend helper functions sysHostInfo, sysCapabilities, sysCapabilitiesSelf, sysInternalCounters, and sysMetrics
    • Added System backend Seal functions sealStatus, sysSeal, and sysUnseal
    • Refactored and added to test suite
  • 0.2.3

    • Fixed security vulnerability on lodash dependency
  • 0.2.2

    • Improved documentation and README
    • Added new function healthCheck
  • 0.2.1

    • Fixed README and documentation
  • 0.2.0

    • Added new functions generateAppRoleSecretId, readAppRoleSecretId and destroyAppRoleSecretId
    • Improved test suite
  • 0.1.1

    • Removed dependency on fs as it's native now
  • 0.1.0

    • First working module with AppRole auth method and KV v2 secret engine

End of Document