Search in sources :

Example 1 with MongoClientSettings

use of com.mongodb.MongoClientSettings 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 2 with MongoClientSettings

use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.

the class ClientSideEncryptionExternalKeyVaultTest method setUp.

@Before
public void setUp() throws IOException, URISyntaxException {
    assumeTrue(serverVersionAtLeast(4, 2));
    assumeTrue("Encryption test with external keyVault is disabled", isClientSideEncryptionTest());
    /* Step 1: get unencrypted client and recreate keys collection */
    client = getMongoClient();
    MongoDatabase keyvaultDatabase = client.getDatabase("keyvault");
    MongoCollection<BsonDocument> datakeys = keyvaultDatabase.getCollection("datakeys", BsonDocument.class).withWriteConcern(WriteConcern.MAJORITY);
    datakeys.drop();
    datakeys.insertOne(bsonDocumentFromPath("external-key.json"));
    /* Step 2: create encryption objects. */
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>();
    Map<String, Object> localMasterkey = new HashMap<String, Object>();
    Map<String, BsonDocument> schemaMap = new HashMap<String, BsonDocument>();
    byte[] localMasterkeyBytes = Base64.getDecoder().decode("Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBM" + "UN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk");
    localMasterkey.put("key", localMasterkeyBytes);
    kmsProviders.put("local", localMasterkey);
    schemaMap.put("db.coll", bsonDocumentFromPath("external-schema.json"));
    AutoEncryptionSettings.Builder autoEncryptionSettingsBuilder = AutoEncryptionSettings.builder().keyVaultNamespace("keyvault.datakeys").kmsProviders(kmsProviders).schemaMap(schemaMap);
    MongoClientSettings externalClientSettings = null;
    if (withExternalKeyVault) {
        externalClientSettings = getMongoClientSettingsBuilder().credential(MongoCredential.createCredential("fake-user", "admin", "fake-pwd".toCharArray())).build();
        autoEncryptionSettingsBuilder.keyVaultMongoClientSettings(externalClientSettings);
    }
    AutoEncryptionSettings autoEncryptionSettings = autoEncryptionSettingsBuilder.build();
    MongoClientSettings clientSettings = getMongoClientSettingsBuilder().autoEncryptionSettings(autoEncryptionSettings).build();
    clientEncrypted = MongoClients.create(clientSettings);
    ClientEncryptionSettings.Builder clientEncryptionSettingsBuilder = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(getMongoClientSettingsBuilder().build()).kmsProviders(kmsProviders).keyVaultNamespace("keyvault.datakeys");
    if (withExternalKeyVault) {
        clientEncryptionSettingsBuilder.keyVaultMongoClientSettings(externalClientSettings);
    }
    ClientEncryptionSettings clientEncryptionSettings = clientEncryptionSettingsBuilder.build();
    clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
}
Also used : HashMap(java.util.HashMap) BsonString(org.bson.BsonString) MongoClientSettings(com.mongodb.MongoClientSettings) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) BsonDocument(org.bson.BsonDocument) AutoEncryptionSettings(com.mongodb.AutoEncryptionSettings) HashMap(java.util.HashMap) Map(java.util.Map) Before(org.junit.Before)

Example 3 with MongoClientSettings

use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.

the class ServerDiscoveryAndMonitoringProseTests method testHeartbeatFrequency.

@Test
@SuppressWarnings("try")
public void testHeartbeatFrequency() throws InterruptedException {
    assumeFalse(isServerlessTest());
    CountDownLatch latch = new CountDownLatch(5);
    MongoClientSettings settings = getMongoClientSettingsBuilder().applyToServerSettings(new Block<ServerSettings.Builder>() {

        @Override
        public void apply(final ServerSettings.Builder builder) {
            builder.heartbeatFrequency(50, TimeUnit.MILLISECONDS);
            builder.addServerMonitorListener(new ServerMonitorListener() {

                @Override
                public void serverHeartbeatSucceeded(final ServerHeartbeatSucceededEvent event) {
                    latch.countDown();
                }
            });
        }
    }).build();
    try (MongoClient ignored = MongoClients.create(settings)) {
        assertTrue("Took longer than expected to reach expected number of hearbeats", latch.await(500, TimeUnit.MILLISECONDS));
    }
}
Also used : ServerSettings(com.mongodb.connection.ServerSettings) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) Block(com.mongodb.Block) MongoClientSettings(com.mongodb.MongoClientSettings) CountDownLatch(java.util.concurrent.CountDownLatch) ServerHeartbeatSucceededEvent(com.mongodb.event.ServerHeartbeatSucceededEvent) ServerMonitorListener(com.mongodb.event.ServerMonitorListener) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) Test(org.junit.Test)

Example 4 with MongoClientSettings

use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.

the class ServerDiscoveryAndMonitoringProseTests method testRTTUpdates.

@Test
public void testRTTUpdates() throws InterruptedException {
    assumeTrue(isStandalone());
    assumeTrue(serverVersionAtLeast(4, 4));
    List<ServerDescriptionChangedEvent> events = synchronizedList(new ArrayList<>());
    MongoClientSettings settings = getMongoClientSettingsBuilder().applicationName("streamingRttTest").applyToServerSettings(new Block<ServerSettings.Builder>() {

        @Override
        public void apply(final ServerSettings.Builder builder) {
            builder.heartbeatFrequency(50, TimeUnit.MILLISECONDS);
            builder.addServerListener(new ServerListener() {

                @Override
                public void serverDescriptionChanged(final ServerDescriptionChangedEvent event) {
                    events.add(event);
                }
            });
        }
    }).build();
    try (MongoClient client = MongoClients.create(settings)) {
        client.getDatabase("admin").runCommand(new Document("ping", 1));
        Thread.sleep(250);
        assertTrue(events.size() >= 1);
        events.forEach(event -> assertTrue(event.getNewDescription().getRoundTripTimeNanos() > 0));
        configureFailPoint(parse(format("{" + "configureFailPoint: \"failCommand\"," + "mode: {times: 1000}," + " data: {" + "   failCommands: [\"%s\", \"%s\"]," + "   blockConnection: true," + "   blockTimeMS: 100," + "   appName: \"streamingRttTest\"" + "  }" + "}", LEGACY_HELLO, HELLO)));
        long startTime = System.currentTimeMillis();
        while (true) {
            long rttMillis = NANOSECONDS.toMillis(client.getClusterDescription().getServerDescriptions().get(0).getRoundTripTimeNanos());
            if (rttMillis > 50) {
                break;
            }
            assertFalse(System.currentTimeMillis() - startTime > 1000);
            // noinspection BusyWait
            Thread.sleep(50);
        }
    } finally {
        disableFailPoint("failCommand");
    }
}
Also used : ServerDescriptionChangedEvent(com.mongodb.event.ServerDescriptionChangedEvent) ServerSettings(com.mongodb.connection.ServerSettings) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) Block(com.mongodb.Block) MongoClientSettings(com.mongodb.MongoClientSettings) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) ServerListener(com.mongodb.event.ServerListener) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) Test(org.junit.Test)

Example 5 with MongoClientSettings

use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.

the class ServerDiscoveryAndMonitoringProseTests method testConnectionPoolManagement.

/**
 * See
 * <a href="https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring-tests.rst#connection-pool-management">Connection Pool Management</a>.
 */
@Test
@Ignore
@SuppressWarnings("try")
public void testConnectionPoolManagement() throws InterruptedException {
    assumeTrue(serverVersionAtLeast(4, 3));
    assumeFalse(isServerlessTest());
    BlockingQueue<Object> events = new LinkedBlockingQueue<>();
    ServerMonitorListener serverMonitorListener = new ServerMonitorListener() {

        @Override
        public void serverHeartbeatSucceeded(final ServerHeartbeatSucceededEvent event) {
            put(events, event);
        }

        @Override
        public void serverHeartbeatFailed(final ServerHeartbeatFailedEvent event) {
            put(events, event);
        }
    };
    ConnectionPoolListener connectionPoolListener = new ConnectionPoolListener() {

        @Override
        public void connectionPoolReady(final ConnectionPoolReadyEvent event) {
            put(events, event);
        }

        @Override
        public void connectionPoolCleared(final ConnectionPoolClearedEvent event) {
            put(events, event);
        }
    };
    String appName = "SDAMPoolManagementTest";
    MongoClientSettings clientSettings = getMongoClientSettingsBuilder().applicationName(appName).applyToClusterSettings(ClusterFixture::setDirectConnection).applyToServerSettings(builder -> builder.heartbeatFrequency(100, TimeUnit.MILLISECONDS).addServerMonitorListener(serverMonitorListener)).applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(connectionPoolListener)).build();
    try (MongoClient unused = MongoClients.create(clientSettings)) {
        /* Note that ServerHeartbeatSucceededEvent type is sometimes allowed but never required.
             * This is because DefaultServerMonitor does not send such events in situations when a server check happens as part
             * of a connection handshake. */
        assertPoll(events, ServerHeartbeatSucceededEvent.class, singleton(ConnectionPoolReadyEvent.class));
        configureFailPoint(new BsonDocument().append("configureFailPoint", new BsonString("failCommand")).append("mode", new BsonDocument().append("times", new BsonInt32(2))).append("data", new BsonDocument().append("failCommands", new BsonArray(asList(new BsonString("isMaster"), new BsonString("hello")))).append("errorCode", new BsonInt32(1234)).append("appName", new BsonString(appName))));
        assertPoll(events, ServerHeartbeatSucceededEvent.class, new HashSet<>(asList(ServerHeartbeatFailedEvent.class, ConnectionPoolClearedEvent.class)));
        assertPoll(events, null, new HashSet<>(asList(ServerHeartbeatSucceededEvent.class, ConnectionPoolReadyEvent.class)));
    } finally {
        disableFailPoint("failCommand");
    }
}
Also used : Document(org.bson.Document) ServerListener(com.mongodb.event.ServerListener) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) Collections.singleton(java.util.Collections.singleton) Arrays.asList(java.util.Arrays.asList) BsonArray(org.bson.BsonArray) ClusterFixture.isStandalone(com.mongodb.ClusterFixture.isStandalone) Assert.fail(org.junit.Assert.fail) ServerDescriptionChangedEvent(com.mongodb.event.ServerDescriptionChangedEvent) ServerHeartbeatSucceededEvent(com.mongodb.event.ServerHeartbeatSucceededEvent) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) BsonNull(org.bson.BsonNull) Collections.synchronizedList(java.util.Collections.synchronizedList) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) String.format(java.lang.String.format) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Block(com.mongodb.Block) Assert.assertFalse(org.junit.Assert.assertFalse) Optional(java.util.Optional) ClusterFixture.configureFailPoint(com.mongodb.ClusterFixture.configureFailPoint) Assume.assumeTrue(org.junit.Assume.assumeTrue) MongoClientSettings(com.mongodb.MongoClientSettings) Fixture.getDefaultDatabaseName(com.mongodb.client.Fixture.getDefaultDatabaseName) BsonDocument.parse(org.bson.BsonDocument.parse) NANOSECONDS(java.util.concurrent.TimeUnit.NANOSECONDS) Assume.assumeFalse(org.junit.Assume.assumeFalse) BsonString(org.bson.BsonString) ServerSettings(com.mongodb.connection.ServerSettings) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterFixture(com.mongodb.ClusterFixture) ServerHeartbeatFailedEvent(com.mongodb.event.ServerHeartbeatFailedEvent) Logger(com.mongodb.diagnostics.logging.Logger) MongoInterruptedException(com.mongodb.MongoInterruptedException) ConnectionPoolListener(com.mongodb.event.ConnectionPoolListener) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Timeout(com.mongodb.internal.Timeout) TimeUnit(java.util.concurrent.TimeUnit) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ServerMonitorListener(com.mongodb.event.ServerMonitorListener) Ignore(org.junit.Ignore) Loggers(com.mongodb.diagnostics.logging.Loggers) ClusterFixture.serverVersionAtLeast(com.mongodb.ClusterFixture.serverVersionAtLeast) Nullable(com.mongodb.lang.Nullable) BsonInt32(org.bson.BsonInt32) ClusterFixture.disableFailPoint(com.mongodb.ClusterFixture.disableFailPoint) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) ServerHeartbeatFailedEvent(com.mongodb.event.ServerHeartbeatFailedEvent) BsonString(org.bson.BsonString) MongoClientSettings(com.mongodb.MongoClientSettings) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ServerHeartbeatSucceededEvent(com.mongodb.event.ServerHeartbeatSucceededEvent) ServerMonitorListener(com.mongodb.event.ServerMonitorListener) BsonInt32(org.bson.BsonInt32) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) BsonDocument(org.bson.BsonDocument) ConnectionPoolListener(com.mongodb.event.ConnectionPoolListener) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) Ignore(org.junit.Ignore) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) Test(org.junit.Test)

Aggregations

MongoClientSettings (com.mongodb.MongoClientSettings)75 Test (org.junit.jupiter.api.Test)24 BsonString (org.bson.BsonString)21 Map (java.util.Map)20 Test (org.junit.Test)20 HashMap (java.util.HashMap)19 Document (org.bson.Document)19 BsonDocument (org.bson.BsonDocument)18 ServerAddress (com.mongodb.ServerAddress)17 AutoEncryptionSettings (com.mongodb.AutoEncryptionSettings)14 Before (org.junit.Before)14 MongoNamespace (com.mongodb.MongoNamespace)13 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)12 ConnectionString (com.mongodb.ConnectionString)12 MongoClientFactoryBean (org.springframework.data.mongodb.core.MongoClientFactoryBean)10 Block (com.mongodb.Block)8 Fixture.getMongoClientSettingsBuilder (com.mongodb.client.Fixture.getMongoClientSettingsBuilder)8 SecureRandom (java.security.SecureRandom)8 TimeUnit (java.util.concurrent.TimeUnit)8 ClusterFixture.isServerlessTest (com.mongodb.ClusterFixture.isServerlessTest)7