Search in sources :

Example 41 with BsonString

use of org.bson.BsonString in project mongo-java-driver by mongodb.

the class ClientEncryptionDataKeyAndDoubleEncryptionTest method testProvider.

@Test
public void testProvider() {
    String keyAltName = format("%s_altname", providerName);
    BsonBinary dataKeyId = clientEncryption.createDataKey(providerName, new DataKeyOptions().keyAltNames(singletonList(keyAltName)).masterKey(getMasterKey()));
    assertEquals(4, dataKeyId.getType());
    ArrayList<Document> dataKeys = client.getDatabase("keyvault").getCollection("datakeys").find(eq("_id", dataKeyId)).into(new ArrayList<>());
    assertEquals(1, dataKeys.size());
    Document dataKey = dataKeys.get(0);
    assertEquals(providerName, dataKey.get("masterKey", new Document()).get("provider", ""));
    String insertWriteConcern = commandListener.getCommandStartedEvent("insert").getCommand().getDocument("writeConcern", new BsonDocument()).getString("w", new BsonString("")).getValue();
    assertEquals("majority", insertWriteConcern);
    String stringToEncrypt = format("hello %s", providerName);
    BsonBinary encrypted = clientEncryption.encrypt(new BsonString(stringToEncrypt), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(dataKeyId));
    assertEquals(6, encrypted.getType());
    Document insertDocument = new Document("_id", providerName);
    insertDocument.put("value", encrypted);
    clientEncrypted.getDatabase("db").getCollection("coll").insertOne(insertDocument);
    Document decryptedDocument = clientEncrypted.getDatabase("db").getCollection("coll").find(eq("_id", providerName)).first();
    assertNotNull(decryptedDocument);
    assertEquals(stringToEncrypt, decryptedDocument.get("value", ""));
    BsonBinary encryptedKeyAltName = clientEncryption.encrypt(new BsonString(stringToEncrypt), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyAltName(keyAltName));
    assertEquals(encrypted, encryptedKeyAltName);
    assertThrows(MongoClientException.class, () -> clientEncrypted.getDatabase("db").getCollection("coll").insertOne(new Document("encrypted_placeholder", encrypted)));
}
Also used : BsonDocument(org.bson.BsonDocument) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) BsonBinary(org.bson.BsonBinary) BsonString(org.bson.BsonString) BsonString(org.bson.BsonString) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) Test(org.junit.Test)

Example 42 with BsonString

use of org.bson.BsonString in project mongo-java-driver by mongodb.

the class ClientSideEncryptionCorpusTest method setUp.

@Before
public void setUp() throws IOException, URISyntaxException {
    assumeTrue(serverVersionAtLeast(4, 2));
    assumeTrue("Corpus tests disabled", hasEncryptionTestsEnabled());
    MongoClientSettings clientSettings = getMongoClientSettingsBuilder().codecRegistry(fromRegistries(fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)), MongoClientSettings.getDefaultCodecRegistry())).build();
    // Step 1: create unencrypted client
    client = MongoClients.create(clientSettings);
    MongoDatabase db = client.getDatabase("db");
    // Step 2: Drop and recreate db.coll with schema
    BsonDocument schemaDocument = bsonDocumentFromPath("corpus-schema.json");
    db.getCollection("coll").drop();
    db.runCommand(new BsonDocument("create", new BsonString("coll")).append("validator", new BsonDocument("$jsonSchema", schemaDocument)));
    // Step 3: Drop and create keyvault.datakeys
    MongoDatabase keyvaultDatabase = client.getDatabase("keyvault");
    MongoCollection<BsonDocument> dataKeysCollection = keyvaultDatabase.getCollection("datakeys", BsonDocument.class).withWriteConcern(WriteConcern.MAJORITY);
    dataKeysCollection.drop();
    dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-aws.json"));
    dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-azure.json"));
    dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-gcp.json"));
    dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-kmip.json"));
    dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-local.json"));
    // Step 4: Configure our objects
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {

        {
            put("aws", new HashMap<String, Object>() {

                {
                    put("accessKeyId", System.getProperty("org.mongodb.test.awsAccessKeyId"));
                    put("secretAccessKey", System.getProperty("org.mongodb.test.awsSecretAccessKey"));
                }
            });
            put("azure", new HashMap<String, Object>() {

                {
                    put("tenantId", System.getProperty("org.mongodb.test.azureTenantId"));
                    put("clientId", System.getProperty("org.mongodb.test.azureClientId"));
                    put("clientSecret", System.getProperty("org.mongodb.test.azureClientSecret"));
                }
            });
            put("gcp", new HashMap<String, Object>() {

                {
                    put("email", System.getProperty("org.mongodb.test.gcpEmail"));
                    put("privateKey", System.getProperty("org.mongodb.test.gcpPrivateKey"));
                }
            });
            put("kmip", new HashMap<String, Object>() {

                {
                    put("endpoint", System.getProperty("org.mongodb.test.kmipEndpoint", "localhost:5698"));
                }
            });
            put("local", new HashMap<String, Object>() {

                {
                    put("key", "Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBM" + "UN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk");
                }
            });
        }
    };
    HashMap<String, BsonDocument> schemaMap = new HashMap<String, BsonDocument>();
    schemaMap.put("db.coll", schemaDocument);
    AutoEncryptionSettings.Builder autoEncryptionSettingsBuilder = AutoEncryptionSettings.builder().keyVaultNamespace("keyvault.datakeys").kmsProviders(kmsProviders);
    if (useLocalSchema) {
        autoEncryptionSettingsBuilder.schemaMap(schemaMap);
    }
    clientSettings = getMongoClientSettingsBuilder().codecRegistry(fromRegistries(fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)), MongoClientSettings.getDefaultCodecRegistry())).autoEncryptionSettings(autoEncryptionSettingsBuilder.build()).build();
    autoEncryptingClient = MongoClients.create(clientSettings);
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(getMongoClientSettings()).kmsProviders(kmsProviders).keyVaultNamespace("keyvault.datakeys").build();
    clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
}
Also used : UuidCodec(org.bson.codecs.UuidCodec) HashMap(java.util.HashMap) Fixture.getMongoClientSettings(com.mongodb.client.Fixture.getMongoClientSettings) MongoClientSettings(com.mongodb.MongoClientSettings) BsonString(org.bson.BsonString) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) AutoEncryptionSettings(com.mongodb.AutoEncryptionSettings) HashMap(java.util.HashMap) Map(java.util.Map) Before(org.junit.Before)

Example 43 with BsonString

use of org.bson.BsonString in project mongo-java-driver by mongodb.

the class ClientSideEncryptionExternalKeyVaultTest method testExternal.

@Test
public void testExternal() {
    boolean authExceptionThrown = false;
    MongoCollection<BsonDocument> coll = clientEncrypted.getDatabase("db").getCollection("coll", BsonDocument.class);
    try {
        coll.insertOne(new BsonDocument().append("encrypted", new BsonString("test")));
    } catch (MongoSecurityException mse) {
        authExceptionThrown = true;
    }
    assertEquals(authExceptionThrown, withExternalKeyVault);
    EncryptOptions encryptOptions = new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, Base64.getDecoder().decode("LOCALAAAAAAAAAAAAAAAAA==")));
    authExceptionThrown = false;
    try {
        clientEncryption.encrypt(new BsonString("test"), encryptOptions);
    } catch (MongoSecurityException mse) {
        authExceptionThrown = true;
    }
    assertEquals(authExceptionThrown, withExternalKeyVault);
}
Also used : MongoSecurityException(com.mongodb.MongoSecurityException) BsonDocument(org.bson.BsonDocument) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) BsonString(org.bson.BsonString) BsonBinary(org.bson.BsonBinary) Test(org.junit.Test) ClusterFixture.isClientSideEncryptionTest(com.mongodb.ClusterFixture.isClientSideEncryptionTest)

Example 44 with BsonString

use of org.bson.BsonString in project mongo-java-driver by mongodb.

the class AbstractClientSideEncryptionDeadlockTest method shouldPassAllOutcomes.

@ParameterizedTest
@MethodSource("testArgumentProvider")
public void shouldPassAllOutcomes(final int maxPoolSize, final int expectedNumberOfClientsCreated, final boolean bypassAutoEncryption, final boolean externalKeyVaultClient, final List<ExpectedEvent> expectedEncryptingClientEvents, final List<ExpectedEvent> expectedExternalKeyVaultsClientEvents) {
    AutoEncryptionSettings.Builder autoEncryptionSettingsBuilder = AutoEncryptionSettings.builder().keyVaultNamespace("keyvault.datakeys").kmsProviders(kmsProviders).bypassAutoEncryption(bypassAutoEncryption);
    TestCommandListener externalKeyVaultClientCommandListener = new TestCommandListener(singletonList("commandStartedEvent"), emptyList());
    if (externalKeyVaultClient) {
        autoEncryptionSettingsBuilder.keyVaultMongoClientSettings(getKeyVaultClientSettings(externalKeyVaultClientCommandListener));
    }
    TestCommandListener encryptingClientCommandListener = new TestCommandListener(singletonList("commandStartedEvent"), emptyList());
    encryptingClient = createMongoClient(getClientSettings(maxPoolSize, encryptingClientCommandListener, autoEncryptionSettingsBuilder.build()));
    BsonDocument unencryptedDocument = new BsonDocument("_id", new BsonInt32(0)).append("encrypted", new BsonString("string0"));
    if (bypassAutoEncryption) {
        getMongoClient().getDatabase("db").getCollection("coll", BsonDocument.class).withWriteConcern(WriteConcern.MAJORITY).insertOne(new BsonDocument("_id", new BsonInt32(0)).append("encrypted", cipherText));
    } else {
        encryptingClient.getDatabase("db").getCollection("coll", BsonDocument.class).withWriteConcern(WriteConcern.MAJORITY).insertOne(unencryptedDocument);
    }
    BsonDocument result = encryptingClient.getDatabase("db").getCollection("coll", BsonDocument.class).find().filter(Filters.eq("_id", 0)).first();
    assertEquals(unencryptedDocument, result);
    assertEquals(expectedNumberOfClientsCreated, getNumUniqueClients(encryptingClientCommandListener), "Unique clients");
    assertEventEquality(encryptingClientCommandListener, expectedEncryptingClientEvents);
    assertEventEquality(externalKeyVaultClientCommandListener, expectedExternalKeyVaultsClientEvents);
}
Also used : BsonInt32(org.bson.BsonInt32) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) AutoEncryptionSettings(com.mongodb.AutoEncryptionSettings) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 45 with BsonString

use of org.bson.BsonString in project mongo-java-driver by mongodb.

the class AbstractClientEncryptionCustomEndpointTest method testEndpoint.

private void testEndpoint(final ClientEncryption clientEncryption, @Nullable final Class<? extends RuntimeException> exceptionClass, @Nullable final Class<? extends RuntimeException> wrappedExceptionClass, @Nullable final String messageContainedInException) {
    try {
        BsonBinary dataKeyId = clientEncryption.createDataKey(provider, new DataKeyOptions().masterKey(masterKey));
        assertNull("Expected exception, but encryption succeeded", exceptionClass);
        clientEncryption.encrypt(new BsonString("test"), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(dataKeyId));
    } catch (Exception e) {
        if (exceptionClass == null) {
            throw e;
        }
        assertEquals(exceptionClass, e.getClass());
        assertEquals(wrappedExceptionClass, e.getCause().getClass());
        if (messageContainedInException != null) {
            assertTrue("Actual Error: " + e.getCause().getMessage(), e.getCause().getMessage().contains(messageContainedInException));
        }
    }
}
Also used : EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) BsonBinary(org.bson.BsonBinary) BsonString(org.bson.BsonString) MongoClientException(com.mongodb.MongoClientException) MongoCryptException(com.mongodb.crypt.capi.MongoCryptException) ConnectException(java.net.ConnectException) UnknownHostException(java.net.UnknownHostException) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions)

Aggregations

BsonString (org.bson.BsonString)168 BsonDocument (org.bson.BsonDocument)146 BsonInt32 (org.bson.BsonInt32)54 BsonArray (org.bson.BsonArray)48 Test (org.junit.Test)33 BsonValue (org.bson.BsonValue)31 Document (org.bson.Document)28 BsonInt64 (org.bson.BsonInt64)27 ArrayList (java.util.ArrayList)23 Map (java.util.Map)14 MongoClientSettings (com.mongodb.MongoClientSettings)13 BsonBinary (org.bson.BsonBinary)13 BsonDouble (org.bson.BsonDouble)13 EncryptOptions (com.mongodb.client.model.vault.EncryptOptions)12 HashMap (java.util.HashMap)12 MongoNamespace (com.mongodb.MongoNamespace)11 Test (org.junit.jupiter.api.Test)11 List (java.util.List)10 DataKeyOptions (com.mongodb.client.model.vault.DataKeyOptions)9 BsonBoolean (org.bson.BsonBoolean)9