Skip to content

Instantly share code, notes, and snippets.

@florianbepunkt
Created August 29, 2020 14:40
Show Gist options
  • Save florianbepunkt/53ccbbc8a47e1acd386354292ae43f26 to your computer and use it in GitHub Desktop.
Save florianbepunkt/53ccbbc8a47e1acd386354292ae43f26 to your computer and use it in GitHub Desktop.
const { Binary, MongoClient } = require("mongodb");
const path = require("path");
const connectionString =
"mongodb+srv://OMMITED.mongodb.net/yourDatabase?retryWrites=true&w=majority";
const keyVaultNamespace = "yourDatabase.__keyVault";
const base64KeyId = "OMITTED";
const createSchema = () => {
return {
"yourDatabase.test": {
bsonType: "object",
encryptMetadata: {
keyId: [new Binary(Buffer.from(base64KeyId, "base64"), 4)],
},
properties: {
foo: {
encrypt: {
bsonType: "string",
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
},
},
},
},
};
};
const kmsProviders = {
aws: {
accessKeyId: "OMITTED",
secretAccessKey: "OMITTED",
},
};
module.exports.hello = async (event) => {
const tmpPath = path.resolve(process.env.LAMBDA_TASK_ROOT, "../../tmp");
process.env.LD_LIBRARY_PATH = `${process.env.LD_LIBRARY_PATH}:${process.env.LAMBDA_TASK_ROOT}/lib`;
const secureClient = new MongoClient(connectionString, {
connectTimeoutMS: 7000,
useNewUrlParser: true,
useUnifiedTopology: true,
autoEncryption: {
keyVaultNamespace,
kmsProviders,
schemaMap: createSchema(),
extraOptions: {
mongocryptdSpawnArgs: [`--pidfilepath=${tmpPath}/mongocryptd.pid`],
mongocryptdSpawnPath: `${process.env.LAMBDA_TASK_ROOT}/bin/mongocryptd`,
},
},
});
await secureClient.connect();
const collection = secureClient.db("development").collection("test");
await collection.insertOne({
foo: "bar",
});
const resp = await collection.find({}).toArray();
return {
statusCode: 200,
body: JSON.stringify(resp),
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment