For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Use Automatic Queryable Encryption with AWS

This guide shows you how to build an application that implements the MongoDB Queryable Encryption feature to automatically encrypt and decrypt document fields and use Amazon Web Services (AWS) KMS for key management.

After you complete the steps in this guide, you should have:

  • A Customer Master Key managed by AWS KMS

  • An AWS IAM user with permissions to access the Customer Master Key in AWS KMS

  • A working client application that inserts documents with encrypted fields using your Customer Master Key

Tip

Customer Master Keys

To learn more about the Customer Master Key, read the Encryption Keys and Key Vaults documentation.

To complete and run the code in this guide, you need to set up your development environment as shown in the Install a Queryable Encryption Compatible Driver and Dependencies page.

Tip

See: Full Application

To see the complete code for this sample application, select the tab corresponding to your programming language and follow the provided link. Each sample application repository includes a README.md file that you can use to learn how to set up your environment and run the application.

1

Create a new symmetric key by following the official AWS documentation on Creating symmetric KMS keys. The key you create is your Customer Master Key. Choose a name and description that helps you identify it; these fields do not affect the functionality or configuration of your CMK.

In the Usage Permissions step of the key generation process, apply the following default key policy that enables Identity and Access Management (IAM) policies to grant access to your Customer Master Key:

{ "Version": "2012-10-17", "Statement": [ { "Sid": "Enable IAM User Permissions", "Effect": "Allow", "Principal": { "AWS": "<ARN of your AWS account principal>" }, "Action": "kms:*", "Resource": "*" } ]}

Important

Record the Amazon Resource Name (ARN) and Region of your Customer Master Key. You will use these in later steps of this guide.

Tip

Key Policies

To learn more about key policies, see Key Policies in AWS KMS in the official AWS documentation.

2

Create a new programmatic IAM user in the AWS management console by following the official AWS documentation on Adding a User. You will use this IAM user as a service account for your Queryable Encryption-enabled application. Your application authenticates with AWS KMS using the IAM user to encrypt and decrypt your Data Encryption Keys (DEKs) with your Customer Master Key (CMK).

Important

Record your Credentials

Ensure you record the following IAM credentials in the final step of creating your IAM user:

  • access key ID

  • secret access key

You have one opportunity to record these credentials. If you do not record these credentials during this step, you must create another IAM user.

Grant your IAM user kms:Encrypt and kms:Decrypt permissions for your remote master key.

Important

The new client IAM user should not have administrative permissions for the master key. To keep your data secure, follow the principle of least privilege.

The following inline policy allows an IAM user to encrypt and decrypt with the Customer Master Key with the least privileges possible:

Note

Remote Master Key ARN

The following policy requires the ARN of the key you generate in the Create the Master Key step of this guide.

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["kms:Decrypt", "kms:Encrypt"], "Resource": "<the Amazon Resource Name (ARN) of your remote master key>" } ]}

To apply the preceding policy to your IAM user, follow the Adding IAM identity permissions guide in the AWS documentation.

Important

Authenticate with IAM Roles in Production

When deploying your Queryable Encryption-enabled application to a production environment, authenticate your application by using an IAM role instead of an IAM user.

To learn more about IAM roles, see the following pages in the official AWS documentation:

1

The code samples in this tutorial use the following variables to perform the Queryable Encryption workflow:

  • kmsProviderName - The KMS you're using to store your Customer Master Key. Set this variable to "aws" for this tutorial.

  • uri - Your MongoDB deployment connection URI. Set your connection URI in the MONGODB_URI environment variable or replace the value directly.

  • keyVaultDatabaseName - The database in MongoDB where your data encryption keys (DEKs) will be stored. Set this variable to "encryption".

  • keyVaultCollectionName - The collection in MongoDB where your DEKs will be stored. Set this variable to "__keyVault".

  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this variable to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The database in MongoDB where your encrypted data will be stored. Set this variable to "medicalRecords".

  • encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this variable to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"const kmsProviderName = "<Your KMS Provider Name>";const uri = process.env.MONGODB_URI; // Your connection URIconst keyVaultDatabaseName = "encryption";const keyVaultCollectionName = "__keyVault";const keyVaultNamespace = `${keyVaultDatabaseName}.${keyVaultCollectionName}`;const encryptedDatabaseName = "medicalRecords";const encryptedCollectionName = "patients";

Important

Key Vault Collection Namespace Permissions

The Key Vault collection is in the encryption.__keyVault namespace. Ensure that the database user your application uses to connect to MongoDB has ReadWrite permissions on this namespace.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

2

Create a variable containing your AWS KMS credentials with the following structure. Use the Access Key ID and Secret Access Key you created in the Create an IAM User step of this tutorial.

kmsProviderCredentials = { aws: { accessKeyId: process.env["AWS_ACCESS_KEY_ID"], // Your AWS access key ID secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"], // Your AWS secret access key },};

Important

Reminder: Authenticate with IAM Roles in Production

To use an IAM role instead of an IAM user to authenticate your application, specify an empty object for your credentials in your KMS provider object. This instructs the driver to automatically retrieve the credentials from the environment:

kmsProviders = { aws: { }};

Create a variable containing your Customer Master Key credentials with the following structure. Use the ARN and Region you recorded in the Create a Customer Master Key step of this tutorial.

customerMasterKeyCredentials = { key: process.env["AWS_KEY_ARN"], // Your AWS Key ARN region: process.env["AWS_KEY_REGION"], // Your AWS Key Region};

Create an autoEncryptionOptions object that contains the following options:

  • The namespace of your Key Vault collection

  • The kmsProviderCredentials object, which contains your AWS KMS credentials

const autoEncryptionOptions = { keyVaultNamespace: keyVaultNamespace, kmsProviders: kmsProviderCredentials,};

Note

Automatic Encryption Options

The automatic encryption options provide configuration information to the Automatic Encryption Shared Library, which modifies the application's behavior when accessing encrypted fields.

To learn more about the Automatic Encryption Shared Library, see the Automatic Encryption Shared Library for Queryable Encryption page.

To create a client used to encrypt and decrypt data in your collection, instantiate a new MongoClient by using your connection URI and your automatic encryption options.

const encryptedClient = Mongo(uri, autoEncryptionOptions);

To encrypt a field, add it to the encryption schema. To enable queries on a field, add the "queries" property. Create the encryption schema as follows:

const encryptedFieldsMap = { encryptedFields: { fields: [ { path: "patientRecord.ssn", bsonType: "string", queries: { queryType: "equality" }, }, { path: "patientRecord.billing", bsonType: "object", }, ], },};

Note

In the previous code sample, both the "ssn" and "billing" fields are encrypted, but only the "ssn" field can be queried.

Instantiate ClientEncryption to access the API for the encryption helper methods.

const clientEncryption = encryptedClient.getClientEncryption()

Create your encrypted collection by using the encryption helper method accessed through the ClientEncryption class. This method automatically generates data encryption keys for your encrypted fields and creates the encrypted collection:

await clientEncryption.createEncryptedCollection( encryptedDatabaseName, encryptedCollectionName, { provider: kmsProviderName, createCollectionOptions: encryptedFieldsMap, masterKey: customerMasterKeyCredentials, });
3

Create a sample document that describes a patient's personal information. Use the encrypted client to insert it into the patients collection, as shown in the following example:

const patientDocument = { patientName: "Jon Doe", patientId: 12345678, patientRecord: { ssn: "987-65-4320", billing: { type: "Visa", number: "4111111111111111", }, },}; const encryptedCollection = encryptedClient.getDB(encryptedDatabaseName).getCollection(encryptedCollectionName); const insertResult = await encryptedCollection.insertOne(patientDocument);
4

The following code sample executes a find query on an encrypted field and prints the decrypted data:

const findResult = await encryptedCollection.findOne({ "patientRecord.ssn": "987-65-4320",});console.log(findResult);

The output of the preceding code sample should look similar to the following:

{ "_id": { "$oid": "648b384a722cb9b8392df76a" }, "name": "Jon Doe", "record": { "ssn": "987-65-4320", "billing": { "type": "Visa", "number": "4111111111111111" } }, "__safeContent__": [ { "$binary": { "base64": "L1NsYItk0Sg+oL66DBj6IYHbX7tveANQyrU2cvMzD9Y=", "subType": "00" } } ]}

Warning

Do not Modify the __safeContent__ Field

The __safeContent__ field is essential to Queryable Encryption. Do not modify the contents of this field.

To learn how Queryable Encryption works, see Queryable Encryption Fundamentals.

To learn more about the topics mentioned in this guide, see the following links:

  • Learn more about Queryable Encryption components on the Reference page.

  • Learn how Customer Master Keys and Data Encryption Keys work on the Encryption Keys and Key Vaults page.

  • See how KMS Providers manage your Queryable Encryption keys on the KMS Providers page.