4.7.0 • Published 3 months ago

@azure/keyvault-secrets v4.7.0

Weekly downloads
55,024
License
MIT
Repository
github
Last release
3 months ago

Azure Key Vault Secrets client library for JS

Azure Key Vault is a service that allows you to encrypt authentication keys, storage account keys, data encryption keys, .pfx files, and passwords by using keys that are protected by hardware security modules (HSMs). If you would like to know more about Azure Key Vault, you may want to review What is Azure Key Vault?.

Azure Key Vault Secrets management allows you to securely store and tightly control access to tokens, passwords, certificates, API keys, and other secrets.

Use the client library for Azure Key Vault Secrets in your Node.js application to

  • Get, set and delete a secret.
  • Update a secret and it's attributes.
  • Backup and restore a secret.
  • Get, purge or recover a deleted secret.
  • Get all the versions of a secret.
  • Get all secrets.
  • Get all deleted secrets.

Please Note: This is a preview version of the Key Vault Secrets library

Source code | Package (npm) | API Reference Documentation | Product documentation | Samples

Getting started

Install the package

Install the Azure Key Vault Secrets client library using npm:

npm install @azure/keyvault-secrets

Prerequisites: You must have an Azure subscription and a Key Vault resource to use this package. If you are using this package in a Node.js application, then use Node.js 6.x or higher.

Configure Typescript

TypeScript users need to have Node type definitions installed:

npm install @types/node

You also need to enable compilerOptions.allowSyntheticDefaultImports in your tsconfig.json. Note that if you have enabled compilerOptions.esModuleInterop, allowSyntheticDefaultImports is enabled by default. See TypeScript's compiler options handbook for more information.

Configuring your Key Vault

Use the Azure Cloud Shell snippet below to create/get client secret credentials.

  • Create a service principal and configure its access to Azure resources:
    az ad sp create-for-rbac -n <your-application-name> --skip-assignment
    Output:
    {
      "appId": "generated-app-ID",
      "displayName": "dummy-app-name",
      "name": "http://dummy-app-name",
      "password": "random-password",
      "tenant": "tenant-ID"
    }
  • Use the above returned credentials information to set AZURE_CLIENT_ID(appId), AZURE_CLIENT_SECRET(password) and AZURE_TENANT_ID(tenant) environment variables. The following example shows a way to do this in Bash:

      export AZURE_CLIENT_ID="generated-app-ID"
      export AZURE_CLIENT_SECRET="random-password"
      export AZURE_TENANT_ID="tenant-ID"
  • Grant the above mentioned application authorization to perform secret operations on the keyvault:

    az keyvault set-policy --name <your-key-vault-name> --spn $AZURE_CLIENT_ID --secret-permissions backup delete get list create

    --secret-permissions: Accepted values: backup, delete, get, list, purge, recover, restore, create

  • Use the above mentioned Key Vault name to retrieve details of your Vault which also contains your Key Vault URL:

    az keyvault show --name <your-key-vault-name>

Key concepts

  • The Secrets client is the primary interface to interact with the API methods related to secrets in the Azure Key Vault API from a JavaScript application. Once initialized, it provides a basic set of methods that can be used to create, read, update and delete secrets.
  • A Secret version is a version of a secret in the Key Vault. Each time a user assigns a value to a unique secret name, a new version of that secret is created. Retrieving a secret by a name will always return the latest value assigned, unless a specific version is provided to the query.
  • Soft delete allows Key Vaults to support deletion and purging as two separate steps, so deleted secrets are not immediately lost. This only happens if the Key Vault has soft-delete enabled.
  • A Secret backup can be generated from any created secret. These backups come as binary data, and can only be used to regenerate a previously deleted secret.

Authenticating the client

To use the Key Vault from TypeScript/JavaScript, you need to first authenticate with the Key Vault service. To authenticate, first we import the identity and SecretsClient, which will connect to the key vault.

import { DefaultAzureCredential } from "@azure/identity";
import { SecretsClient } from "@azure/keyvault-secrets";

Once these are imported, we can next connect to the Key Vault service. To do this, we'll need to copy some settings from the Key Vault we are connecting to into our environment variables. Once they are in our environment, we can access them with the following code:

// DefaultAzureCredential expects the following three environment variables:
// * AZURE_TENANT_ID: The tenant ID in Azure Active Directory
// * AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant
// * AZURE_CLIENT_SECRET: The client secret for the registered application
const credential = new DefaultAzureCredential();

// Build the URL to reach your key vault
const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

// Lastly, create our secrets client and connect to the service
const client = new SecretsClient(url, credential);

Examples

The following sections provide code snippets that cover some of the common tasks using Azure Key Vault Secrets. The scenarios that are covered here consist of:

Creating and setting a secret

setSecret assigns a provided value to the specified secret name. If a secret with the same name already exists, then a new version of the secret is created.

const secretName = "MySecretName";
const result = await client.setSecret(secretName, "MySecretValue");

Getting a secret

The simplest way to read secrets back from the vault is to get a secret by name. This will retrieve the most recent version of the secret. You can optionally get a different version of the key if you specify it as part of the optional parameters.

const latestSecret = await client.getSecret(secretName);
console.log(`Latest version of the secret ${secretName}: `, getResult);
const specificSecret = await client.getSecret(secretName, { version: latestSecret.version! });
console.log(`The secret ${secretName} at the version ${latestSecret.version!}: `, getResult);

Creating and updating secrets with attributes

A secret can have more information than its name and its value. They can also include the following attributes:

  • tags: Any set of key-values that can be used to search and filter secrets.
  • contentType: Any string that can be used to help the receiver of the secret understand how to use the secret value.
  • enabled: A boolean value that determines whether the secret value can be read or not.
  • notBefore: A given date after which the secret value can be retrieved.
  • expires: A given date after which the secret value cannot be retrieved.

An object with these attributes can be sent as the third parameter of setSecret, right after the secret's name and value, as follows:

const result = await client.setSecret(secretName, "MySecretValue", {
  enabled: false
});

This will create a new version of the same secret, which will have the latest provided attributes.

Attributes can also be updated to an existing secret version with updateSecretAttributes, as follows:

const result = client.getSecret(secretName);
await client.updateSecretAttributes(secretName, result.version, { enabled: false });

Deleting a secret

The deleteSecret method sets a secret up for deletion. This process will happen in the background as soon as the necessary resources are available.

await client.deleteSecret(secretName);

If soft-delete is enabled for the Key Vault, this operation will only label the secret as a deleted secret. A deleted secret can't be updated. They can only be either read, recovered or purged.

await client.deleteSecret(secretName);

// If soft-delete is enabled, we can eventually do:
await client.getDeletedSecret(secretName);
// Deleted secrets can also be recovered or purged:
await client.recoverDeletedSecret(secretName);
// await client.purgeDeletedSecret(secretName);

Since the deletion of a secret won't happen instantly, some time is needed after the deleteSecret method is called before the deleted secret is available to be read, recovered or purged.

Iterating lists of secrets

Using the SecretsClient, you can retrieve and iterate through all of the secrets in a Key Vault, as well as through all of the deleted secrets and the versions of a specific secret. The following API methods are available:

  • listSecrets will list all of your non-deleted secrets by their names, only at their latest versions.
  • listDeletedSecrets will list all of your deleted secrets by their names, only at their latest versions.
  • listSecretVersions will list all the versions of a secret based on a secret name.

Which can be used as follows:

for await (let secret of client.listSecrets()) {
  console.log("Secret: ", secret);
}
for await (let deletedSecret of client.listDeletedSecrets()) {
  console.log("Deleted secret: ", deletedSecret);
}
for await (let version of client.listSecretVersions(secretName)) {
  console.log("Version: ", version);
}

All of these methods will return all of the available results at once. To retrieve them by pages, add .byPage() right after invoking the API method you want to use, as follows:

for await (let page of client.listSecrets().byPage()) {
  for (let secret of page) {
    console.log("Secret: ", secret);
  }
}
for await (let page of client.listDeletedSecrets().byPage()) {
  for (let deletedSecret of page) {
    console.log("Deleted secret: ", deletedSecret);
  }
}
for await (let page of client.listSecretVersions(secretName).byPage()) {
  for (let version of page) {
    console.log("Version: ", version);
  }
}

Troubleshooting

Enable logs

You can set the following environment variable to get the debug logs when using this library.

  • Getting debug logs from the Key Vault Secrets SDK
export DEBUG=azure*

Next steps

Please take a look at the samples directory for detailed examples on how to use this library.

Contributing

This project welcomes contributions and suggestions. Please read the contributing guidelines for detailed information about how to contribute and what to expect while contributing.

Testing

To run our tests, first install the dependencies (with npm install or rush install), then run the unit tests with: npm run unit-test. Our unit tests that target the behavior of our library against remotely available endpoints are executed using previously recorded HTTP request and responses.

Our integration tests will run against the live resources, which are determined by the environment variables you provide. To run the integration tests, you can run npm run integration-test, but make sure to provide the following environment variables:

  • AZURE_CLIENT_ID: The Client ID of your Azure account.
  • AZURE_CLIENT_SECRET: The secret of your Azure account.
  • AZURE_TENANT_ID: The Tenant ID of your Azure account.
  • KEYVAULT_NAME: The name of the Key Vault you want to run the tests against.

WARNING: Integration tests will wipe all of the existing records in the targeted Key Vault.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Impressions

rentalainen-apisnitch2md-common-servicesmaitsa-serviceaz-calibers-globalaz-hy-databasesazure-calibers-cloudpcaz-hy-publicappsaz-ky-aks-on-offaz-ky-kube-appsaz-mbs-aksaz-mbs-sharedrunk-codingks-ky-deepseaks-ky-apimks-ky-apim-balance@chris7ca/ewallet-shareddlt-app@pixm/pixm-core-libinject-az-keyvaultdevops-endpoint-manager-dummy@everything-registry/sub-chunk-107cc-backml-node-akv@bunbot/azurekeyvault-loaderqa-utils-pruebas@lilaquadrat/hosting@lilaquadrat/studioses-create-domain-cliskyeye-libraryskyeye-svc-common-grpcskyeye-svc-common-utilssidelab-key-vault@radutils/config-builder-source-azuresimple-az@onevor/ymir-plugin-azure-key-vault@myorganisationtbc/common@mcma/azure-key-vault@nordicsemiconductor/asset-tracker-cloud-azuresofy-common-services-testsbq-message-handler-js-dotnetcorespk@thxmike/azure-key-vault-clientsecureactions@purista/azure-secret-storedrunk-pulumieth-key-vaultenhanced-env-azure-vaultdt-common-libsadanicommonmodulefailure-azurefunctionsfastify-secrets-azurekv-migration-aws@elenaizaguirre/cactus-plugin-keychain-azure-kv@eqxjs/azure-manage-identity-demo@eqxjs/kms-demo@eqxjs/azure-manage-identity@fernandezfalvaro/wallet-hsm-azuremanulife-neo-ors-backendmergein-azure-keyvault-helpermfonic-test-packagemicrosoft-identity-expresshelen-common-infragreenlock-store-az-keyvaultgreenlock-store-keyvaultinsomnia-plugin-azure-keyvault-secrets@achs/azure-key-vaultverifiablecredentials-crypto-sdk-typescriptverifiablecredentials-crypto-sdk-typescript-plugin-keyvaultaz-keyvaultazure-env-app-configurationazure-app-proxy-managerazure-k8s-configazure-key-vault-envtrack-search-functionstrevorcontractkitacme-http-01-azure-key-vault-middlewarewrapperkv@azberry/az-simple@azure/app-configuration-providercirruswavecitadel-svc-common-secrets-servicecitadel-svc-common-utils@configu/node@basis-theory/basis-theory-js-encryption-azure@codiac.io/codiac-ops-enterprise@cs-chatbots/router-masterbot-toolscloudkeys@calvear/azure-key-vaultcc-backend-tscds.email-subscription@celo/wallet-hsm-azure@codebucket/azure-env@digifi/app-config-loader@delphai/typed-configcodegenapp@drunk-pulumi/azure-providers@hmcts/properties-volumecypress-azure-keyvaultcuong.nc.dev-common
4.8.0-beta.1

6 months ago

4.7.0

1 year ago

4.6.0

2 years ago

4.5.1

2 years ago

4.5.0-beta.1

2 years ago

4.5.0

2 years ago

4.4.0

2 years ago

4.4.0-beta.2

2 years ago

4.4.0-beta.1

3 years ago

4.3.0

3 years ago

4.2.0

3 years ago

4.2.0-beta.4

3 years ago

4.2.0-beta.3

3 years ago

4.2.0-beta.2

3 years ago

4.2.0-beta.1

4 years ago

4.1.0

4 years ago

4.0.4

4 years ago

4.0.3

4 years ago

4.1.0-preview.1

4 years ago

4.0.2

4 years ago

4.0.1

4 years ago

4.0.0

4 years ago

4.0.0-preview.9

5 years ago

4.0.0-preview.8

5 years ago

4.0.0-preview.7

5 years ago

4.0.0-preview.5

5 years ago

4.0.0-preview.4

5 years ago

4.0.0-preview.3

5 years ago

4.0.0-preview.2

5 years ago

4.0.0-preview.1

5 years ago