Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS AWS KMS Decryption in Lambda

Let me start out by saying that it feels like this question is asked a lot, but none of the answers in the questions seem to resolve the issue I'm experiencing.

I am writing a lambda function in NodeJS. Everything about it works great except for trying to decrypt an encrypted environment variable.

In trying to get this to work, I've commented everything else about my Lambda out and I still get no results. Here's the code I'm working with right now:

const aws = require('aws-sdk')
exports.handler = async (event, context, callback) => {
    const kms = new aws.KMS()

    let params = {
      //CiphertextBlob: Buffer.from(process.env.SECRET_KEY, 'base64')
      CiphertextBlob: process.env.SECRET_KEY
    }

    console.log('before decrypt')
    console.log('SECRET_KEY', process.env.SECRET_KEY)

    kms.decrypt(params, function (err, data) {
      console.log('decrypt')
      if (err) console.log(err, err.stack) // an error occurred
      else     console.log(data)           // successful response
    })

    console.log('after decrypt')
}

The Lambda runs successfully, there is no error experienced. Here is the output from this code:

START RequestId: c3a83ca7-0f7a-11e9-84f1-a5f7503df368 Version: $LATEST
2019-01-03T17:12:36.726Z    c3a83ca7-0f7a-11e9-84f1-a5f7503df368    before decrypt
2019-01-03T17:12:36.763Z    c3a83ca7-0f7a-11e9-84f1-a5f7503df368    SECRET_KEY Encoded key string that I'm not putting in here
2019-01-03T17:12:36.765Z    c3a83ca7-0f7a-11e9-84f1-a5f7503df368    after decrypt
END RequestId: c3a83ca7-0f7a-11e9-84f1-a5f7503df368
REPORT RequestId: c3a83ca7-0f7a-11e9-84f1-a5f7503df368  Duration: 699.51 ms Billed Duration: 700 ms     Memory Size: 128 MB Max Memory Used: 40 MB  

As you can see, none of the console logs inside the decrypt callback actually show up, and I don't know why.

Using the buffer version of the secret key (line 6) instead of the plaintext version of the key (line 7) doesn't have any effect on the output either.

Can someone please help me figure out what I'm missing?

like image 939
Lisa Avatar asked Jan 03 '19 17:01

Lisa


Video Answer


1 Answers

This is the solution my coworker helped me with.

const aws = require('aws-sdk')
const kms = new aws.KMS()
exports.handler = async (event, context, callback) => {
  let params = {
    CiphertextBlob: Buffer.from(process.env.SECRET_KEY, 'base64')
  }

  let secret = null
  try {
    const decrypted = await kms.decrypt(params).promise()
    secret = decrypted.Plaintext.toString('utf-8')
  }
  catch (exception) {
    console.error(exception)
  }
}
like image 127
Lisa Avatar answered Oct 14 '22 16:10

Lisa