Search in sources :

Example 46 with MongoNamespace

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

the class ClientSideEncryptionExplicitEncryptionOnlyTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 * Assumes the schema has already been created in MongoDB.
 *
 * @param args ignored args
 */
public static void main(final String[] args) {
    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {

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

                {
                    put("key", localMasterKey);
                }
            });
        }
    };
    MongoNamespace keyVaultNamespace = new MongoNamespace("encryption.testKeyVault");
    MongoClientSettings clientSettings = MongoClientSettings.builder().autoEncryptionSettings(AutoEncryptionSettings.builder().keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).bypassAutoEncryption(true).build()).build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    // Set up the key vault for this example
    MongoCollection<Document> keyVaultCollection = mongoClient.getDatabase(keyVaultNamespace.getDatabaseName()).getCollection(keyVaultNamespace.getCollectionName());
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    keyVaultCollection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Ensure that two data keys cannot share the same keyAltName.
    ObservableSubscriber<String> indexSubscriber = new OperationSubscriber<>();
    keyVaultCollection.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true).partialFilterExpression(Filters.exists("keyAltNames"))).subscribe(indexSubscriber);
    indexSubscriber.await();
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Create the ClientEncryption instance
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://localhost")).build()).keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).build();
    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions());
    // Explicitly encrypt a field
    BsonBinary encryptedFieldValue = clientEncryption.encrypt(new BsonString("123456789"), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(dataKeyId));
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(new Document("encryptedField", encryptedFieldValue)).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    ObservableSubscriber<Document> documentSubscriber = new OperationSubscriber<>();
    collection.find().first().subscribe(documentSubscriber);
    Document doc = documentSubscriber.get().get(0);
    System.out.println(doc.toJson());
    // release resources
    clientEncryption.close();
    mongoClient.close();
}
Also used : HashMap(java.util.HashMap) ClientEncryption(com.mongodb.client.vault.ClientEncryption) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) Document(org.bson.Document) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) InsertOneResult(com.mongodb.client.result.InsertOneResult) IndexOptions(com.mongodb.client.model.IndexOptions) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) BsonBinary(org.bson.BsonBinary) SecureRandom(java.security.SecureRandom) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 47 with MongoNamespace

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

the class ClientSideEncryptionExplicitEncryptionAndDecryptionTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 * Assumes the schema has already been created in MongoDB.
 *
 * @param args ignored args
 */
public static void main(final String[] args) {
    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {

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

                {
                    put("key", localMasterKey);
                }
            });
        }
    };
    MongoNamespace keyVaultNamespace = new MongoNamespace("encryption.testKeyVault");
    MongoClientSettings clientSettings = MongoClientSettings.builder().build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    // Set up the key vault for this example
    MongoCollection<Document> keyVaultCollection = mongoClient.getDatabase(keyVaultNamespace.getDatabaseName()).getCollection(keyVaultNamespace.getCollectionName());
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    keyVaultCollection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Ensure that two data keys cannot share the same keyAltName.
    ObservableSubscriber<String> indexSubscriber = new OperationSubscriber<>();
    keyVaultCollection.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true).partialFilterExpression(Filters.exists("keyAltNames"))).subscribe(indexSubscriber);
    indexSubscriber.await();
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Create the ClientEncryption instance
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://localhost")).build()).keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).build();
    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions());
    // Explicitly encrypt a field
    BsonBinary encryptedFieldValue = clientEncryption.encrypt(new BsonString("123456789"), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(dataKeyId));
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(new Document("encryptedField", encryptedFieldValue)).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    ObservableSubscriber<Document> documentSubscriber = new OperationSubscriber<>();
    collection.find().first().subscribe(documentSubscriber);
    Document doc = documentSubscriber.get().get(0);
    System.out.println(doc.toJson());
    // Explicitly decrypt the field
    System.out.println(clientEncryption.decrypt(new BsonBinary(doc.get("encryptedField", Binary.class).getData())));
    // release resources
    clientEncryption.close();
    mongoClient.close();
}
Also used : HashMap(java.util.HashMap) ClientEncryption(com.mongodb.client.vault.ClientEncryption) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) Document(org.bson.Document) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) InsertOneResult(com.mongodb.client.result.InsertOneResult) IndexOptions(com.mongodb.client.model.IndexOptions) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) BsonBinary(org.bson.BsonBinary) SecureRandom(java.security.SecureRandom) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 48 with MongoNamespace

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

the class MapReducePublisherImpl method createFindOperation.

private AsyncReadOperation<AsyncBatchCursor<T>> createFindOperation(final int initialBatchSize) {
    String dbName = databaseName != null ? databaseName : getNamespace().getDatabaseName();
    FindOptions findOptions = new FindOptions().collation(collation).batchSize(initialBatchSize);
    return getOperations().find(new MongoNamespace(dbName, collectionName), new BsonDocument(), getDocumentClass(), findOptions);
}
Also used : FindOptions(com.mongodb.internal.client.model.FindOptions) BsonDocument(org.bson.BsonDocument) MongoNamespace(com.mongodb.MongoNamespace)

Example 49 with MongoNamespace

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

the class ClientSideEncryptionSessionTest method setUp.

@Before
public void setUp() throws IOException, URISyntaxException {
    assumeTrue(serverVersionAtLeast(4, 2));
    assumeTrue(isClientSideEncryptionTest());
    assumeFalse(isStandalone());
    /* 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<>();
    Map<String, Object> localMasterkey = new HashMap<>();
    Map<String, BsonDocument> schemaMap = new HashMap<>();
    byte[] localMasterkeyBytes = Base64.getDecoder().decode("Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBM" + "UN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk");
    localMasterkey.put("key", localMasterkeyBytes);
    kmsProviders.put("local", localMasterkey);
    schemaMap.put(getDefaultDatabaseName() + "." + COLLECTION_NAME, bsonDocumentFromPath("external-schema.json"));
    AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder().keyVaultNamespace("keyvault.datakeys").kmsProviders(kmsProviders).schemaMap(schemaMap).build();
    MongoClientSettings clientSettings = getMongoClientSettingsBuilder().autoEncryptionSettings(autoEncryptionSettings).build();
    clientEncrypted = MongoClients.create(clientSettings);
    CollectionHelper<BsonDocument> collectionHelper = new CollectionHelper<>(new BsonDocumentCodec(), new MongoNamespace(getDefaultDatabaseName(), COLLECTION_NAME));
    collectionHelper.drop();
    collectionHelper.create();
}
Also used : HashMap(java.util.HashMap) BsonString(org.bson.BsonString) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) BsonDocument(org.bson.BsonDocument) AutoEncryptionSettings(com.mongodb.AutoEncryptionSettings) CollectionHelper(com.mongodb.client.test.CollectionHelper) HashMap(java.util.HashMap) Map(java.util.Map) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) Before(org.junit.Before)

Example 50 with MongoNamespace

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

the class ConnectionsSurvivePrimaryStepDownProseTest method setUp.

@Before
public void setUp() {
    assumeTrue(isDiscoverableReplicaSet() && serverVersionAtLeast(4, 0));
    connectionPoolListener = new TestConnectionPoolListener();
    MongoClientSettings settings = MongoClientSettings.builder(getMongoClientSettings()).retryWrites(false).applyToConnectionPoolSettings(new Block<ConnectionPoolSettings.Builder>() {

        @Override
        public void apply(final ConnectionPoolSettings.Builder builder) {
            builder.addConnectionPoolListener(connectionPoolListener);
        }
    }).build();
    collectionHelper = new CollectionHelper<Document>(new DocumentCodec(), new MongoNamespace(getDefaultDatabaseName(), COLLECTION_NAME));
    client = MongoClients.create(settings);
    MongoDatabase database = client.getDatabase(getDefaultDatabaseName());
    collection = client.getDatabase(getDefaultDatabaseName()).getCollection(COLLECTION_NAME);
    collection.withWriteConcern(WriteConcern.MAJORITY).drop();
    database.withWriteConcern(WriteConcern.MAJORITY).createCollection(COLLECTION_NAME);
}
Also used : TestConnectionPoolListener(com.mongodb.internal.connection.TestConnectionPoolListener) DocumentCodec(org.bson.codecs.DocumentCodec) Block(com.mongodb.Block) Fixture.getMongoClientSettings(com.mongodb.client.Fixture.getMongoClientSettings) MongoClientSettings(com.mongodb.MongoClientSettings) Document(org.bson.Document) MongoNamespace(com.mongodb.MongoNamespace) ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings) Before(org.junit.Before)

Aggregations

MongoNamespace (com.mongodb.MongoNamespace)55 BsonDocument (org.bson.BsonDocument)34 BsonString (org.bson.BsonString)21 Document (org.bson.Document)20 Before (org.junit.Before)17 MongoClientSettings (com.mongodb.MongoClientSettings)15 BsonValue (org.bson.BsonValue)13 ArrayList (java.util.ArrayList)10 HashMap (java.util.HashMap)10 Map (java.util.Map)10 BsonDocumentCodec (org.bson.codecs.BsonDocumentCodec)10 DocumentCodec (org.bson.codecs.DocumentCodec)8 CollectionHelper (com.mongodb.client.test.CollectionHelper)7 Test (org.junit.jupiter.api.Test)7 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)6 ConnectionString (com.mongodb.ConnectionString)6 Test (org.junit.Test)6 IndexOptions (com.mongodb.client.model.IndexOptions)5 AggregateToCollectionOperation (com.mongodb.internal.operation.AggregateToCollectionOperation)5 DisplayName (org.junit.jupiter.api.DisplayName)5