Skip to content

Instantly share code, notes, and snippets.

@jdelibas

jdelibas/README.md

Last active Jun 7, 2017
Embed
What would you like to do?
AWS KMS and S3 secret storage

AWS KMS and S3 secret storage

Usage

const Secrets = require('./Secrets')
const secrets = new Secrets({
  accessKeyId: 'some aws access key id',
  secretAccessKey: 'some aws secret access key'
})

const bucket = 'some-s3-bucket'
const filename = 'some.secrets'
const keyid = 'some kms key id'

async function demo () {
  try {
    // Load secrets from s3 and decrypt them
    // returns object
    let decrypted = await this.aws.getSecrets({
      bucket,
      filename
    })
    console.log(decrypted)
    
    // Edit the object
    decrypted['newkey'] = 'new data'
    
    // Save the new object (encrypt and store in s3)
    return await this.aws.saveSecrets({
      bucket,
      filename,
      keyid,
      data: decrypted
    })
  } catch (e) {
    throw (e)
  }
}

demo()
  .then(res => console.log(res))
  .catch(err => console.log(err))
/* global TextDecoder */
const AWSSDK = require('aws-sdk')
AWSSDK.config.setPromisesDependency(Promise)
export default class Secrets{
constructor (config) {
AWSSDK.config = config
this.s3 = new AWSSDK.S3()
this.kms = new AWSSDK.KMS()
}
async getSecrets ({ bucket, filename }) {
try {
const s3Params = {
Bucket: bucket,
Key: filename
}
const res = await this.s3.getObject(s3Params).promise()
const kmsParams = {
CiphertextBlob: res.Body
}
const decrypted = await this.kms.decrypt(kmsParams).promise()
// decode uint8 array
const decoded = new TextDecoder('utf-8').decode(decrypted.Plaintext)
return JSON.parse(decoded)
} catch (e) {
throw e
}
}
async saveSecrets ({ bucket, filename, keyid, data }) {
try {
const kmsParams = {
KeyId: keyid,
Plaintext: JSON.stringify(data)
}
const encrypted = await this.kms.encrypt(kmsParams).promise()
const s3Params = {
Bucket: bucket,
Key: filename,
Body: encrypted.CiphertextBlob
}
return await this.s3.putObject(s3Params).promise()
} catch (e) {
throw e
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment