Skip to content

Instantly share code, notes, and snippets.

@TimothyJones
Last active September 4, 2022 04:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save TimothyJones/8165694951385246c665dc94ef18702e to your computer and use it in GitHub Desktop.
Save TimothyJones/8165694951385246c665dc94ef18702e to your computer and use it in GitHub Desktop.
A javascript module that demonstrates decrypting some KMS-encrypted environment variables
const AWS = require('aws-sdk');
const encryptedEnvironmentVariableNames = ['SOME_VARIABLE', 'SOME_OTHER_VARIABLE'];
// This module exports a function that returns a promise for obtaining
// a decrypted copy of the environnment.
//
// Configure it by putting the name of each environment variable you would like to
// decrypt above.
//
// When successful, the promise resolves to a copy of process.env with
// each variable listed above decrypted.
//
const kms = new AWS.KMS();
// This function is the core decryption.
// It's just a promisified kms.decrypt call
const decrypt = data =>
new Promise((resolve, reject) =>
kms.decrypt(
{
CiphertextBlob: Buffer.from(data, 'base64')
},
(err, result) => {
if (err) {
reject(err);
} else {
resolve(result.Plaintext.toString());
}
}
)
);
const decryptedEnv = Promise.all(
// This uses the named variables defined at the top to determine what to decrypt.
// Depending on your needs, you could instead filter the existing environment
// on some pattern (eg all env vars starting with "ENCRYPTED_SECRET_") to
// determine what to decrypt.
encryptedEnvironmentVariableNames.map(name =>
decrypt(process.env[name]).then(data => ({ [name]: data }))
)
).then(array =>
array.reduce((config, item) => ({ ...config, ...item }), { ...process.env })
);
// We export a promise directly, so that it will stay resolved in
// future executions of the same lambda, reducing the number of decryption calls
module.exports = decryptedEnv;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment