diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..a7d0fc7b7 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "esbonio.sphinx.confDir": "" +} \ No newline at end of file diff --git a/source/driver-compatibility-reference.txt b/source/driver-compatibility-reference.txt deleted file mode 100644 index 5c61b2a26..000000000 --- a/source/driver-compatibility-reference.txt +++ /dev/null @@ -1,19 +0,0 @@ -:orphan: - -==================== -Driver Compatibility -==================== - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: twocols - -.. note:: Check the driver documentation pages for compatibility information - - Please check our `driver documentation page home `__ - for the latest information on driver compatibility with MongoDB and driver - languages. diff --git a/source/figures/CSFLE_Data_Key_KMIP.png b/source/figures/CSFLE_Data_Key_KMIP.png deleted file mode 100644 index 7ecf2af52..000000000 Binary files a/source/figures/CSFLE_Data_Key_KMIP.png and /dev/null differ diff --git a/source/figures/CSFLE_Data_Key_KMS.png b/source/figures/CSFLE_Data_Key_KMS.png deleted file mode 100644 index d9c102a91..000000000 Binary files a/source/figures/CSFLE_Data_Key_KMS.png and /dev/null differ diff --git a/source/figures/CSFLE_Data_Key_Local.png b/source/figures/CSFLE_Data_Key_Local.png deleted file mode 100644 index 4e2cf3f69..000000000 Binary files a/source/figures/CSFLE_Data_Key_Local.png and /dev/null differ diff --git a/source/figures/CSFLE_Master_Key_KMS.png b/source/figures/CSFLE_Master_Key_KMS.png deleted file mode 100644 index 152a0cb98..000000000 Binary files a/source/figures/CSFLE_Master_Key_KMS.png and /dev/null differ diff --git a/source/figures/CSFLE_Master_Key_Local.png b/source/figures/CSFLE_Master_Key_Local.png deleted file mode 100644 index d3697602a..000000000 Binary files a/source/figures/CSFLE_Master_Key_Local.png and /dev/null differ diff --git a/source/figures/CSFLE_Read_Encrypted_Data.png b/source/figures/CSFLE_Read_Encrypted_Data.png deleted file mode 100644 index 417f8e4c1..000000000 Binary files a/source/figures/CSFLE_Read_Encrypted_Data.png and /dev/null differ diff --git a/source/figures/CSFLE_Security_Feature_Chart.png b/source/figures/CSFLE_Security_Feature_Chart.png deleted file mode 100644 index 7d16671dd..000000000 Binary files a/source/figures/CSFLE_Security_Feature_Chart.png and /dev/null differ diff --git a/source/figures/CSFLE_Write_Encrypted_Data.png b/source/figures/CSFLE_Write_Encrypted_Data.png deleted file mode 100644 index 276042767..000000000 Binary files a/source/figures/CSFLE_Write_Encrypted_Data.png and /dev/null differ diff --git a/source/includes/fact-authenticate-with-java-gssapi.rst b/source/includes/fact-authenticate-with-java-gssapi.rst deleted file mode 100644 index 57826fc9b..000000000 --- a/source/includes/fact-authenticate-with-java-gssapi.rst +++ /dev/null @@ -1,55 +0,0 @@ -GSSAPI (Kerberos) Authentication -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. important:: - - The Java driver maintainers have only confirmed the content of this - document on Linux using Java 6 and Java 7, on OS X using Java 7, - and on Windows with SSPI using Java 7. - - These features are only present in `MongoDB Enterprise - `_. - -To authenticate to a MongoDB cluster using Kerberos, you must supply -the Kerberos user name and specify the Kerberos authentication -mechanism: - -.. code-block:: java - - MongoCredential credential = MongoCredential.createGSSAPICredential("user1@MYREALM.ME"); - - MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(credential)); - -With Kerberos you specify neither the password nor the database name, -as authentication is performed via the Kerberos key distribution -center (KDC). - -To actually run a program that authenticates with Kerberos, you will -typically need to specify several system properties so that the -underlying GSSAPI Java libraries can acquire a Kerberos ticket: - -.. code-block:: properties - - java.security.krb5.realm=MYREALM.ME - java.security.krb5.kdc=mykdc.myrealm.me - -.. note:: - - Many authentication problems with GSSAPI/Kerberos occur due to - mismatches between server realm names. In general, you should - specify exactly the same hostname as used as the realm name in your - Kerberos configuration when creating GSSAPI credentials. - - You can force canonicalization of the hostname provided to the - driver by adding a mechanism property to the GSSAPI - ``MongoCredential``, which can be useful if your realm is a - fully-qualified domain name and you are using an IP address or - alias: - - .. code-block:: java - - MongoCredential credential = MongoCredential.createGSSAPICredential("user1@MYREALM.ME").withMechanismProperty("CANONICALIZE_HOST_NAME",true); - - You should note, however, that if your deployment is not using - secured DNS lookups, it is possible for an attacker to pose as the - Kerberos principal you are attempting to communicate with. diff --git a/source/includes/fact-authenticate-with-java-x509.rst b/source/includes/fact-authenticate-with-java-x509.rst deleted file mode 100644 index a07768c07..000000000 --- a/source/includes/fact-authenticate-with-java-x509.rst +++ /dev/null @@ -1,15 +0,0 @@ -MONGODB-X509 Authentication -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The MONGODB-X509 mechanism authenticates a user whose name is derived -from the distinguished subject name of the X.509 certificate presented -by the driver during SSL negotiation. - -This authentication method requires the use of SSL connections with -certificate validation and is available in MongoDB 2.6 and newer: - -.. code-block:: java - - MongoCredential credential = MongoCredential.createMongoX509Credential(""); - - MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(credential), MongoClientOptions.builder().sslEnabled(true).build()); diff --git a/source/includes/fact-authenticate-with-java.rst b/source/includes/fact-authenticate-with-java.rst deleted file mode 100644 index 6a11b07e5..000000000 --- a/source/includes/fact-authenticate-with-java.rst +++ /dev/null @@ -1,23 +0,0 @@ -Authentication -~~~~~~~~~~~~~~ - -MongoDB can be run in a secure mode where access to databases is -controlled via authentication. When run in this mode, any client application -must provide a list of credentials which will be used to authenticate against. -In the Java driver, you simply provide the credentials when creating a -``MongoClient`` instance: - -.. code-block:: java - - MongoCredential credential = MongoCredential.createCredential(userName, database, password); - MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential)); - -or in the connection string: - -.. code-block:: java - - MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://user:pwd@localhost")); - -MongoDB supports various different authentication mechanisms. See the `access control tutorials`_ for more information. - -.. _`access control tutorials`: http://docs.mongodb.com/manual/administration/security-access-control diff --git a/source/includes/iam-user-policy-minimum.json b/source/includes/iam-user-policy-minimum.json deleted file mode 100644 index 40414a492..000000000 --- a/source/includes/iam-user-policy-minimum.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": ["kms:Decrypt", "kms:Encrypt"], - "Resource": "" - } - ] -} diff --git a/source/includes/key-policy-default.json b/source/includes/key-policy-default.json deleted file mode 100644 index 6fed9e727..000000000 --- a/source/includes/key-policy-default.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "Enable IAM User Permissions", - "Effect": "Allow", - "Principal": { - "AWS": "" - }, - "Action": "kms:*", - "Resource": "*" - } - ] -} diff --git a/source/includes/steps-fle-configure-the-mongodb-client.yaml b/source/includes/steps-fle-configure-the-mongodb-client.yaml deleted file mode 100644 index 0756a99c0..000000000 --- a/source/includes/steps-fle-configure-the-mongodb-client.yaml +++ /dev/null @@ -1,374 +0,0 @@ -title: Specify the Key Vault Collection Namespace -ref: specify-the-key-vault-collection-namespace -content: | - The key vault collection contains the data key that the client uses to - encrypt and decrypt fields. MedcoMD uses the collection - ``encryption.__keyVault`` as the key vault in the following - **code snippet**. - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: java - - String keyVaultNamespace = "encryption.__keyVault"; - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - - const keyVaultNamespace = 'encryption.__keyVault'; - .. tab:: - :tabid: python - - .. code-block:: python - - key_vault_namespace = "encryption.__keyVault" - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - var keyVaultNamespace = CollectionNamespace.FromFullName("encryption.__keyVault"); - .. tab:: - :tabid: go - - .. code-block:: go - - keyVaultNamespace := "encryption.__keyVault" - ---- -title: Specify the Local Master Encryption Key -ref: specify-the-local-master-encryption-key -content: | - The client expects a key management system to store and provide the - application's master encryption key. For now, MedcoMD only has a local - master key, so they use the ``local`` KMS provider and specify the key - inline with the following **code snippet**. - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: java - :emphasize-lines: 2,5 - - Map keyMap = new HashMap(); - keyMap.put("key", localMasterKey); - - Map> kmsProviders = new HashMap>(); - kmsProviders.put("local", keyMap); - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - :emphasize-lines: 2,3 - - const kmsProviders = { - local: { - key: localMasterKey, - } - } - .. tab:: - :tabid: python - - .. code-block:: python - :emphasize-lines: 2,3 - - kms_providers = { - "local": { - "key": local_master_key - } - } - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - var kmsProviders = new Dictionary>(); - var localMasterKeyBase64 = File.ReadAllText(__localMasterKeyPath); - var localMasterKeyBytes = Convert.FromBase64String(localMasterKeyBase64); - var localOptions = new Dictionary - { - { "key", localMasterKeyBytes } - }; - kmsProviders.Add("local", localOptions); - .. tab:: - :tabid: go - - .. code-block:: go - - localMasterKey := getMasterKey() - kmsProviders := map[string]map[string]interface{ - "local": - "key": localMasterKey - } - - .. note:: - - In the companion project, the KMS provider information is represented by a struct. - - ---- -title: Map the JSON Schema to the Patients Collection -ref: map-the-json-schema-to-the-patients-collection -content: | - The MedcoMD engineers assign their schema to a variable. The JSON Schema - that MedcoMD defined doesn't explicitly specify the collection to which it - applies. To assign the schema, they map it to the ``medicalRecords.patients`` - collection namespace in the following **code snippet**: - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: java - :emphasize-lines: 2 - - HashMap schemaMap = new HashMap(); - schemaMap.put("medicalRecords.patients", BsonDocument.parse(jsonSchema)); - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - :emphasize-lines: 2 - - const patientSchema = { - 'medicalRecords.patients': jsonSchema, - } - .. tab:: - :tabid: python - - .. code-block:: python - :emphasize-lines: 2 - - patient_schema = { - "medicalRecords.patients": json_schema - } - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - // JsonSchemaCreator is a utility class found in the C# companion - // project to this guide - var schema = JsonSchemaCreator.CreateJsonSchema(keyIdBase64); - - .. tab:: - :tabid: go - - .. code-block:: go - - // schema.CreateJSONSchema(dataKeyBase64) is a helper funciton found in the - // Go companion project to this guide - schema := schema.CreateJSONSchema(dataKeyBase64) - schemaMap := map[string]interface{}{ - "medicalRecords.patients": schema, - } ---- -title: Specify the Location of the Encryption Binary -ref: specify-the-location-of-the-encryption-binary -content: | - MongoDB drivers communicate with the ``mongocryptd`` encryption binary to - perform automatic client-side field level encryption. The ``mongocryptd`` - process performs the following: - - - Validates the encryption instructions defined in the JSON Schema - and flags the referenced fields for encryption in read and write - operations. - - Prevents unsupported operations from being executed on encrypted fields. - - Configure the client to spawn the ``mongocryptd`` process by specifying the - path to the binary using the following configuration options: - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: java - :emphasize-lines: 2 - - Map extraOptions = new HashMap(); - extraOptions.put("mongocryptdSpawnPath", "/usr/local/bin/mongocryptd"); - - .. note:: Encryption Binary Daemon - - If the ``mongocryptd`` daemon is already running, you can - configure the client to skip starting it by passing the - following option: - - .. code-block:: java - :emphasize-lines: 1 - - extraOptions.put("mongocryptdBypassSpawn", true); - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - :emphasize-lines: 2 - - const extraOptions = { - mongocryptdSpawnPath: '/usr/local/bin/mongocryptd', - } - - .. note:: Encryption Binary Daemon - - If the ``mongocryptd`` daemon is already running, you can - configure the client to skip starting it by passing the - following option: - - .. code-block:: javascript - :emphasize-lines: 1 - - extraOptions.mongocryptdBypassSpawn = true; - .. tab:: - :tabid: python - - .. code-block:: python - :emphasize-lines: 2 - - extra_options = { - 'mongocryptd_spawn_path': '/usr/local/bin/mongocryptd' - } - - .. note:: Encryption Binary Daemon - - If the ``mongocryptd`` daemon is already running, you can - configure the client to skip starting it by passing the - following option: - - .. code-block:: python - :emphasize-lines: 1 - - extra_options['mongocryptd_bypass_spawn'] = True - .. tab:: - :tabid: csharp - - - .. note:: Encryption Executable - - Specify the spawn path if the ``mongocryptd.exe`` - executable is not in the PATH. - - .. code-block:: csharp - - var extraOptions = new Dictionary() - { - { "mongocryptdSpawnPath", $@"{MongoBinariesPath}\mongocryptd.exe" }, - }; - - .. tab:: - :tabid: go - - .. note:: - - It is only necessary to specify the spawn path if ``mongocryptd`` is not - present in the system path. - - .. code-block:: go - - extraOptions := map[string]interface{}{ - "mongocryptdSpawnPath": "/usr/local/bin/mongocryptd", - } - - .. note:: Encryption Binary Daemon - - If the ``mongocryptd`` daemon is already running, you can - configure the client to skip starting it by passing the - following option: - - .. code-block:: go - - extraOptions := map[string]interface{}{ - "mongocryptdBypassSpawn": true, - } - ---- -title: Create the MongoClient -ref: create-the-mongoclient -content: | - To create the CSFLE-enabled client, MedcoMD instantiates a standard - MongoDB client object with the additional automatic encryption - settings with the following **code snippet**: - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: java - :emphasize-lines: 3-8 - - MongoClientSettings clientSettings = MongoClientSettings.builder() - .applyConnectionString(new ConnectionString("mongodb://localhost:27017")) - .autoEncryptionSettings(AutoEncryptionSettings.builder() - .keyVaultNamespace(keyVaultNamespace) - .kmsProviders(kmsProviders) - .schemaMap(schemaMap) - .extraOptions(extraOptions) - .build()) - .build(); - - MongoClient mongoClient = MongoClients.create(clientSettings); - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - :emphasize-lines: 5-9 - - const secureClient = new MongoClient(connectionString, { - useNewUrlParser: true, - useUnifiedTopology: true, - monitorCommands: true, - autoEncryption: { - keyVaultNamespace, - kmsProviders, - schemaMap: patientSchema, - extraOptions: extraOptions, - } - }); - .. tab:: - :tabid: python - - .. code-block:: python - :emphasize-lines: 2-5 - - fle_opts = AutoEncryptionOpts( - kms_providers, - key_vault_namespace, - schema_map=patient_schema, - **extra_options - ) - client = MongoClient(connection_string, auto_encryption_opts=fle_opts) - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - var clientSettings = MongoClientSettings.FromConnectionString(_connectionString); - var autoEncryptionOptions = new AutoEncryptionOptions( - keyVaultNamespace: keyVaultNamespace, - kmsProviders: kmsProviders, - schemaMap: schemaMap, - extraOptions: extraOptions); - clientSettings.AutoEncryptionOptions = autoEncryptionOptions; - var client = new MongoClient(clientSettings); - - .. tab:: - :tabid: go - - .. code-block:: go - - autoEncryptionOpts := options.AutoEncryption(). - SetKmsProviders(provider.Credentials()). - SetKeyVaultNamespace(keyVaultNamespace). - SetSchemaMap(schemaMap). - SetExtraOptions(extraOptions) - client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri).SetAutoEncryptionOptions(autoEncryptionOpts)) diff --git a/source/includes/steps-fle-convert-to-a-remote-master-key-aws.yaml b/source/includes/steps-fle-convert-to-a-remote-master-key-aws.yaml deleted file mode 100644 index 3766b318e..000000000 --- a/source/includes/steps-fle-convert-to-a-remote-master-key-aws.yaml +++ /dev/null @@ -1,434 +0,0 @@ -title: Create an AWS IAM User -ref: create-an-aws-iam-user -content: | - 1. 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 CSFLE-enable application. - Your application authenticates with AWS KMS using the IAM user to - encrypt and decrypt the remote master key. Take note of the following - IAM credentials needed to authenticate with the KMS: - - - **access key ID** - - **secret access key** - - 2. 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. We recommend that you follow the - `principle of least privilege `__ - to keep your data secure. - - The following inline policy allows an IAM user to encrypt and decrypt - with the remote master key with the least privileges possible: - - .. literalinclude:: /includes/iam-user-policy-minimum.json - :language: json - - To add this policy, follow the - `Adding IAM identity permissions `__ - guide in the AWS documentation. - - .. note:: Remote Master Key Amazon Resource Name (ARN) - - The preceding policy requires the ARN of the key you generate in the - :ref:`Create the Master Key ` step of this guide. - - .. important:: Authenticate with IAM Roles in Production - - When deploying your CSFLE-enabled application to a production environment, - authenticate your application through an IAM role instead of an IAM user. - - To authenticate with an IAM role, specify your temporary IAM role credentials - in your KMS provider object as follows: - - .. code-block:: json - - { - "accessKeyId":"", - "secretAccessKey":"", - "sessionToken":"" - } - - You can get your temporary IAM role credentials through the following mechanisms: - - - `Call AssumeRole `__ - - `Retrieve Credentials from EC2 Instance Metadata `__ - - Your application must include logic to get new temporary credentials - and recreate your CSFLE-enabled ``MongoClient`` instance when each set of - temporary credentials expires. - - To learn more about IAM roles, see the following pages in the official AWS - documentation: - - - `IAM roles `__ - - `When to create an IAM role (instead of a user) `__ - - To learn how to get temporary credentials and assume a role in each of - the languages supported in this guide, see the following ``AssumeRole`` - runnable examples in the AWS documentation: - - - `Java `__ - - `NodeJS `__ - - `Python `__ - (example uses multi-factor authentication) - - `C# `__ - - `Go `__ - ---- -title: Create the Master Key -ref: create-the-master-key -content: | - The following diagram shows the steps required to create a new - **master key** on a KMS provider. - - .. image:: /figures/CSFLE_Master_Key_KMS.png - :alt: Diagram that describes creating a master key when using a KMS provider - - .. _aws-create-master-key: - - 1. To create a master key, log into your AWS management console and create - a new symmetric master key in the KMS section. Choose a name and - description that helps you identify it; these fields do not affect the - functionality or configuration. - - 2. In the :guilabel:`Usage Permissions` step of the key generation - process, use the following default key policy to enable IAM policies - to allow access to your remote master key: - - .. literalinclude:: /includes/key-policy-default.json - :language: json - - To learn more about key policies, see - `Key Policies in AWS KMS `__ - in the official AWS documentation. - ---- -title: Specify the AWS KMS Provider Credentials -ref: specify-the-aws-kms-provider-credentials -content: | - Unlike the local key provider, the AWS KMS provider does not read - the master key directly from the client application. Instead, - it accepts the :guilabel:`Access Key ID` and :guilabel:`Secret Access - Key` configurations that point to the master key. The IAM user must have - the permissions set up in the previous step in order for the client to - use the KMS to encrypt and decrypt data encryption keys. Follow the steps - below to specify your credentials: - - 1. First, identify the following authentication credentials on AWS KMS: - - .. list-table:: - :header-rows: 1 - :stub-columns: 1 - :widths: 25 15 15 45 - - * - Field - - Required for IAM User - - Required for IAM Role - - Description - - * - Access Key ID - - Yes - - Yes - - Identifies the account user. - - * - Secret Access Key - - Yes - - Yes - - Contains the authentication credentials of the account user. - - * - Session Token - - No - - Yes - - Contains a token obtained from AWS Security Token Service (STS). - - - 2. Next, add your authentication credentials to your CSFLE-enabled client - code: - - .. include:: /includes/substitute-placeholders-aws.rst - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: java - - BsonString awsAccessKeyId = new BsonString(""); - BsonString awsSecretAccessKey = new BsonString(""); - Map> kmsProviders = new HashMap>(); - Map providerDetails = new HashMap(); - - providerDetails.put("accessKeyId", awsAccessKeyId); - providerDetails.put("secretAccessKey", awsSecretAccessKey); - - kmsProviders.put("aws", providerDetails); - - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - - kmsProviders = { - aws: { - accessKeyId: "", - secretAccessKey: "", - }, - } - - .. tab:: - :tabid: python - - .. code-block:: python - - kms_providers = { - "aws": { - "accessKeyId": "", - "secretAccessKey": "" - } - } - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - var kmsProviders = new Dictionary>(); - - var awsAccessKey = Environment.GetEnvironmentVariable("FLE_AWS_ACCESS_KEY"); - var awsSecretAccessKey = Environment.GetEnvironmentVariable("FLE_AWS_SECRET_ACCESS_KEY"); - var awsKmsOptions = new Dictionary - { - { "accessKeyId", awsAccessKey }, - { "secretAccessKey", awsSecretAccessKey } - }; - kmsProviders.Add("aws", awsKmsOptions); - - .. note:: - - To use the AWS Key Vault, you must use - `libmongocrypt `__ version 1.0 or later in your application's environment. - - .. tab:: - :tabid: go - - In ``kms/provider.go``, update the variable declarations or define the expected environmental variables in - ``AWSProvider()``. - - .. code-block:: go - - awsAccessKeyID := GetCheckedEnv("FLE_AWS_ACCESS_KEY") - awsSecretAccessKey := GetCheckedEnv("FLE_AWS_SECRET_ACCESS_KEY") - - The expected KMS provider map is created with struct tags. - - .. code-block:: go - - func (a *AWS) Credentials() map[string]map[string]interface{} { - return map[string]map[string]interface{}{"aws": structs.Map(a.credentials)} - } - ---- -title: Create a New Data Encryption Key -ref: create-a-new-data-key -content: | - To encrypt your data, you need a data encryption key generated from your - KMS-hosted **master key**. The following diagram shows the requests you need - to make from the client application to create and store a new **data - encryption key**: - - .. image:: /figures/CSFLE_Data_Key_KMS.png - :alt: Diagram that describes creating a data encryption key when using a KMS provider - - 1. First, specify the following information to access the master key: - - .. list-table:: - :header-rows: 1 - :stub-columns: 1 - :widths: 30 15 45 - - * - Field - - Required - - Description - - * - key - - Yes - - `Amazon Resource Number (ARN) `__ - of the master key. - - * - region - - No - - AWS region of your master key, e.g. "us-west-2"; required only if not specified in your ARN. - - * - endpoint - - No - - Custom hostname for the AWS endpoint if configured for your account. - - 2. Once you have the required information, update and run the following code - to generate the new data encryption key: - - .. include:: /includes/substitute-placeholders-aws-key.rst - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: Java - - ClientEncryption clientEncryption = ClientEncryptions.create(ClientEncryptionSettings.builder() - .keyVaultMongoClientSettings(MongoClientSettings.builder() - .applyConnectionString(new ConnectionString("mongodb://localhost:27017")) - .build()) - .keyVaultNamespace(keyVaultNamespace) - .kmsProviders(kmsProviders) - .build()); - - BsonString masterKeyArn = new BsonString(""); // e.g. "arn:aws:kms:us-east-2:111122223333:alias/test-key" - BsonString masterKeyRegion = new BsonString("") - DataKeyOptions dataKeyOptions = new DataKeyOptions().masterKey( - new BsonDocument() - .append("key", masterKeyArn)); - .append("region", masterKeyRegion) - - BsonBinary dataKeyId = clientEncryption.createDataKey("aws", dataKeyOptions); - String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeyId.getData()); - - System.out.println("DataKeyId [base64]: " + base64DataKeyId); - - .. note:: - - To use AWS KMS, you must use `mongodb-crypt `__ - version 1.0 or later in your application's environment. - - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - - const encryption = new ClientEncryption(client, { - keyVaultNamespace, - kmsProviders, - }); - const key = await encryption.createDataKey("aws", { - masterKey: { - key: "", // e.g. "arn:aws:kms:us-east-2:111122223333:alias/test-key" - region: "", // e.g. "us-east-2" - }, - }); - - const base64DataKeyId = key.toString("base64"); - console.log("DataKeyId [base64]: ", base64DataKeyId); - - .. tab:: - :tabid: python - - .. code-block:: python - - import pymongo - from pymongo import MongoClient - from pymongo.encryption_options import AutoEncryptionOpts - from bson.binary import STANDARD - from bson.codec_options import CodecOptions - - connection_string = "mongodb://localhost:27017" - key_vault_namespace = "encryption.__keyVault" - - fle_opts = AutoEncryptionOpts( - kms_providers, # pass in the kms_providers from the previous step - key_vault_namespace - ) - - client = MongoClient(connection_string) - client_encryption = pymongo.encryption.ClientEncryption( - { - "aws": { - "accessKeyId": "", - "secretAccessKey": "" - } - }, - key_vault_namespace, - client, - CodecOptions(uuid_representation=STANDARD) - ) - data_key_id = client_encryption.create_data_key("aws", {"region": "","key": ""}) - - .. note:: - - To use AWS KMS, you must use `pymongocrypt `__ - version 1.0 or later in your application's environment. - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - var keyVaultClient = new MongoClient(connectionString); - var clientEncryptionOptions = new ClientEncryptionOptions( - keyVaultClient: keyVaultClient, - keyVaultNamespace: keyVaultNamespace, - kmsProviders: kmsProviders); - - var clientEncryption = new ClientEncryption(clientEncryptionOptions); - var awsKeyARN = Environment.GetEnvironmentVariable("FLE_AWS_KEY_ARN"); // e.g. "arn:aws:kms:us-east-2:111122223333:alias/test-key" - var awsKeyRegion = Environment.GetEnvironmentVariable("FLE_AWS_KEY_REGION"); - var awsEndpoint = Environment.GetEnvironmentVariable("FLE_AWS_ENDPOINT"); // Optional, AWS KMS URL. - var dataKeyOptions = new DataKeyOptions( - masterKey: new BsonDocument - { - { "region", awsKeyRegion }, - { "key", awsKeyARN }, - { "endpoint", () => awsEndpoint, awsEndpoint != null } - }); - - var dataKeyId = clientEncryption.CreateDataKey("aws", dataKeyOptions, CancellationToken.None); - Console.WriteLine($"AWS DataKeyId [UUID]: {dataKeyId}"); - var dataKeyIdBase64 = Convert.ToBase64String(GuidConverter.ToBytes(dataKeyId, GuidRepresentation.Standard)); - Console.WriteLine($"AWS DataKeyId [base64]: {dataKeyIdBase64}"); - - .. note:: - - To use the AWS Key Vault, you must use - `libmongocrypt `__ version 1.0 or later in your application's environment. - - .. tab:: - :tabid: go - - In ``kms/provider.go``, update the variable declarations or define the expected environmental variables - in ``AWSProvider()``. - - .. code-block:: go - - awsKeyARN := GetCheckedEnv("FLE_AWS_KEY_ARN") - awsKeyRegion := GetCheckedEnv("FLE_AWS_KEY_REGION") - - Struct tags are used to pass these values directly to the driver for use. In ``kms/provider.go`` - - .. code-block:: go - - func (a *AWS) DataKeyOpts() interface{} { - return a.dataKeyOpts - } - - In ``csfle/data_key.go`` - - .. code-block:: go - - dataKeyOpts := options.DataKey().SetMasterKey(provider.DataKeyOpts()) - dataKeyID, err := clientEnc.CreateDataKey(context.TODO(), provider.Name(), dataKeyOpts) - ---- -title: Update the Automatic Encryption JSON Schema -ref: update-the-json-schema -content: | - If you previously embedded the key ID of your data encryption key in your - automatic encryption rules, update the :ref:`JSON Schema ` - with your new data encryption key ID. - - Your client application is now ready to automatically encrypt your data - using the master key on your KMS provider. diff --git a/source/includes/steps-fle-convert-to-a-remote-master-key-azure.yaml b/source/includes/steps-fle-convert-to-a-remote-master-key-azure.yaml deleted file mode 100644 index 61054533b..000000000 --- a/source/includes/steps-fle-convert-to-a-remote-master-key-azure.yaml +++ /dev/null @@ -1,367 +0,0 @@ -title: Register an Azure Application -ref: create-an-azure-user -content: | - 1. Register a new application in Azure Active directory if you do not already - have one for this CSFLE-enabled client. See the Azure documentation on - `Applications and service principals `__ - for more information. - - 2. Once you register the application, take note of the following credentials - needed to authenticate with the Key Vault: - - - **tenant id** - - **client id** - - **client secret** - ---- -title: Create the Master Key -ref: create-the-master-key -content: | - The following diagram shows the steps required to create a new - **master key** on a KMS provider. - - .. image:: /figures/CSFLE_Master_Key_KMS.png - :alt: Diagram that describes creating a master key when using a KMS provider - - 1. To create a master key, follow Microsoft's official - `Secrets Guide `__. - Follow the instructions in one of the :guilabel:`Quickstarts` sections - that corresponds to your preferred method to create and configure your - key. For example, the `Portal Quickstart `__ - demonstrates how to create a new vault and key. - - 2. Grant the client application ``list`` and ``read`` permissions to the - key. - - .. important:: - - The client user *should not* have administrative permissions for the - master key. We recommend that you follow the - `principle of least privilege `__ - to keep your data secure. - ---- -title: Specify the Azure Credentials -ref: specify-the-azure-credentials -content: | - Unlike the local key provider, the Azure Key Vault does not read the - master key directly from the client application. Instead, it retrieves - the key using your Azure credentials and the key vault details. - - 1. First, configure your client application with the following - authentication credentials on AWS: - - .. list-table:: - :header-rows: 1 - :stub-columns: 1 - :widths: 30 15 45 - - * - Field - - Required - - Description - - * - azure.tenantId - - Yes - - Identifies the organization of the account. - - * - azure.clientId - - Yes - - Identifies the clientId to authenticate your registered application. - - * - azure.clientSecret - - Yes - - Used to authenticate your registered application. - - * - azure.identityPlatformEndpoint - - No - - Specifies a hostname and port number for the authentication server. - Defaults to login.microsoftonline.com and is only needed for - non-commercial Azure instances such as a government or China account. - - 2. Next, update the KMS Provider configuration in your CSFLE-enabled client - creation code: - - .. include:: /includes/substitute-placeholders-azure.rst - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - In ``CSFLEHelpers.java``, update the ``kmsProviders`` map that you - pass to ``ClientEncryptionSettings.builder().kmsProviders()`` method - with your Azure authentication details: - - - .. code-block:: java - - Map providerDetails = new HashMap(); - - providerDetails.put("tenantId", new BsonString("")); - providerDetails.put("clientId", new BsonString("")); - providerDetails.put("clientSecret", new BsonString("")); - - Map> kmsProviders = new HashMap>(); - kmsProviders.put("azure", providerDetails); - - ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder() - // ... - .kmsProviders(kmsProviders) - .build(); - - .. note:: - - To use the Azure Key Vault, you must use `mongodb-crypt `__ - version 1.1 or later in your application's environment. - - - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - - kmsProviders = { - azure: { - tenantId: "", - clientId: "", - clientSecret: "", - }, - } - - .. note:: - - To use the Azure Key Vault, you must use ``mongodb-client-encryption`` version - `1.1.1 `__ or later. - - .. tab:: - :tabid: python - - In ``app.py``, define the following dictionary to pass to your call to - construct a ``ClientEncryption`` instance: - - - .. code-block:: python - - kms_providers = { - "azure": { - "tenantId": "", - "clientId": "", - "clientSecret": "" - } - } - - .. note:: - - To use the Azure Key Vault, you must use ``pymongocrypt`` version - 1.1 or later in your application's environment. Follow our guide - to `build libmongocrypt from source `__. - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - var kmsProviders = new Dictionary>(); - - var azureTenantId = Environment.GetEnvironmentVariable("FLE_AZURE_TENANT_ID"); - var azureClientId = Environment.GetEnvironmentVariable("FLE_AZURE_CLIENT_ID"); - var azureClientSecret = Environment.GetEnvironmentVariable("FLE_AZURE_CLIENT_SECRET"); - var azureIdentityPlatformEndpoint = Environment.GetEnvironmentVariable("FLE_AZURE_IDENTIFY_PLATFORM_ENPOINT"); // Optional, only needed if user is using a non-commercial Azure instance - - var azureKmsOptions = new Dictionary - { - { "tenantId", azureTenantId }, - { "clientId", azureClientId }, - { "clientSecret", azureClientSecret }, - }; - if (azureIdentityPlatformEndpoint != null) - { - azureKmsOptions.Add("identityPlatformEndpoint", azureIdentityPlatformEndpoint); - } - kmsProviders.Add("azure", azureKmsOptions);; - - .. note:: - - To use the Azure KMS, you must use - `libmongocrypt `__ version 1.1 or later in your application's environment. - - .. tab:: - :tabid: go - - In ``kms/provider.go``, update the variable declarations or define the expected environmental variables in - ``AzureProvider()``. - - .. code-block:: go - - azureTenantID := GetCheckedEnv("FLE_AZURE_TENANT_ID") - azureClientID := GetCheckedEnv("FLE_AZURE_CLIENT_ID") - azureClientSecret := GetCheckedEnv("FLE_AZURE_CLIENT_SECRET") - - The expected KMS provider map is created with struct tags. - - .. code-block:: go - - func (a *Azure) Credentials() map[string]map[string]interface{} { - return map[string]map[string]interface{}{"azure": structs.Map(a.credentials)} - } - - .. note:: - - To use the Azure KMS, you must use - `libmongocrypt `__ version 1.1 or later in your application's environment. - ---- -title: Create a New Data Encryption Key -ref: create-a-new-data-key -content: | - To encrypt your data, you need a data encryption key generated from your - KMS-hosted **master key**. The following diagram shows the requests you need - to make from the client application to create and store a new **data - encryption key**: - - .. image:: /figures/CSFLE_Data_Key_KMS.png - :alt: Diagram that describes creating a data encryption key when using a KMS provider - - 1. First, provide your client with the following information to access the - master key: - - .. list-table:: - :header-rows: 1 - :stub-columns: 1 - :widths: 30 15 45 - - * - Field - - Required - - Description - - * - keyName - - Yes - - Name of the master key - - * - keyVersion - - No - - Version of the master key - - * - keyVaultEndpoint - - Yes - - URL of the key vault. E.g. myVaultName.vault.azure.net - - 2. Once you have the required information, update and run the following code - to generate a new data encryption key: - - .. include:: /includes/substitute-placeholders-azure-key.rst - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - In ``CSFLEHelpers.java``, add your KMS provider and master key - details to your call to createDataKey() on your ``ClientEncryption`` - instance as follows: - - .. code-block:: Java - - DataKeyOptions dataKeyOptions = new DataKeyOptions().masterKey( - new BsonDocument() - .append("keyName", new BsonString("")) - .append("keyVersion", new BsonString("")) - .append("keyVersion", new BsonString(""))); - - BsonBinary dataKeyId = clientEncryption.createDataKey("azure", dataKeyOptions); - - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - - const encryption = new ClientEncryption(client, { - keyVaultNamespace, - kmsProviders, - }); - const key = await encryption.createDataKey("azure", { - masterKey: { - keyName: "", - keyVaultEndpoint: "", - }, - }); - - const base64DataKeyId = key.toString("base64"); - console.log("DataKeyId [base64]: ", base64DataKeyId); - - - .. tab:: - :tabid: python - - In ``app.py``, define the following dictionary to pass to your call to - ``create_data_key()``: - - .. code-block:: python - - master_key = { - "keyName": "", - "keyVersion": "", - "keyVaultEndpoint": "" - } - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - var keyVaultClient = new MongoClient(_connectionString); - var clientEncryptionOptions = new ClientEncryptionOptions( - keyVaultClient: keyVaultClient, - keyVaultNamespace: _keyVaultNamespace, - kmsProviders: kmsProviders); - - var clientEncryption = new ClientEncryption(clientEncryptionOptions); - var azureKeyName = Environment.GetEnvironmentVariable("FLE_AZURE_KEY_NAME"); - var azureKeyVaultEndpoint = Environment.GetEnvironmentVariable("FLE_AZURE_KEYVAULT_ENDPOINT"); // typically .vault.azure.net - var azureKeyVersion = Environment.GetEnvironmentVariable("FLE_AZURE_KEY_VERSION"); // Optional - var dataKeyOptions = new DataKeyOptions( - masterKey: new BsonDocument - { - { "keyName", azureKeyName }, - { "keyVaultEndpoint", azureKeyVaultEndpoint }, - { "keyVersion", () => azureKeyVersion, azureKeyVersion != null } - }); - - var dataKeyId = clientEncryption.CreateDataKey("azure", dataKeyOptions, CancellationToken.None); - - .. tab:: - :tabid: go - - In ``kms/provider.go``, update the variable declarations or define the expected environmental variables - in ``AzureProvider()``. - - .. code-block:: go - - azureKeyVaultEndpoint := GetCheckedEnv("FLE_AZURE_KEYVAULT_ENDPOINT") - azureKeyName := GetCheckedEnv("FLE_AZURE_KEY_NAME") - - Struct tags are used to pass these values directly to the driver for use. In ``kms/provider.go`` - - .. code-block:: go - - func (a *Azure) DataKeyOpts() interface{} { - return a.dataKeyOpts - } - - In ``csfle/data_key.go`` - - .. code-block:: go - - dataKeyOpts := options.DataKey().SetMasterKey(provider.DataKeyOpts()) - dataKeyID, err := clientEnc.CreateDataKey(context.TODO(), provider.Name(), dataKeyOpts) - ---- -title: Update the Automatic Encryption JSON Schema -ref: update-the-json-schema -content: | - If you previously embedded the key ID of your data encryption key in your - automatic encryption rules, update the :ref:`JSON Schema ` - with your new data encryption key ID. - - Your client application is now ready to automatically encrypt your data - using the master key on your KMS provider. diff --git a/source/includes/steps-fle-convert-to-a-remote-master-key-gcp.yaml b/source/includes/steps-fle-convert-to-a-remote-master-key-gcp.yaml deleted file mode 100644 index 17b88e735..000000000 --- a/source/includes/steps-fle-convert-to-a-remote-master-key-gcp.yaml +++ /dev/null @@ -1,426 +0,0 @@ -title: Create a GCP Service Account -ref: create-a-gcp-service-account -content: | - 1. Create a service account for your client application by following the - official Google documentation on - `Creating and managing a service account `__. - - 2. After you create the service account, locate and record the following - authentication settings for use in a later step: - - - **email** - - **privateKey** (this value is only returned when you create the account) - - **endpoint** - ---- -title: Create the Master Key -ref: create-the-master-key-gcp -content: | - The following diagram shows the steps required to create a new - **master key** on a KMS provider. - - .. image:: /figures/CSFLE_Master_Key_KMS.png - :alt: Diagram that describes creating a master key when using a KMS provider - - 1. To create a master key, log into your Google Cloud account and - follow the steps in Google Cloud's official - `Creating symmetric keys guide `__ - to create a **symmetric key**. - - The master key is used by your application to encrypt and decrypt your - **data encryption key**. - - .. note:: - - If you rotate the master key, either by specifying a date or manually, - the provider changes the content of the master key. To transition - to the new key: - - 1. Decrypt and save the data using the original data encryption key. - #. Generate a new data encryption key with the new master key. - #. Update the ``keyVersion`` parameter to the latest version of the master key. - #. Re-encrypt the data using the new data encryption key. - - 2. Ensure that your client application has permissions to encrypt and - decrypt data using the key. For example, the - `roles/cloudkms.cryptoKeyEncrypterDecrypter `__ - role has permissions to both encrypt and decrypt keys. - - .. important:: - - The client application *should not* have administrative permissions - for the master key. We recommend that you follow the - `principle of least privilege `__ - to keep your data secure. - ---- -title: Specify your Google Cloud KMS Credentials -ref: specify-your-gcp-kms-provider-credentials -content: | - Unlike the local key provider, the Google Cloud KMS does not read - the master key directly from the client application. Instead, - it retrieves the key using your service client credentials and key - details. - - 1. First, identify the following authentication credentials on Google KMS: - - .. list-table:: - :header-rows: 1 - :stub-columns: 1 - :widths: 20 12 68 - - * - Field - - Required - - Description - - * - email - - Yes - - Identifies your service account email address. - - * - privateKey - - Yes - - | Identifies your service account private key in either - `base64 string `__ or - :manual:`Binary subtype 0 ` - format without the prefix and suffix markers. - | - | Suppose your service account private key value is as follows: - - .. code-block:: none - :copyable: false - - -----BEGIN PRIVATE KEY-----\nyour-private-key\n-----END PRIVATE KEY-----\n - - | The value you would specify for this field is: - - .. code-block:: none - :copyable: false - - your-private-key - - | If you have a ``user-key.json`` credential file, you can extract - the string by executing the following command in a bash or - similar shell: - - .. code-block:: shell - - cat user-key.json | jq -r .private_key | openssl pkcs8 -topk8 -nocrypt -inform PEM -outform DER | base64 -w 0 - - * - endpoint - - No - - Specifies a hostname and port number for the authentication server. - Defaults to oauth2.googleapis.com. - - 2. Next, add your authentication credentials to your CSFLE-enabled client - code: - - .. include:: /includes/substitute-placeholders-gcp.rst - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: java - - Map> kmsProviders = new HashMap>(); - Map providerDetails = new HashMap(); - - providerDetails.put("email", new BsonString("")); - providerDetails.put("privateKey", new BsonString("")); - providerDetails.put("endpoint", new BsonString("")); - - kmsProviders.put("gcp", providerDetails); - - .. note:: - - To use the GCP KMS, you must use - `mongodb-crypt `__ - version 1.1 or later in your application's environment. - - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - - kmsProviders = { - gcp: { - email: "", - privateKey: "", - endpoint: "", - }, - } - - .. note:: - - To use the GCP KMS, you must use ``mongodb-client-encryption`` version - `1.1.1 `__ or later. - - .. tab:: - :tabid: python - - .. code-block:: python - - kms_provider = { - "gcp": { - "email": "", - "privateKey": "", - "endpoint": "", - } - } - - .. note:: - - To use the GCP KMS, you must use ``pymongocrypt`` version - 1.1 or later in your application's environment. Follow our guide - to `build libmongocrypt from source `__. - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - var kmsProviders = new Dictionary>(); - - var gcpPrivateKey = Environment.GetEnvironmentVariable("FLE_GCP_PRIVATE_KEY"); - var gcpEmail = Environment.GetEnvironmentVariable("FLE_GCP_EMAIL"); - var gcpEndpoint = Environment.GetEnvironmentVariable("FLE_GCP_IDENTITY_ENDPOINT"); // Optional, defaults to "oauth2.googleapis.com". - var gcpKmsOptions = new Dictionary - { - { "privateKey", gcpPrivateKey }, - { "email", gcpEmail }, - }; - if (gcpEndpoint != null) - { - gcpKmsOptions.Add("endpoint", gcpEndpoint); - } - kmsProviders.Add("gcp", gcpKmsOptions); - - .. note:: - - To use the GCP KMS, you must use - `libmongocrypt `__ version 1.1 or later in your application's environment. - - .. tab:: - :tabid: go - - In ``kms/provider.go``, update the variable declarations or define the expected environmental variables - in ``GCPProvider()``. - - .. code-block:: go - - gcpEmail := GetCheckedEnv("FLE_GCP_EMAIL") - gcpPrivateKey := GetCheckedEnv("FLE_GCP_PRIVATE_KEY") - - The expected KMS provider map is created with struct tags. - - .. code-block:: go - - func (g *GCP) Credentials() map[string]map[string]interface{} { - return map[string]map[string]interface{}{"gcp": structs.Map(g.credentials)} - } - - - .. note:: - - To use the GCP KMS, you must use - `libmongocrypt `__ - version 1.1 or later in your application's environment. - ---- -title: Create a New Data Encryption Key -ref: create-a-new-data-key-gcp -content: | - To encrypt your data, you need a data encryption key generated from your - KMS-hosted **master key**. The following diagram shows the requests you need - to make from the client application to create and store a new **data - encryption key**: - - .. image:: /figures/CSFLE_Data_Key_KMS.png - :alt: Diagram that describes creating a data encryption key when using a KMS provider - - 1. First, provide your client with the following information to access the - master key: - - .. list-table:: - :header-rows: 1 - :stub-columns: 1 - :widths: 30 15 45 - - * - Field - - Required - - Description - - * - projectId - - Yes - - Identifier for your project in which you created the key. - - * - location - - Yes - - Region specified for your key. - - * - keyRing - - Yes - - Identifier for the group of keys your key belongs to. - - * - keyName - - Yes - - Identifier for the symmetric master key. - - * - keyVersion - - No - - Specifies the version of the named key. If not specified, the default - version of the key is used. - - * - endpoint - - No - - Specifies the host and optional port of the Cloud KMS. The default - is ``cloudkms.googleapis.com``. - - 2. Once you have the required information, update and run the following code - to generate a new data encryption key: - - .. include:: /includes/substitute-placeholders-gcp-key.rst - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - In ``CSFLEHelpers.java``, update your call to - ``DataKeyOptions.masterKey()`` to include your master key data: - - .. code-block:: Java - - DataKeyOptions dataKeyOptions = new DataKeyOptions().masterKey( - new BsonDocument() - .append("provider", "gcp") - .append("projectId", "") - .append("location", "") - .append("keyRing", "") - .append("keyVersion", "") - .append("endpoint", "")); - - BsonBinary dataKeyId = clientEncryption.createDataKey("gcp", dataKeyOptions); - - .. tab:: - :tabid: nodejs - - - .. code-block:: javascript - - const encryption = new ClientEncryption(client, { - keyVaultNamespace, - kmsProviders, - }); - const key = await encryption.createDataKey("gcp", { - masterKey: { - projectId: "", - location: "", - keyRing: "", - keyName: "", - keyVersion: "", - endpoint: "", - }, - }); - - const base64DataKeyId = key.toString("base64"); - console.log("DataKeyId [base64]: ", base64DataKeyId); - - .. tab:: - :tabid: python - - In ``app.py``, define the following dictionary to pass to your call to - ``create_data_key()``: - - .. code-block:: python - - master_key = { - "provider": "gcp", - "projectId": "", - "location": "", - "keyRing": "", - "keyName": "", - "keyVersion": "", - "endpoint": "", - } - - .. note:: - - To use Google Cloud KMS, you must use `pymongocrypt `__ - version 1.1 or later in your application's environment. - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - // _connectionString is defined elsewhere as "mongodb://localhost:27017" - - var keyVaultClient = new MongoClient(_connectionString); - var clientEncryptionOptions = new ClientEncryptionOptions( - keyVaultClient: keyVaultClient, - keyVaultNamespace: _keyVaultNamespace, - kmsProviders: kmsProviders); - - var clientEncryption = new ClientEncryption(clientEncryptionOptions); - - - var gcpDataKeyProjectId = Environment.GetEnvironmentVariable("FLE_GCP_PROJ_ID"); - var gcpDataKeyLocation = Environment.GetEnvironmentVariable("FLE_GCP_KEY_LOC"); // Optional. e.g. "global" - var gcpDataKeyKeyRing = Environment.GetEnvironmentVariable("FLE_GCP_KEY_RING"); - var gcpDataKeyKeyName = Environment.GetEnvironmentVariable("FLE_GCP_KEY_NAME"); - var gcpDataKeyKeyVersion = Environment.GetEnvironmentVariable("FLE_GCP_KEY_VERSION"); // Optional - var gcpDataKeyEndpoint = Environment.GetEnvironmentVariable("FLE_GCP_KMS_ENDPOINT"); // Optional, KMS URL, defaults to https://www.googleapis.com/auth/cloudkms - - var dataKeyOptions = new DataKeyOptions( - masterKey: new BsonDocument - { - { "projectId", gcpDataKeyProjectId }, - { "location", gcpDataKeyLocation } , - { "keyRing", gcpDataKeyKeyRing }, - { "keyName", gcpDataKeyKeyName }, - { "keyVersion", () => gcpDataKeyKeyVersion, gcpDataKeyKeyVersion != null }, - { "endpoint", () => gcpDataKeyEndpoint, gcpDataKeyEndpoint != null } - }); - - var dataKeyId = clientEncryption.CreateDataKey("gcp", dataKeyOptions, CancellationToken.None); - - .. tab:: - :tabid: go - - In ``kms/provider.go``, update the variable declarations or define the expected environmental variables - in ``GCPProvider()``. - - .. code-block:: go - - gcpProjectID := GetCheckedEnv("FLE_GCP_PROJ_ID") - gcpLocation := GetCheckedEnv("FLE_GCP_LOCATION") - gcpKeyRing := GetCheckedEnv("FLE_GCP_KEY_RING") - gcpKeyName := GetCheckedEnv("FLE_GCP_KEY_NAME") - - Struct tags are used to pass these values directly to the driver for use. In ``kms/provider.go`` - - .. code-block:: go - - func (g *GCP) DataKeyOpts() interface{} { - return g.dataKeyOpts - } - - In ``csfle/data_key.go`` - - .. code-block:: go - - dataKeyOpts := options.DataKey().SetMasterKey(provider.DataKeyOpts()) - dataKeyID, err := clientEnc.CreateDataKey(context.TODO(), provider.Name(), dataKeyOpts) - ---- -title: Update the Automatic Encryption JSON Schema -ref: update-the-json-schema-gcp -content: | - If you previously embedded the key ID of your data encryption key in your - automatic encryption rules, update the :ref:`JSON Schema ` - with your new data encryption key id. - - Your client application is now ready to automatically encrypt your data - using the master key on your KMS provider. diff --git a/source/includes/steps-fle-convert-to-a-remote-master-key-kmip.yaml b/source/includes/steps-fle-convert-to-a-remote-master-key-kmip.yaml deleted file mode 100644 index 91398dbf8..000000000 --- a/source/includes/steps-fle-convert-to-a-remote-master-key-kmip.yaml +++ /dev/null @@ -1,127 +0,0 @@ -title: Configure Your KMIP Provider -ref: configure-kmip-provider -content: | - - To connect a MongoDB driver client to your KMIP provider, you must configure - your KMIP provider such that it accepts your client's TLS certificate. - - Consult the documentation for your KMIP provider for information on how - to accept your client certificate. - ---- -title: Specify your Certificates -ref: specify-certificates -content: | - - Your client must connect to your KMIP provider through TLS and present - a client certificate that your KMIP provider accepts. - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - Specify the following Java system properties to configure your client's - TLS connection: - - .. code-block:: shell - - -Djavax.net.ssl.keyStoreType=pkcs12 - -Djavax.net.ssl.keyStore= - -Djavax.net.ssl.keyStorePassword= - - .. note:: Configure Client With SSLContext - - If you would rather configure your KMIP provider-client using an SSL context, use the - `kmsProviderSslContextMap <{+java-api+}/apidocs/mongodb-driver-core/com/mongodb/ClientEncryptionSettings.Builder.html#kmsProviderSslContextMap(java.util.Map)>`__ - method. - ---- -title: Create a New Data Encryption Key -ref: create-a-new-data-key -content: | - To encrypt your data, you need a data encryption key generated from your - KMIP provider-hosted **master key**. The following diagram shows the requests you need - to make from the client application to create and store a new **data - encryption key**: - - .. image:: /figures/CSFLE_Data_Key_KMIP.png - :alt: Diagram that describes creating a data encryption key when using a KMIP provider - - 1. First, specify the following information to access the master key: - - .. list-table:: - :header-rows: 1 - :stub-columns: 1 - :widths: 30 15 45 - - * - Field - - Required - - Description - - * - keyId - - No - - The ``keyId`` field of a 96 byte - `Secret Data managed object `__ - stored in your KMIP provider. - - .. note:: Create a New Master Key - - If you do not specify the ``keyId`` field in the ``masterKey`` document - you send to your KMIP provider, the driver creates a new - 96 Byte Secret Data managed object in your KMIP provider to act as your - master key. - - * - endpoint - - Yes - - The URI of your KMIP provider. - - 2. Once you have the required information, update and run the following code - to generate the new data encryption key: - - .. include:: /includes/substitute-placeholders-kmip.rst - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: java - - Map> kmsProviderProperties = new HashMap<>(); - Map providerDetails = new HashMap<>(); - providerDetails.put("endpoint", ""); - kmsProviderProperties.put(kmsProvider, providerDetails); - String keyVaultCollection = "" - - ClientEncryption clientEncryption = ClientEncryptions.create(ClientEncryptionSettings.builder() - .keyVaultMongoClientSettings(MongoClientSettings.builder() - .applyConnectionString(new ConnectionString("")) - .build()) - .keyVaultNamespace(keyVaultNamespace) - .kmsProviders(kmsProviders) - .build()); - - DataKeyOptions dataKeyOptions = new DataKeyOptions().masterKey( - new BsonDocument() - .append("keyId", "")); - - BsonBinary dataKeyId = clientEncryption.createDataKey("kmip", dataKeyOptions); - - System.out.println("DataKeyId [UUID]: " + dataKeyId.asUuid().toString()); - - .. note:: - - To use a KMIP provider, you must use `mongodb-crypt `__ - version 1.3 or later in your application's environment. - ---- -title: Update the Automatic Encryption JSON Schema -ref: update-the-json-schema -content: | - If you previously embedded the key ID of your data encryption key in your - automatic encryption rules, update the :ref:`JSON Schema ` - with your new data encryption key ID. - - Your client application is now ready to automatically encrypt your data - using the master key on your KMIP provider. diff --git a/source/includes/steps-fle-create-data-encryption-key.yaml b/source/includes/steps-fle-create-data-encryption-key.yaml deleted file mode 100644 index 030ea216e..000000000 --- a/source/includes/steps-fle-create-data-encryption-key.yaml +++ /dev/null @@ -1,475 +0,0 @@ -title: Read the Locally-Managed Master Key from a File -ref: read-local-master-key-from-file -level: 4 -content: | - First, retrieve the contents of the master key file that you generated - in the :ref:`Create a Master Key ` section - with the following **code snippet**: - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: java - :emphasize-lines: 6 - - String path = "master-key.txt"; - - byte[] localMasterKey= new byte[96]; - - try (FileInputStream fis = new FileInputStream(path)) { - fis.readNBytes(localMasterKey, 0, 96); - } - .. note:: - - The `FileInputStream#readNBytes `_ - method was introduced in Java 9. The helper method is used in - this guide to keep the implementation concise. If you are using - JDK 8, you may consider - `implementing a custom solution `_ - to read a file into a byte array. - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - :emphasize-lines: 2 - - const path = './master-key.txt'; - const localMasterKey = fs.readFileSync(path); - .. tab:: - :tabid: python - - .. code-block:: python - :emphasize-lines: 3 - - path = "./master-key.txt" - with open(path, "rb") as f: - local_master_key = f.read() - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - string localMasterKeyBase64 = File.ReadAllText(__localMasterKeyPath); - var localMasterKeyBytes = Convert.FromBase64String(localMasterKeyBase64); - ---- -title: Specify KMS Provider Settings -ref: specify-kms-provider-settings -level: 4 -content: | - Next, specify the KMS provider settings. The client uses these settings to - discover the master key. Set the provider name to ``local`` when using a local - master key in the following **code snippet**: - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - The KMS provider settings are stored in a Map in order to use the - :java-docs:`kmsProviders helper - method ` - for the ClientEncryptionSettings Builder. - - .. code-block:: java - :emphasize-lines: 2,5 - - Map keyMap = new HashMap(); - keyMap.put("key", localMasterKey); - - Map> kmsProviders = new HashMap>(); - kmsProviders.put("local", keyMap); - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - :emphasize-lines: 2,3 - - const kmsProviders = { - local: { - key: localMasterKey, - }, - }; - .. tab:: - :tabid: python - - .. code-block:: python - :emphasize-lines: 2,3 - - kms_providers = { - "local": { - "key": local_master_key # local_master_key variable from the previous step - }, - } - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - var kmsProviders = new Dictionary>(); - var localOptions = new Dictionary - { - { "key", localMasterKeyBytes } - }; - kmsProviders.Add("local", localOptions); - ---- -title: Create a Data Encryption Key -ref: create-a-data-encryption-key -level: 4 -content: | - Construct a client with the MongoDB connection string and key vault - namespace configuration, create a unique index on the ``keyAltNames`` field - in that collection, and create a data encryption key with the following - **code snippet**. The key vault in this example uses the ``encryption`` - database and ``__keyVault`` collection. - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: java - :emphasize-lines: 8,9,12,13 - - String connectionString = "mongodb://localhost:27017"; - String keyVaultNamespace = "encryption.__keyVault"; - - ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder() - .keyVaultMongoClientSettings(MongoClientSettings.builder() - .applyConnectionString(new ConnectionString(connectionString)) - .build()) - .keyVaultNamespace(keyVaultNamespace) - .kmsProviders(kmsProviders) - .build(); - - ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings); - BsonBinary dataKeyId = clientEncryption.createDataKey(kmsProvider, new DataKeyOptions()); - System.out.println("DataKeyId [UUID]: " + dataKeyId.asUuid()); - - String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeyId.getData()); - System.out.println("DataKeyId [base64]: " + base64DataKeyId); - - The ``createDataKey()`` method returns a :java-docs:`BsonBinary - ` object from which we can extract - the UUID and Base64 representations of the key id. - - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - :emphasize-lines: 12,14,15,17 - - const base64 = require('uuid-base64'); - - const connectionString = 'mongodb://localhost:27017'; - const keyVaultNamespace = 'encryption.__keyVault'; - const client = new MongoClient(connectionString, { - useNewUrlParser: true, - useUnifiedTopology: true, - }); - - async function main() { - try { - await client.connect(); - const encryption = new ClientEncryption(client, { - keyVaultNamespace, - kmsProviders, - }); - const key = await encryption.createDataKey('local'); - const base64DataKeyId = key.toString('base64'); - const uuidDataKeyId = base64.decode(base64DataKeyId); - console.log('DataKeyId [UUID]: ', uuidDataKeyId); - console.log('DataKeyId [base64]: ', base64DataKeyId); - } finally { - await client.close(); - } - } - main(); - - .. note:: - - This code includes a dependency on the ``uuid-base64`` - npm package. See the `npmjs documentation on the uuid-base64 - package `_ for - installation instructions. - .. tab:: - :tabid: python - - .. code-block:: python - :emphasize-lines: 13,21 - - from pymongo import MongoClient - from pymongo.encryption_options import AutoEncryptionOpts - from pymongo.encryption import ClientEncryption - import base64 - from bson.codec_options import CodecOptions - from bson.binary import STANDARD, UUID - - connection_string = "mongodb://localhost:27017" - key_vault_namespace = "encryption.__keyVault" - - client = MongoClient(connection_string) - client_encryption = ClientEncryption( - kms_providers, # pass in the kms_providers variable from the previous step - key_vault_namespace, - client, - CodecOptions(uuid_representation=STANDARD) - ) - - - def create_data_encryption_key(): - data_key_id = client_encryption.create_data_key("local") - uuid_data_key_id = UUID(bytes=data_key_id) - base_64_data_key_id = base64.b64encode(data_key_id) - print("DataKeyId [UUID]: ", str(uuid_data_key_id)) - print("DataKeyId [base64]: ", base_64_data_key_id) - return data_key_id - - - data_key_id = create_data_encryption_key() - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - var keyVaultClient = new MongoClient(_connectionString); - var clientEncryptionOptions = new ClientEncryptionOptions( - keyVaultClient: keyVaultClient, - keyVaultNamespace: _keyVaultNamespace, - kmsProviders: kmsProviders); - var clientEncryption = new ClientEncryption(kmsProviders); - var dataKeyId = clientEncryption.CreateDataKey("local", new DataKeyOptions(), CancellationToken.None); - Console.WriteLine($"Local DataKeyId [UUID]: {dataKeyId}"); - var dataKeyIdBase64 = Convert.ToBase64String(GuidConverter.ToBytes(dataKeyId, GuidRepresentation.Standard)); - Console.WriteLine($"Local DataKeyId [base64]: {dataKeyIdBase64}"); - - - - The ``_id`` field of the data encryption key is represented as a **UUID** - and is encoded in **Base64** format. Use your **Base64**-encoded data key - id when specified for the remainder of this guide. - - The output from the code above should resemble the following: - - .. code-block:: none - - DataKeyId [UUID]: de4d775a-4499-48bc-bb93-3f81c3c90704 - DataKeyId [base64]: 3k13WkSZSLy7kwAAP4HDyQ== - - .. note:: - - Ensure that the client has `ReadWrite - `_ - permissions on the specified key vault namespace. ---- -title: Verify that the Data Encryption Key was Created -ref: verify-data-key-created -level: 4 -content: | - Query the key vault collection for the data encryption key that was inserted - as a document into your MongoDB replica set using the key id printed in the - prior step with the following **code snippet**. - - .. tabs-drivers:: - - .. tab:: - :tabid: java-sync - - .. code-block:: java - :emphasize-lines: 4 - - String connectionString = "mongodb://localhost:27017"; - String keyVaultDb = "encryption"; - String keyVaultCollection = "__keyVault"; - String base64KeyId = "3k13WkSZSLy7kwAAP4HDyQ=="; // use the base64 data key id returned by createKey() in the prior step - - MongoClient mongoClient = MongoClients.create(connectionString); - MongoCollection collection = mongoClient.getDatabase(keyVaultDb).getCollection(keyVaultCollection); - - Bson query = Filters.eq("_id", new Binary((byte) 4, Base64.getDecoder().decode(base64KeyId))); - Document doc = collection - .find(query) - .first(); - - System.out.println(doc); - - This code example should print a retrieved document that resembles the - following: - - .. code-block:: none - - Document{{ - _id=dad3a063-4f9b-48f8-bf4e-7ca9d323fd1c, - keyMaterial=org.bson.types.Binary@40e1535, - creationDate=Wed Sep 25 22:22:54 EDT 2019, - updateDate=Wed Sep 25 22:22:54 EDT 2019, - status=0, - masterKey=Document{{provider=local}} - }} - - .. note:: View the Extended JSON Representation of the Data Key - - While the ``Document`` class is the - `Document type <{+java-api+}/bson/documents>`__ - most commonly used to work with query results, we can use the - ``BsonDocument`` class to view the data key document as extended - JSON. Replace the ``Document`` assignment code with the following - to retrieve and print a ``BsonDocument``: - - .. code-block:: java - :emphasize-lines: 1,2 - - BsonDocument doc = collection - .withDocumentClass(BsonDocument.class) - .find(query) - .first(); - - System.out.println(doc); - .. tab:: - :tabid: nodejs - - .. code-block:: javascript - :emphasize-lines: 7 - - const mongodb = require("mongodb") - const { MongoClient, Binary } = mongodb - - const connectionString = 'mongodb://localhost:27017/'; - const keyVaultDb = 'encryption'; - const keyVaultCollection = '__keyVault'; - const base64KeyId = '3k13WkSZSLy7kwAAP4HDyQ=='; // use the base64 data key id returned by createKey() in the prior step - - const client = new MongoClient(connectionString, { - useNewUrlParser: true, - useUnifiedTopology: true, - }); - - async function main() { - try { - await client.connect(); - const keyDB = client.db(keyVaultDb); - const keyColl = keyDB.collection(keyVaultCollection); - const query = { - _id: new Binary(Buffer.from(base64KeyId, "base64"), 4), - }; - const dataKey = await keyColl.findOne(query); - console.log(dataKey); - } finally { - await client.close(); - } - } - main(); - - This code example should print a retrieved document that resembles the - following: - - .. code-block:: none - - { - _id: Binary { - _bsontype: 'Binary', - sub_type: 4, - position: 16, - buffer: - }, - keyMaterial: Binary { - _bsontype: 'Binary', - sub_type: 0, - position: 160, - buffer: - }, - creationDate: 2019-09-25T22:22:54.017Z, - updateDate: 2019-09-25T22:22:54.017Z, - status: 0, - masterKey: { provider: 'local' } - } - .. tab:: - :tabid: python - - .. code-block:: python - :emphasize-lines: 9,10 - - from pprint import pprint - connection_string = "mongodb://localhost:27017" - key_vault_db = "encryption" - key_vault_coll = "__keyVault" - - client = MongoClient(connection_string) - key_vault = client[key_vault_db][key_vault_coll] - - # Pass in the data_key_id created in previous section - key = key_vault.find_one({"_id": data_key_id}) - pprint(key) - - - This code example should print a retrieved document that resembles the - following: - - .. code-block:: none - - { - "_id": UUID('1e83d013-d873-47df-abb1-e57898a72d4c'), - "keyMaterial": b'\x96#\xeb\xa1xKA\xa7GM\xef\x08\xc04\'gD\x96\x9c\xa4\xd3?\xe3Db0H\xbb\x86\xa5\xc2\x1f\x14\x0f\xb8\xb8\x8a\x9d\xc9\xae\xa1g\xaf\xeb\x8b\x99\xb4b"\xc0\xe8e\x07\x1b.\xeet\xf5<%\xfd\x06Y\x15o=3Yk\x9fue\xd8V#X\xc1IB\xf5\xc9+\x95\xb1\x9c\xc0\x08U?\xaf\xb1U\xc6\x84\x89\x9b\xdc\x98\xc9~\xb2\xbd\xf6\\\xa2y\x08\xdf\x8f\xa1\x03\t9\xe7_+J>_H\xb4\x97up\x93Sc\x88\x0fG-+\x86\x95\x9e\xc2\x8es\x9e\xcb%%lVQ\xa2\xf1\xe3W\x83\x10]\xc9\x1fm\x7f\xbc\xbf\xd2d', - "creationDate": datetime.datetime(2019, 9, 30, 20, 43, 10, 951000), - "updateDate": datetime.datetime(2019, 9, 30, 20, 43, 10, 951000), - "status": 0, - "masterKey": { - "provider": "local" - } - } - - .. tab:: - :tabid: csharp - - .. code-block:: csharp - - - var client = new MongoClient("mongodb://localhost:27017"); - // dataKeyId is the UUID from the previous step that was printed - // to the console - var dataKeyId = "" - var collection = client - .GetDatabase(_keyVaultNamespace.DatabaseNamespace.DatabaseName) - .GetCollection( - _keyVaultNamespace.CollectionName, - new MongoCollectionSettings - { - GuidRepresentation = GuidRepresentation.Standard - }); - var query = Builders.Filter.Eq("_id", new BsonBinaryData(dataKeyId, GuidRepresentation.Standard)); - var keyDocument = collection - .Find(query) - .Single(); - - Console.WriteLine(keyDocument); - - This code example should print a retrieved document that resembles the - following: - - .. code-block:: none - - { - "_id" : CSUUID("aae4f3b4-91b6-4cef-8867-3113a6dfb27b"), - "keyMaterial" : new BinData(0, "rcfTQLRxF1mg98/Jr7iFwXWshvAVIQY6JCswrW+4bSqvLwa8bQrc65w7+3P3k+TqFS+1Ce6FW4Epf5o/eqDyT//I73IRc+yPUoZew7TB1pyIKmxL6ABPXJDkUhvGMiwwkRABzZcU9NNpFfH+HhIXjs324FuLzylIhAmJA/gvXcuz6QSD2vFpSVTRBpNu1sq0C9eZBSBaOxxotMZAcRuqMA=="), - "creationDate" : ISODate("2020-11-08T17:58:36.372Z"), - "updateDate" : ISODate("2020-11-08T17:58:36.372Z"), - "status" : 0, - "masterKey" : { - "provider" : "local" - } - } - - - This retrieved document contains the following data: - - * Data encryption key id (stored as a UUID). - * Data encryption key in encrypted form. - * KMS provider information for the master key. - * Other metadata such as creation and last modified date. - diff --git a/source/includes/table-sql-to-mongo-to-cpp-examples.yaml b/source/includes/table-sql-to-mongo-to-cpp-examples.yaml deleted file mode 100644 index 8b478f1bc..000000000 --- a/source/includes/table-sql-to-mongo-to-cpp-examples.yaml +++ /dev/null @@ -1,245 +0,0 @@ -# table structure. all content symbolic. -section: layout -header: [ meta.header1, meta.header2, meta.header3 ] -rows: - - 1: [ content.sql1, content.mongo1, content.cpp1 ] - - 2: [ content.sql2, content.mongo2, content.cpp2 ] - - 3: [ content.sql3, content.mongo3, content.cpp3 ] - - 4: [ content.sql4, content.mongo4, content.cpp4 ] - - 5: [ content.sql5, content.mongo5, content.cpp5 ] - - 6: [ content.sql6, content.mongo6, content.cpp6 ] - - 7: [ content.sql7, content.mongo7, content.cpp7 ] - - 8: [ content.sql8, content.mongo8, content.cpp8 ] - - 9: [ content.sql9, content.mongo9, content.cpp9 ] - - 10: [ content.sql10, content.mongo10, content.cpp10 ] - - 11: [ content.sql11, content.mongo11, content.cpp11 ] - - 12: [ content.sql12, content.mongo12, content.cpp12 ] - - 13: [ content.sql13, content.mongo13, content.cpp13 ] ---- -# table metadata, as meta. -section: meta -header1: "SQL" -header2: ":program:`manual:mongo` Shell" -header3: "C++ Driver" ---- -# table content, as content. -section: content -sql1: | - .. code-block:: sql - - INSERT INTO USERS - VALUES( 1, 1) -mongo1: | - .. code-block:: javascript - - db.users.insert( { a: 1, b: 1 } ) -cpp1: | - .. code-block:: cpp - - // GENOID is optional. if not done by client, - // server will add an _id - - c.insert("mydb.users", - BSON(GENOID<<"a"<<1<<"b"<<1)); - // then: - string err = c.getLastError(); -sql2: | - .. code-block:: sql - - SELECT a,b FROM users -mongo2: | - .. code-block:: javascript - - db.users.find( {}, - {a: 1, b: 1 } - ) -cpp2: | - .. code-block:: cpp - - BSONObj b = BSON("a"<<1<<"b"<<1) - auto_ptr cursor = - c.query("mydb.users", Query(), - 0, 0, &b); -sql3: | - .. code-block:: sql - - SELECT * FROM users -mongo3: | - .. code-block:: javascript - - db.users.find() -cpp3: | - .. code-block:: cpp - - auto_ptr cursor = - c.query("mydb.users", Query()); -sql4: | - .. code-block:: sql - - SELECT * - FROM users - WHERE age=33 -mongo4: | - .. code-block:: javascript - - db.users.find( { age: 33 } ) -cpp4: | - .. code-block:: cpp - - auto_ptr cursor = - c.query("mydb.users", QUERY("age"<<33)) - // or: - auto_ptr cursor = - c.query("mydb.users", BSON("age"<<33)) -sql5: | - .. code-block:: sql - - SELECT * - FROM users - WHERE age=33 - ORDER BY name -mongo5: | - .. code-block:: javascript - - db.users.find( { age: 33 } ).sort( { name: 1 } ) -cpp5: | - .. code-block:: cpp - - auto_ptr cursor = - c.query("mydb.users", - QUERY("age"<<33).sort("name")); -sql6: | - .. code-block:: sql - - SELECT * - FROM users - WHERE age>33 - AND age<=40 -mongo6: | - .. code-block:: javascript - - db.users.find( { 'age': { $gt:33, $lte:40 } } ) -cpp6: | - .. code-block:: cpp - - auto_ptr cursor = - c.query("mydb.users", - QUERY("age"< cursor = - c.query("mydb.users", Query(), - 10, 20); -sql9: | - .. code-block:: sql - - SELECT * FROM users LIMIT 1 -mongo9: | - .. code-block:: javascript - - db.users.findOne() -cpp9: | - .. code-block:: cpp - - bo obj = c.findOne("mydb.users", Query()); -sql10: | - .. code-block:: sql - - SELECT DISTINCT last_name - FROM users - WHERE x=1 -mongo10: | - .. code-block:: javascript - - db.users.distinct( 'last_name', {x: 1} ) -cpp10: | - .. code-block:: cpp - - // no helper for distinct yet in c++ driver, - // so send command manually - bo cmdResult; - bool ok = c.runCommand( - "mydb", - BSON("distinct" << "users" - << "key" << "last_name" - << "query" << BSON("x"<<1)), - cmdResult); - list results; - cmdResult["values"].Obj().Vals(results); -sql11: | - .. code-block:: sql - - SELECT COUNT(*) - FROM users - where AGE > 30 -mongo11: | - .. code-block:: javascript - - db.users.find( { age: { $gt: 30 } } ).count() -cpp11: | - .. code-block:: cpp - - unsigned long long n = - c.count("mydb.users", BSON("age"<