Search in sources :

Example 11 with BsonBinary

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

the class ClientSideEncryptionCorpusTest method testCorpus.

@Test
public void testCorpus() throws IOException, URISyntaxException {
    // Step 5: Iterate over corpus
    BsonDocument corpus = bsonDocumentFromPath("corpus.json");
    BsonDocument corpusCopied = new BsonDocument();
    for (String field : corpus.keySet()) {
        if (!corpus.get(field).isDocument()) {
            corpusCopied.append(field, corpus.get(field));
            continue;
        }
        BsonDocument fieldDocument = corpus.getDocument(field).clone();
        String kms = fieldDocument.getString("kms").getValue();
        String abbreviatedAlgorithName = fieldDocument.getString("algo").getValue();
        String method = fieldDocument.getString("method").getValue();
        String identifier = fieldDocument.getString("identifier").getValue();
        boolean allowed = fieldDocument.getBoolean("allowed").getValue();
        BsonValue value = fieldDocument.get("value");
        byte[] awsKeyId = Base64.getDecoder().decode("AWSAAAAAAAAAAAAAAAAAAA==");
        byte[] azureKeyId = Base64.getDecoder().decode("AZUREAAAAAAAAAAAAAAAAA==");
        byte[] gcpKeyId = Base64.getDecoder().decode("GCPAAAAAAAAAAAAAAAAAAA==");
        byte[] kmipKeyId = Base64.getDecoder().decode("KMIPAAAAAAAAAAAAAAAAAA==");
        byte[] localKeyId = Base64.getDecoder().decode("LOCALAAAAAAAAAAAAAAAAA==");
        if (method.equals("auto")) {
            corpusCopied.append(field, corpus.get(field));
            continue;
        }
        if (!method.equals("explicit")) {
            throw new UnsupportedOperationException("Unsupported method: " + method);
        }
        String fullAlgorithmName = "AEAD_AES_256_CBC_HMAC_SHA_512-";
        if (abbreviatedAlgorithName.equals("rand")) {
            fullAlgorithmName += "Random";
        } else if (abbreviatedAlgorithName.equals("det")) {
            fullAlgorithmName += "Deterministic";
        } else {
            throw new UnsupportedOperationException("Unsupported algorithm: " + abbreviatedAlgorithName);
        }
        EncryptOptions opts = new EncryptOptions(fullAlgorithmName);
        if (identifier.equals("id")) {
            switch(kms) {
                case "aws":
                    opts.keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, awsKeyId));
                    break;
                case "azure":
                    opts.keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, azureKeyId));
                    break;
                case "gcp":
                    opts.keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, gcpKeyId));
                    break;
                case "kmip":
                    opts.keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, kmipKeyId));
                    break;
                case "local":
                    opts.keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, localKeyId));
                    break;
                default:
                    throw new UnsupportedOperationException("Unsupported provider: " + kms);
            }
        } else if (identifier.equals("altname")) {
            opts.keyAltName(kms);
        } else {
            throw new UnsupportedOperationException("Unsupported identifier: " + identifier);
        }
        try {
            BsonValue encryptedValue = clientEncryption.encrypt(value, opts);
            fieldDocument.put("value", encryptedValue);
            corpusCopied.append(field, fieldDocument);
        } catch (MongoException e) {
            if (allowed) {
                throw e;
            }
            corpusCopied.append(field, fieldDocument);
        }
    }
    // Step 6: insert corpusCopied
    MongoCollection<BsonDocument> encryptedCollection = autoEncryptingClient.getDatabase("db").getCollection("coll", BsonDocument.class);
    encryptedCollection.insertOne(corpusCopied);
    // Step 7: check the auto decrypted document
    BsonDocument corpusDecrypted = encryptedCollection.find(new BsonDocument()).first();
    assertEquals(corpus, corpusDecrypted);
    // Step 8: check the document with an unencrypted client
    MongoCollection<BsonDocument> coll = client.getDatabase("db").getCollection("coll", BsonDocument.class);
    BsonDocument corpusEncryptedActual = coll.find(new BsonDocument()).first();
    BsonDocument corpusEncryptedExpected = bsonDocumentFromPath("corpus-encrypted.json");
    for (String field : corpusEncryptedExpected.keySet()) {
        if (field.equals("_id") || field.equals("altname_aws") || field.equals("altname_local")) {
            continue;
        }
        boolean allowed = corpusEncryptedActual.getDocument(field).getBoolean("allowed").getValue();
        String algorithm = corpusEncryptedActual.getDocument(field).getString("algo").getValue();
        BsonValue actualValue = corpusEncryptedActual.getDocument(field).get("value");
        BsonValue expectedValue = corpusEncryptedExpected.getDocument(field).get("value");
        if (algorithm.equals("det")) {
            assertEquals(actualValue, expectedValue);
        } else if (algorithm.equals("rand")) {
            if (allowed) {
                assertNotEquals(actualValue, expectedValue);
            }
        } else {
            throw new UnsupportedOperationException("Unsupported algorithm type: " + algorithm);
        }
        if (allowed) {
            BsonValue decrypted = clientEncryption.decrypt(actualValue.asBinary());
            assertEquals("Values should be equal for field " + field, clientEncryption.decrypt(expectedValue.asBinary()), decrypted);
        } else {
            assertEquals("Values should be equal for field " + field, expectedValue, actualValue);
        }
    }
}
Also used : MongoException(com.mongodb.MongoException) BsonDocument(org.bson.BsonDocument) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) BsonBinary(org.bson.BsonBinary) BsonString(org.bson.BsonString) BsonValue(org.bson.BsonValue) Test(org.junit.Test)

Example 12 with BsonBinary

use of org.bson.BsonBinary 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 13 with BsonBinary

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

the class AbstractUuidRepresentationTest method shouldDecodePojoWithLegacyUuidRepresentation.

@Test
public void shouldDecodePojoWithLegacyUuidRepresentation() {
    bsonDocumentCollection.insertOne(new BsonDocument("_id", new BsonBinary(uuid, uuidRepresentation == UuidRepresentation.UNSPECIFIED || uuidRepresentation == UuidRepresentation.STANDARD ? UuidRepresentation.PYTHON_LEGACY : uuidRepresentation)));
    try {
        UuidIdPojo document = uuidIdPojoCollection.find().first();
        assertNotNull(document);
        assertEquals(uuid, document.getId());
    } catch (BSONException e) {
        assertNotEquals(UuidRepresentation.C_SHARP_LEGACY, uuidRepresentation);
        assertNotEquals(UuidRepresentation.PYTHON_LEGACY, uuidRepresentation);
    }
}
Also used : BsonDocument(org.bson.BsonDocument) BsonBinary(org.bson.BsonBinary) BSONException(org.bson.BSONException) Test(org.junit.Test)

Example 14 with BsonBinary

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

the class JsonReader method visitBinDataExtendedJson.

private BsonBinary visitBinDataExtendedJson(final String firstKey) {
    Mark mark = new Mark();
    try {
        verifyToken(JsonTokenType.COLON);
        if (firstKey.equals("$binary")) {
            JsonToken nextToken = popToken();
            if (nextToken.getType() == JsonTokenType.BEGIN_OBJECT) {
                JsonToken nameToken = popToken();
                String firstNestedKey = nameToken.getValue(String.class);
                byte[] data;
                byte type;
                if (firstNestedKey.equals("base64")) {
                    verifyToken(JsonTokenType.COLON);
                    data = Base64.getDecoder().decode(readStringFromExtendedJson());
                    verifyToken(JsonTokenType.COMMA);
                    verifyString("subType");
                    verifyToken(JsonTokenType.COLON);
                    type = readBinarySubtypeFromExtendedJson();
                } else if (firstNestedKey.equals("subType")) {
                    verifyToken(JsonTokenType.COLON);
                    type = readBinarySubtypeFromExtendedJson();
                    verifyToken(JsonTokenType.COMMA);
                    verifyString("base64");
                    verifyToken(JsonTokenType.COLON);
                    data = Base64.getDecoder().decode(readStringFromExtendedJson());
                } else {
                    throw new JsonParseException("Unexpected key for $binary: " + firstNestedKey);
                }
                verifyToken(JsonTokenType.END_OBJECT);
                verifyToken(JsonTokenType.END_OBJECT);
                return new BsonBinary(type, data);
            } else {
                mark.reset();
                return visitLegacyBinaryExtendedJson(firstKey);
            }
        } else {
            mark.reset();
            return visitLegacyBinaryExtendedJson(firstKey);
        }
    } finally {
        mark.discard();
    }
}
Also used : BsonBinary(org.bson.BsonBinary) BsonReaderMark(org.bson.BsonReaderMark)

Example 15 with BsonBinary

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

the class BasicDBObjectTest method toJsonShouldRenderUuidAsStandard.

@Test
public void toJsonShouldRenderUuidAsStandard() {
    UUID uuid = UUID.randomUUID();
    BasicDBObject doc = new BasicDBObject("_id", uuid);
    String json = doc.toJson();
    assertEquals(new BsonDocument("_id", new BsonBinary(uuid)), BsonDocument.parse(json));
}
Also used : BsonDocument(org.bson.BsonDocument) BsonBinary(org.bson.BsonBinary) UUID(java.util.UUID) Test(org.junit.Test)

Aggregations

BsonBinary (org.bson.BsonBinary)78 Test (org.junit.Test)51 BsonDocument (org.bson.BsonDocument)32 BsonString (org.bson.BsonString)16 Document (org.bson.Document)16 EncryptOptions (com.mongodb.client.model.vault.EncryptOptions)13 DataKeyOptions (com.mongodb.client.model.vault.DataKeyOptions)11 BSONException (org.bson.BSONException)9 Map (java.util.Map)8 BasicDBObject (com.mongodb.BasicDBObject)6 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)6 ConnectionString (com.mongodb.ConnectionString)6 MongoClientSettings (com.mongodb.MongoClientSettings)6 SecureRandom (java.security.SecureRandom)6 HashMap (java.util.HashMap)6 ClientEncryption (com.mongodb.client.vault.ClientEncryption)5 UUID (java.util.UUID)5 Binary (org.bson.types.Binary)5 MongoNamespace (com.mongodb.MongoNamespace)4 IndexOptions (com.mongodb.client.model.IndexOptions)4