<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Encryption - MongoDB Rust Driver</title>
<!-- Custom HTML head -->
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="favicon.svg">
<link rel="shortcut icon" href="favicon.png">
<link rel="stylesheet" href="css/variables.css">
<link rel="stylesheet" href="css/general.css">
<link rel="stylesheet" href="css/chrome.css">
<link rel="stylesheet" href="css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<link rel="stylesheet" href="ayu-highlight.css">
<!-- Custom theme stylesheets -->
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded "><a href="index.html"><strong aria-hidden="true">1.</strong> Introduction</a></li><li class="chapter-item expanded "><a href="installation_features.html"><strong aria-hidden="true">2.</strong> Installation and Features</a></li><li class="chapter-item expanded "><a href="connecting.html"><strong aria-hidden="true">3.</strong> Connecting to the Database</a></li><li class="chapter-item expanded "><a href="reading.html"><strong aria-hidden="true">4.</strong> Reading From the Database</a></li><li class="chapter-item expanded "><div><strong aria-hidden="true">5.</strong> Writing To the Database</div></li><li class="chapter-item expanded "><a href="performance.html"><strong aria-hidden="true">6.</strong> Performance</a></li><li class="chapter-item expanded "><div><strong aria-hidden="true">7.</strong> Serde Integration</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">8.</strong> Sessions and Transactions</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">9.</strong> Change Streams</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">10.</strong> Monitoring</div></li><li class="chapter-item expanded "><a href="tracing.html"><strong aria-hidden="true">11.</strong> Tracing and Logging</a></li><li class="chapter-item expanded "><a href="web_framework_examples.html"><strong aria-hidden="true">12.</strong> Web Framework Examples</a></li><li class="chapter-item expanded "><a href="encryption.html" class="active"><strong aria-hidden="true">13.</strong> Encryption</a></li><li class="chapter-item expanded affix "><li class="part-title">Development</li><li class="chapter-item expanded "><div><strong aria-hidden="true">14.</strong> Writing Tests</div></li></ol>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">MongoDB Rust Driver</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="unstable-api"><a class="header" href="#unstable-api">Unstable API</a></h1>
<p>To enable support for in-use encryption (<a href="https://www.mongodb.com/docs/manual/core/csfle/">client-side field level encryption</a> and <a href="https://www.mongodb.com/docs/manual/core/queryable-encryption/">queryable encryption</a>), enable the <code>"in-use-encryption-unstable"</code> feature of the <code>mongodb</code> crate. As the name implies, the API for this feature is unstable, and may change in backwards-incompatible ways in minor releases.</p>
<h1 id="client-side-field-level-encryption"><a class="header" href="#client-side-field-level-encryption">Client-Side Field Level Encryption</a></h1>
<p>Starting with MongoDB 4.2, client-side field level encryption allows an application to encrypt specific data fields in addition to pre-existing MongoDB encryption features such as <a href="https://dochub.mongodb.org/core/security-encryption-at-rest">Encryption at Rest</a> and <a href="https://dochub.mongodb.org/core/security-tls-transport-encryption">TLS/SSL (Transport Encryption)</a>.</p>
<p>With field level encryption, applications can encrypt fields in documents prior to transmitting data over the wire to the server. Client-side field level encryption supports workloads where applications must guarantee that unauthorized parties, including server administrators, cannot read the encrypted data.</p>
<p>See also the MongoDB documentation on <a href="https://dochub.mongodb.org/core/client-side-field-level-encryption">Client Side Field Level Encryption</a>.</p>
<h2 id="dependencies"><a class="header" href="#dependencies">Dependencies</a></h2>
<p>To get started using client-side field level encryption in your project, you will need to install <a href="https://github.com/mongodb/libmongocrypt">libmongocrypt</a>, which can be fetched from a <a href="https://www.mongodb.com/docs/manual/core/csfle/reference/libmongocrypt/#std-label-csfle-reference-libmongocrypt">variety of package repositories</a>. If you install libmongocrypt in a location outside of the system library search path, the <code>MONGOCRYPT_LIB_DIR</code> environment variable will need to be set when compiling your project.</p>
<p>Additionally, either <code>crypt_shared</code> or <code>mongocryptd</code> are required in order to use automatic client-side encryption.</p>
<h3 id="crypt_shared"><a class="header" href="#crypt_shared">crypt_shared</a></h3>
<p>The Automatic Encryption Shared Library (crypt_shared) provides the same functionality as mongocryptd, but does not require you to spawn another process to perform automatic encryption.</p>
<p>By default, the <code>mongodb</code> crate attempts to load crypt_shared from the system and if found uses it automatically. To load crypt_shared from another location, set the <code>"cryptSharedLibPath"</code> field in <code>extra_options</code>:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">use mongodb::{bson::doc, Client, error::Result};
</span><span class="boring">
</span><span class="boring">async fn func() -> Result<()> {
</span><span class="boring">let options = todo!();
</span><span class="boring">let kv_namespace = todo!();
</span><span class="boring">let kms_providers: Vec<_> = todo!();
</span>let client = Client::encrypted_builder(options, kv_namespace, kms_providers)?
.extra_options(doc! {
"cryptSharedLibPath": "/path/to/crypt/shared",
})
.build();
<span class="boring">
</span><span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<p>If the <code>mongodb</code> crate cannot load crypt_shared it will attempt to fallback to using mongocryptd by default. Include <code>"cryptSharedRequired": true</code> in the <code>extra_options</code> document to always use crypt_shared and fail if it could not be loaded.</p>
<p>For detailed installation instructions see the <a href="https://www.mongodb.com/docs/manual/core/queryable-encryption/reference/shared-library">MongoDB documentation on Automatic Encryption Shared Library</a>.</p>
<h3 id="mongocryptd"><a class="header" href="#mongocryptd">mongocryptd</a></h3>
<p>If using <code>crypt_shared</code> is not an option, the <code>mongocryptd</code> binary is required for automatic client-side encryption and is included as a component in the <a href="https://dochub.mongodb.org/core/install-mongodb-enterprise">MongoDB Enterprise Server package</a>. For detailed installation instructions see the <a href="https://dochub.mongodb.org/core/client-side-field-level-encryption-mongocryptd">MongoDB documentation on mongocryptd</a>.</p>
<p><code>mongocryptd</code> performs the following:</p>
<ul>
<li>Parses the automatic encryption rules specified to the database connection. If the JSON schema contains invalid automatic encryption syntax or any document validation syntax, <code>mongocryptd</code> returns an error.</li>
<li>Uses the specified automatic encryption rules to mark fields in read and write operations for encryption.</li>
<li>Rejects read/write operations that may return unexpected or incorrect results when applied to an encrypted field. For supported and unsupported operations, see <a href="https://dochub.mongodb.org/core/client-side-field-level-encryption-read-write-support">Read/Write Support with Automatic Field Level Encryption</a>.</li>
</ul>
<p>A <code>Client</code> configured with auto encryption will automatically spawn the <code>mongocryptd</code> process from the application's <code>PATH</code>. Applications can control the spawning behavior as part of the automatic encryption options:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">use mongodb::{bson::doc, Client, error::Result};
</span><span class="boring">
</span><span class="boring">async fn func() -> Result<()> {
</span><span class="boring">let options = todo!();
</span><span class="boring">let kv_namespace = todo!();
</span><span class="boring">let kms_providers: Vec<_> = todo!();
</span>let client = Client::encrypted_builder(options, kv_namespace, kms_providers)?
.extra_options(doc! {
"mongocryptdSpawnPath": "/path/to/mongocryptd",
"mongocryptdSpawnArgs": ["--logpath=/path/to/mongocryptd.log", "--logappend"],
})
.build();
<span class="boring">
</span><span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<p>If your application wishes to manage the <code>mongocryptd</code> process manually, it is possible to disable spawning <code>mongocryptd</code>:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">use mongodb::{bson::doc, Client, error::Result};
</span><span class="boring">
</span><span class="boring">async fn func() -> Result<()> {
</span><span class="boring">let options = todo!();
</span><span class="boring">let kv_namespace = todo!();
</span><span class="boring">let kms_providers: Vec<_> = todo!();
</span>let client = Client::encrypted_builder(options, kv_namespace, kms_providers)?
.extra_options(doc! {
"mongocryptdBypassSpawn": true,
"mongocryptdURI": "mongodb://localhost:27020",
})
.build();
<span class="boring">
</span><span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<p><code>mongocryptd</code> is only responsible for supporting automatic client-side field level encryption and does not itself perform any encryption or decryption.</p>
<h2 id="automatic-client-side-field-level-encryption"><a class="header" href="#automatic-client-side-field-level-encryption">Automatic Client-Side Field Level Encryption</a></h2>
<p>Automatic client-side field level encryption is enabled by using the <code>Client::encrypted_builder</code> constructor method. The following examples show how to setup automatic client-side field level encryption using <code>ClientEncryption</code> to create a new encryption data key.</p>
<p><em>Note</em>: Automatic client-side field level encryption requires MongoDB 4.2+ enterprise or a MongoDB 4.2+ Atlas cluster. The community version of the server supports automatic decryption as well as explicit client-side encryption.</p>
<h3 id="providing-local-automatic-encryption-rules"><a class="header" href="#providing-local-automatic-encryption-rules">Providing Local Automatic Encryption Rules</a></h3>
<p>The following example shows how to specify automatic encryption rules via the <code>schema_map</code> option. The automatic encryption rules are expressed using a <a href="https://dochub.mongodb.org/core/client-side-field-level-encryption-automatic-encryption-rules">strict subset of the JSON Schema syntax</a>.</p>
<p>Supplying a <code>schema_map</code> provides more security than relying on JSON Schemas obtained from the server. It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted data that should be encrypted.</p>
<p>JSON Schemas supplied in the <code>schema_map</code> only apply to configuring automatic client-side field level encryption. Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.</p>
<!--- Changes to this example should also be made to manual/deps/src/example/local_rules.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use mongodb::{
bson::{self, doc, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::KmsProvider,
options::ClientOptions,
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
// The MongoDB namespace (db.collection) used to store the
// encrypted documents in this example.
let encrypted_namespace = Namespace::new("test", "coll");
// This must be the same master key that was used to create
// the encryption key.
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
// The MongoDB namespace (db.collection) used to store
// the encryption data keys.
let key_vault_namespace = Namespace::new("encryption", "__testKeyVault");
// The MongoClient used to access the key vault (key_vault_namespace).
let key_vault_client = Client::with_uri_str(URI).await?;
let key_vault = key_vault_client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
key_vault_client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
// Create a new data key and json schema for the encryptedField.
// https://dochub.mongodb.org/core/client-side-field-level-encryption-automatic-encryption-rules
let data_key_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["encryption_example_1".to_string()])
.run()
.await?;
let schema = doc! {
"properties": {
"encryptedField": {
"encrypt": {
"keyId": [data_key_id],
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
}
}
},
"bsonType": "object",
};
let client = Client::encrypted_builder(
ClientOptions::parse(URI).await?,
key_vault_namespace,
kms_providers,
)?
.schema_map([(encrypted_namespace.to_string(), schema)])
.build()
.await?;
let coll = client
.database(&encrypted_namespace.db)
.collection::<Document>(&encrypted_namespace.coll);
// Clear old data.
coll.drop(None).await?;
coll.insert_one(doc! { "encryptedField": "123456789" }, None)
.await?;
println!("Decrypted document: {:?}", coll.find_one(None, None).await?);
let unencrypted_coll = Client::with_uri_str(URI)
.await?
.database(&encrypted_namespace.db)
.collection::<Document>(&encrypted_namespace.coll);
println!(
"Encrypted document: {:?}",
unencrypted_coll.find_one(None, None).await?
);
Ok(())
}</code></pre></pre>
<h3 id="server-side-field-level-encryption-enforcement"><a class="header" href="#server-side-field-level-encryption-enforcement">Server-Side Field Level Encryption Enforcement</a></h3>
<p>The MongoDB 4.2+ server supports using schema validation to enforce encryption of specific fields in a collection. This schema validation will prevent an application from inserting unencrypted values for any fields marked with the <code>"encrypt"</code> JSON schema keyword.</p>
<p>The following example shows how to setup automatic client-side field level encryption using <code>ClientEncryption</code> to create a new encryption data key and create a collection with the <a href="https://dochub.mongodb.org/core/client-side-field-level-encryption-automatic-encryption-rules">Automatic Encryption JSON Schema Syntax</a>:</p>
<!--- Changes to this example should also be made to manual/deps/src/example/server_side_enforcement.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use mongodb::{
bson::{self, doc, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::KmsProvider,
options::{ClientOptions, CreateCollectionOptions, WriteConcern},
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
// The MongoDB namespace (db.collection) used to store the
// encrypted documents in this example.
let encrypted_namespace = Namespace::new("test", "coll");
// This must be the same master key that was used to create
// the encryption key.
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
// The MongoDB namespace (db.collection) used to store
// the encryption data keys.
let key_vault_namespace = Namespace::new("encryption", "__testKeyVault");
// The MongoClient used to access the key vault (key_vault_namespace).
let key_vault_client = Client::with_uri_str(URI).await?;
let key_vault = key_vault_client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
key_vault_client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
// Create a new data key and json schema for the encryptedField.
let data_key_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["encryption_example_2".to_string()])
.run()
.await?;
let schema = doc! {
"properties": {
"encryptedField": {
"encrypt": {
"keyId": [data_key_id],
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
}
}
},
"bsonType": "object",
};
let client = Client::encrypted_builder(
ClientOptions::parse(URI).await?,
key_vault_namespace,
kms_providers,
)?
.build()
.await?;
let db = client.database(&encrypted_namespace.db);
let coll = db.collection::<Document>(&encrypted_namespace.coll);
// Clear old data
coll.drop(None).await?;
// Create the collection with the encryption JSON Schema.
db.create_collection(
&encrypted_namespace.coll,
CreateCollectionOptions::builder()
.write_concern(WriteConcern::MAJORITY)
.validator(doc! { "$jsonSchema": schema })
.build(),
).await?;
coll.insert_one(doc! { "encryptedField": "123456789" }, None)
.await?;
println!("Decrypted document: {:?}", coll.find_one(None, None).await?);
let unencrypted_coll = Client::with_uri_str(URI)
.await?
.database(&encrypted_namespace.db)
.collection::<Document>(&encrypted_namespace.coll);
println!(
"Encrypted document: {:?}",
unencrypted_coll.find_one(None, None).await?
);
// This would return a Write error with the message "Document failed validation".
// unencrypted_coll.insert_one(doc! { "encryptedField": "123456789" }, None)
// .await?;
Ok(())
}</code></pre></pre>
<h3 id="automatic-queryable-encryption"><a class="header" href="#automatic-queryable-encryption">Automatic Queryable Encryption</a></h3>
<p>Verison 2.4.0 of the <code>mongodb</code> crate brings support for Queryable Encryption with MongoDB >=6.0.</p>
<p>Queryable Encryption is the second version of Client-Side Field Level Encryption. Data is encrypted client-side. Queryable Encryption supports indexed encrypted fields, which are further processed server-side.</p>
<p>You must have MongoDB 6.0 Enterprise to preview the feature.</p>
<p>Automatic encryption in Queryable Encryption is configured with an <code>encrypted_fields</code> mapping, as demonstrated by the following example:</p>
<!--- Changes to this example should also be made to manual/deps/src/example/automatic_queryable_encryption.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">extern crate futures;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use futures::TryStreamExt;
use mongodb::{
bson::{self, doc, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::KmsProvider,
options::ClientOptions,
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
let key_vault_namespace = Namespace::new("keyvault", "datakeys");
let key_vault_client = Client::with_uri_str(URI).await?;
let key_vault = key_vault_client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
key_vault_client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
let key1_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["firstName".to_string()])
.run()
.await?;
let key2_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["lastName".to_string()])
.run()
.await?;
let encrypted_fields_map = vec![(
"example.encryptedCollection",
doc! {
"escCollection": "encryptedCollection.esc",
"eccCollection": "encryptedCollection.ecc",
"ecocCollection": "encryptedCollection.ecoc",
"fields": [
{
"path": "firstName",
"bsonType": "string",
"keyId": key1_id,
"queries": [{"queryType": "equality"}],
},
{
"path": "lastName",
"bsonType": "string",
"keyId": key2_id,
}
]
},
)];
let client = Client::encrypted_builder(
ClientOptions::parse(URI).await?,
key_vault_namespace,
kms_providers,
)?
.encrypted_fields_map(encrypted_fields_map)
.build()
.await?;
let db = client.database("example");
let coll = db.collection::<Document>("encryptedCollection");
coll.drop(None).await?;
db.create_collection("encryptedCollection", None).await?;
coll.insert_one(
doc! { "_id": 1, "firstName": "Jane", "lastName": "Doe" },
None,
)
.await?;
let docs: Vec<_> = coll
.find(doc! {"firstName": "Jane"}, None)
.await?
.try_collect()
.await?;
println!("{:?}", docs);
Ok(())
}</code></pre></pre>
<h3 id="explicit-queryable-encryption"><a class="header" href="#explicit-queryable-encryption">Explicit Queryable Encryption</a></h3>
<p>Verison 2.4.0 of the <code>mongodb</code> crate brings support for Queryable Encryption with MongoDB >=6.0.</p>
<p>Queryable Encryption is the second version of Client-Side Field Level Encryption. Data is encrypted client-side. Queryable Encryption supports indexed encrypted fields, which are further processed server-side.</p>
<p>Explicit encryption in Queryable Encryption is performed using the <code>encrypt</code> and <code>decrypt</code> methods. Automatic encryption (to allow the <code>find_one</code> to automatically decrypt) is configured using an <code>encrypted_fields</code> mapping, as demonstrated by the following example:</p>
<!--- Changes to this example should also be made to manual/deps/src/example/explicit_queryable_encryption.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use mongodb::{
bson::{self, doc, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::{KmsProvider, Algorithm},
options::{ClientOptions, CreateCollectionOptions},
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
// This must be the same master key that was used to create
// the encryption key.
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
// The MongoDB namespace (db.collection) used to store
// the encryption data keys.
let key_vault_namespace = Namespace::new("keyvault", "datakeys");
// Set up the key vault (key_vault_namespace) for this example.
let client = Client::with_uri_str(URI).await?;
let key_vault = client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
// The MongoClient to use for reading/writing to the key vault.
// This can be the same MongoClient used by the main application.
client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
// Create a new data key for the encryptedField.
let indexed_key_id = client_encryption
.create_data_key(MasterKey::Local)
.run()
.await?;
let unindexed_key_id = client_encryption
.create_data_key(MasterKey::Local)
.run()
.await?;
let encrypted_fields = doc! {
"escCollection": "enxcol_.default.esc",
"eccCollection": "enxcol_.default.ecc",
"ecocCollection": "enxcol_.default.ecoc",
"fields": [
{
"keyId": indexed_key_id.clone(),
"path": "encryptedIndexed",
"bsonType": "string",
"queries": {
"queryType": "equality"
}
},
{
"keyId": unindexed_key_id.clone(),
"path": "encryptedUnindexed",
"bsonType": "string",
}
]
};
// The MongoClient used to read/write application data.
let encrypted_client = Client::encrypted_builder(
ClientOptions::parse(URI).await?,
key_vault_namespace,
kms_providers,
)?
.bypass_query_analysis(true)
.build()
.await?;
let db = encrypted_client.database("test");
db.drop(None).await?;
// Create the collection with encrypted fields.
db.create_collection(
"coll",
CreateCollectionOptions::builder()
.encrypted_fields(encrypted_fields)
.build(),
)
.await?;
let coll = db.collection::<Document>("coll");
// Create and encrypt an indexed and unindexed value.
let val = "encrypted indexed value";
let unindexed_val = "encrypted unindexed value";
let insert_payload_indexed = client_encryption
.encrypt(val, indexed_key_id.clone(), Algorithm::Indexed)
.contention_factor(1)
.run()
.await?;
let insert_payload_unindexed = client_encryption
.encrypt(unindexed_val, unindexed_key_id, Algorithm::Unindexed)
.run()
.await?;
// Insert the payloads.
coll.insert_one(
doc! {
"encryptedIndexed": insert_payload_indexed,
"encryptedUnindexed": insert_payload_unindexed,
},
None,
)
.await?;
// Encrypt our find payload using QueryType.EQUALITY.
// The value of `data_key_id` must be the same as used to encrypt the values
// above.
let find_payload = client_encryption
.encrypt(val, indexed_key_id, Algorithm::Indexed)
.query_type("equality")
.contention_factor(1)
.run()
.await?;
// Find the document we inserted using the encrypted payload.
// The returned document is automatically decrypted.
let doc = coll
.find_one(doc! { "encryptedIndexed": find_payload }, None)
.await?;
println!("Returned document: {:?}", doc);
Ok(())
}</code></pre></pre>
<h2 id="explicit-encryption"><a class="header" href="#explicit-encryption">Explicit Encryption</a></h2>
<p>Explicit encryption is a MongoDB community feature and does not use the mongocryptd process. Explicit encryption is provided by the <code>ClientEncryption</code> struct, for example:</p>
<!--- Changes to this example should also be made to manual/deps/src/example/explicit_encryption.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use mongodb::{
bson::{self, doc, Bson, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::{Algorithm, KmsProvider},
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
// This must be the same master key that was used to create
// the encryption key.
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
// The MongoDB namespace (db.collection) used to store
// the encryption data keys.
let key_vault_namespace = Namespace::new("keyvault", "datakeys");
// The MongoClient used to read/write application data.
let client = Client::with_uri_str(URI).await?;
let coll = client.database("test").collection::<Document>("coll");
// Clear old data
coll.drop(None).await?;
// Set up the key vault (key_vault_namespace) for this example.
let key_vault = client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
// The MongoClient to use for reading/writing to the key vault.
// This can be the same MongoClient used by the main application.
client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
// Create a new data key for the encryptedField.
let data_key_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["encryption_example_3".to_string()])
.run()
.await?;
// Explicitly encrypt a field:
let encrypted_field = client_encryption
.encrypt(
"123456789",
data_key_id,
Algorithm::AeadAes256CbcHmacSha512Deterministic,
)
.run()
.await?;
coll.insert_one(doc! { "encryptedField": encrypted_field }, None)
.await?;
let mut doc = coll.find_one(None, None).await?.unwrap();
println!("Encrypted document: {:?}", doc);
// Explicitly decrypt the field:
let field = match doc.get("encryptedField") {
Some(Bson::Binary(bin)) => bin,
_ => panic!("invalid field"),
};
let decrypted: Bson = client_encryption
.decrypt(field.as_raw_binary())
.await?
.try_into()?;
doc.insert("encryptedField", decrypted);
println!("Decrypted document: {:?}", doc);
Ok(())
}</code></pre></pre>
<h2 id="explicit-encryption-with-automatic-decryption"><a class="header" href="#explicit-encryption-with-automatic-decryption">Explicit Encryption with Automatic Decryption</a></h2>
<p>Although automatic encryption requires MongoDB 4.2+ enterprise or a MongoDB 4.2+ Atlas cluster, automatic decryption is supported for all users. To configure automatic decryption without automatic encryption set <code>bypass_auto_encryption</code> to <code>true</code> in the <code>EncryptedClientBuilder</code>:</p>
<!--- Changes to this example should also be made to manual/deps/src/example/explicit_encryption_auto_decryption.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use mongodb::{
bson::{self, doc, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::{Algorithm, KmsProvider},
options::ClientOptions,
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
// This must be the same master key that was used to create
// the encryption key.
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
// The MongoDB namespace (db.collection) used to store
// the encryption data keys.
let key_vault_namespace = Namespace::new("keyvault", "datakeys");
// `bypass_auto_encryption(true)` disables automatic encryption but keeps
// the automatic _decryption_ behavior. bypass_auto_encryption will
// also disable spawning mongocryptd.
let client = Client::encrypted_builder(
ClientOptions::parse(URI).await?,
key_vault_namespace.clone(),
kms_providers.clone(),
)?
.bypass_auto_encryption(true)
.build()
.await?;
let coll = client.database("test").collection::<Document>("coll");
// Clear old data
coll.drop(None).await?;
// Set up the key vault (key_vault_namespace) for this example.
let key_vault = client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
// The MongoClient to use for reading/writing to the key vault.
// This can be the same MongoClient used by the main application.
client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
// Create a new data key for the encryptedField.
let data_key_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["encryption_example_4".to_string()])
.run()
.await?;
// Explicitly encrypt a field:
let encrypted_field = client_encryption
.encrypt(
"123456789",
data_key_id,
Algorithm::AeadAes256CbcHmacSha512Deterministic,
)
.run()
.await?;
coll.insert_one(doc! { "encryptedField": encrypted_field }, None)
.await?;
// Automatically decrypts any encrypted fields.
let doc = coll.find_one(None, None).await?.unwrap();
println!("Decrypted document: {:?}", doc);
let unencrypted_coll = Client::with_uri_str(URI)
.await?
.database("test")
.collection::<Document>("coll");
println!(
"Encrypted document: {:?}",
unencrypted_coll.find_one(None, None).await?
);
Ok(())
}</code></pre></pre>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="web_framework_examples.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="web_framework_examples.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
</nav>
</div>
<!-- Livereload script (if served using the cli tool) -->
<script>
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsAddress = wsProtocol + "//" + location.host + "/" + "__livereload";
const socket = new WebSocket(wsAddress);
socket.onmessage = function (event) {
if (event.data === "reload") {
socket.close();
location.reload();
}
};
window.onbeforeunload = function() {
socket.close();
}
</script>
<script>
window.playground_copyable = true;
</script>
<script src="elasticlunr.min.js"></script>
<script src="mark.min.js"></script>
<script src="searcher.js"></script>
<script src="clipboard.min.js"></script>
<script src="highlight.js"></script>
<script src="book.js"></script>
<!-- Custom JS scripts -->
</div>
</body>
</html>