diff --git a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md index 6ba5e91018f4f..8725d1b06b22e 100644 --- a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md @@ -5,8 +5,10 @@ #### Features Added #### Breaking Changes +* Reading legacy mixed-type arrays with unencrypted scalars now fails by default with `IllegalStateException`; see [migration and opt-out guidance](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/cosmos/azure-cosmos-encryption/README.md#legacy-mixed-type-arrays). - See [PR 51247](https://github.com/Azure/azure-sdk-for-java/pull/51247) #### Bugs Fixed +* Fixed client-side encryption and decryption of mixed-type arrays for item and PATCH operations. - See [PR 51247](https://github.com/Azure/azure-sdk-for-java/pull/51247) #### Other Changes diff --git a/sdk/cosmos/azure-cosmos-encryption/README.md b/sdk/cosmos/azure-cosmos-encryption/README.md index f7b6414ad14f6..cf267ba84a866 100644 --- a/sdk/cosmos/azure-cosmos-encryption/README.md +++ b/sdk/cosmos/azure-cosmos-encryption/README.md @@ -151,6 +151,52 @@ However, because Azure Cosmos DB is accessed via network calls there are client- - [Troubleshooting Guide][troubleshooting] covers common issues, workarounds, diagnostic steps, and tools when you use Azure Cosmos DB Java SDK v4 with Azure Cosmos DB SQL API accounts. +### Legacy mixed-type arrays + +Earlier SDK versions could leave scalar array elements unencrypted inside an encrypted property when the first +array element was an object or another array. For example, with `/sensitive` included in the encryption policy, +writing `[{"label":"secret"},42]` encrypted `"secret"` but left `42` in plaintext. This can occur in nested arrays +as well. The old reader skipped the same scalar elements, so reads could succeed despite the missing encryption. + +The corrected reader decrypts every non-null scalar array element. If an element cannot be decrypted, it throws +`IllegalStateException` with the encrypted property name, the array-local index, migration guidance, and the original +exception as its cause. It does not silently return the value as plaintext. This failure can also indicate incorrect +keys or damaged ciphertext; it is not proof that the item was written by an older SDK. + +#### Temporary compatibility opt-out + +The fix is enabled by default. To temporarily restore legacy array traversal for **both reads and writes** +(including PATCH), set either of the following before creating encryption clients: + +- JVM system property: `-DCOSMOS.ENCRYPTION_MIXED_ARRAYS_ENABLED=false` +- Environment variable: `COSMOS_ENCRYPTION_MIXED_ARRAYS_ENABLED=false` + +A non-empty JVM property takes precedence over the environment variable. Values are case-insensitive `true` or +`false`; invalid values are rejected rather than silently disabling encryption. Each encryption client +captures the setting when it is created and shares it with its container processors; restart the application +to change modes consistently. +The setting is implemented in the encryption package and does not require a new `azure-cosmos` config getter. + +**Warning:** legacy mode restores the first-element-based behavior, including the bug that leaves scalar elements +unencrypted after an object or array. It logs a warning once per JVM and is a migration bridge, not a long-term fix. +It also retains legacy failures for unsupported scalar-first mixed arrays. Legacy readers skip scalar elements +after a leading container, so they cannot correctly read mixed arrays already written with the fix enabled. +Do not use the two modes interchangeably on the same data or switch to legacy mode after writing corrected data. +Opt-out is an explicit traversal choice, not a fallback for decoding or authentication failures. + +If you confirm that an item contains legacy mixed-type arrays: + +1. Coordinate a migration so old clients do not read rewritten items or write more legacy items during the cutover. +2. Read the affected items with the SDK version that wrote them, or with the compatibility opt-out in a separate + migration reader process, to recover their decrypted values. +3. Pass the decrypted items to a separate encryption-enabled writer process with the fix enabled and rewrite the + complete items. Use ETags to prevent overwriting concurrent changes; do not first read the legacy items through + the corrected reader. Do not copy raw encrypted values into the writer. +4. Resume normal access with the fix enabled after the affected items have been migrated. + +These items are partially encrypted, not wholly unencrypted: existing encrypted fields still require decryption. +Do not treat authentication failures as plaintext or assume that raw stored items can be rewritten without decryption. + ### Enable Client Logging Azure Cosmos DB Java SDK v4 uses SLF4j as the logging facade that supports logging into popular logging frameworks such as log4j and logback. diff --git a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/CosmosEncryptionAsyncClient.java b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/CosmosEncryptionAsyncClient.java index 64fa7b7afad11..9efb9fa3362f8 100644 --- a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/CosmosEncryptionAsyncClient.java +++ b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/CosmosEncryptionAsyncClient.java @@ -10,16 +10,17 @@ import com.azure.cosmos.CosmosAsyncClientEncryptionKey; import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosAsyncDatabase; -import com.azure.cosmos.CosmosBridgeInternal; import com.azure.cosmos.CosmosException; import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.encryption.implementation.Constants; +import com.azure.cosmos.encryption.implementation.EncryptionConfigs; import com.azure.cosmos.encryption.implementation.EncryptionImplementationBridgeHelpers; import com.azure.cosmos.encryption.implementation.keyprovider.EncryptionKeyStoreProviderImpl; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.RequestOptions; import com.azure.cosmos.implementation.Utils; +import com.azure.cosmos.implementation.UserAgentFeatureFlags; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.azure.cosmos.implementation.caches.AsyncCache; import com.azure.cosmos.models.CosmosClientEncryptionKeyProperties; @@ -46,6 +47,7 @@ public final class CosmosEncryptionAsyncClient implements Closeable { private final KeyEncryptionKeyResolver keyEncryptionKeyResolver; private final String keyEncryptionKeyResolverName; private final EncryptionKeyStoreProviderImpl encryptionKeyStoreProviderImpl; + private final boolean mixedArrayEncryptionEnabled; private final static ImplementationBridgeHelpers.CosmosAsyncClientEncryptionKeyHelper.CosmosAsyncClientEncryptionKeyAccessor cosmosAsyncClientEncryptionKeyAccessor = ImplementationBridgeHelpers.CosmosAsyncClientEncryptionKeyHelper.getCosmosAsyncClientEncryptionKeyAccessor(); private final static ImplementationBridgeHelpers.CosmosAsyncClientHelper.CosmosAsyncClientAccessor cosmosAsyncClientAccessor = ImplementationBridgeHelpers.CosmosAsyncClientHelper.getCosmosAsyncClientAccessor(); @@ -62,6 +64,7 @@ public final class CosmosEncryptionAsyncClient implements Closeable { if (StringUtils.isEmpty(keyEncryptionKeyResolverName)) { throw new IllegalArgumentException("keyEncryptionKeyResolverName is null"); } + this.mixedArrayEncryptionEnabled = EncryptionConfigs.isMixedArrayEncryptionEnabled(); this.cosmosAsyncClient = cosmosAsyncClient; this.keyEncryptionKeyResolver = keyEncryptionKeyResolver; this.clientEncryptionKeyPropertiesCacheByKeyId = new AsyncCache<>(); @@ -93,6 +96,10 @@ EncryptionKeyStoreProviderImpl getEncryptionKeyStoreProviderImpl() { return encryptionKeyStoreProviderImpl; } + boolean isMixedArrayEncryptionEnabled() { + return this.mixedArrayEncryptionEnabled; + } + Mono getContainerPropertiesAsync( CosmosAsyncContainer container, boolean shouldForceRefresh) { @@ -195,9 +202,11 @@ public CosmosAsyncClient getCosmosAsyncClient() { private void appendEncryptionUserAgentSuffix() { try { - CosmosBridgeInternal - .getAsyncDocumentClient(this.cosmosAsyncClient) - .appendUserAgentSuffix(Constants.USER_AGENT_SUFFIX); + cosmosAsyncClientAccessor.appendUserAgentSuffix(this.cosmosAsyncClient, Constants.USER_AGENT_SUFFIX); + if (!this.mixedArrayEncryptionEnabled) { + cosmosAsyncClientAccessor.addUserAgentFeatureFlag(this.cosmosAsyncClient, + UserAgentFeatureFlags.EncryptionMixedArrayOptOut); + } } catch (Exception e) { LOGGER.warn("Failed to append encryption SDK user agent suffix", e); } @@ -273,6 +282,11 @@ public Mono getContainerPropertiesAsync(CosmosEncrypt public EncryptionKeyStoreProviderImpl getEncryptionKeyStoreProviderImpl(CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient) { return cosmosEncryptionAsyncClient.getEncryptionKeyStoreProviderImpl(); } + + @Override + public boolean isMixedArrayEncryptionEnabled(CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient) { + return cosmosEncryptionAsyncClient.isMixedArrayEncryptionEnabled(); + } }); } } diff --git a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionConfigs.java b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionConfigs.java new file mode 100644 index 0000000000000..ca8656b9d0615 --- /dev/null +++ b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionConfigs.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.encryption.implementation; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Internal configuration for the encryption SDK. + */ +public final class EncryptionConfigs { + static final String MIXED_ARRAYS_ENABLED = "COSMOS.ENCRYPTION_MIXED_ARRAYS_ENABLED"; + static final String MIXED_ARRAYS_ENABLED_VARIABLE = "COSMOS_ENCRYPTION_MIXED_ARRAYS_ENABLED"; + private static final Logger LOGGER = LoggerFactory.getLogger(EncryptionConfigs.class); + private static final AtomicBoolean LEGACY_MODE_WARNING_LOGGED = new AtomicBoolean(false); + + private EncryptionConfigs() { + } + + /** + * Resolves the mixed-array encryption setting, giving the JVM property precedence over the environment variable. + * + * @return whether corrected mixed-array traversal is enabled + */ + public static boolean isMixedArrayEncryptionEnabled() { + return isMixedArrayEncryptionEnabled(System.getProperty(MIXED_ARRAYS_ENABLED), + System.getenv(MIXED_ARRAYS_ENABLED_VARIABLE)); + } + + static boolean isMixedArrayEncryptionEnabled(String systemPropertyValue, String environmentVariableValue) { + String value = systemPropertyValue == null || systemPropertyValue.isEmpty() + ? environmentVariableValue : systemPropertyValue; + if (value == null || value.isEmpty() || "true".equalsIgnoreCase(value)) { + return true; + } + if ("false".equalsIgnoreCase(value)) { + if (LEGACY_MODE_WARNING_LOGGED.compareAndSet(false, true)) { + LOGGER.warn("Mixed-array encryption is disabled through {} or {}. Legacy traversal can leave " + + "scalar array elements unencrypted and cannot correctly read mixed arrays written with " + + "the fix enabled. Use this temporary compatibility mode only until legacy data is migrated.", + MIXED_ARRAYS_ENABLED, MIXED_ARRAYS_ENABLED_VARIABLE); + } + return false; + } + throw new IllegalArgumentException("Invalid " + MIXED_ARRAYS_ENABLED + " or " + + MIXED_ARRAYS_ENABLED_VARIABLE + " setting. Only 'true' or 'false' are supported."); + } +} diff --git a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionImplementationBridgeHelpers.java b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionImplementationBridgeHelpers.java index 372af741f80db..dbaa0661e2c2f 100644 --- a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionImplementationBridgeHelpers.java +++ b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionImplementationBridgeHelpers.java @@ -104,6 +104,8 @@ Mono getContainerPropertiesAsync( boolean shouldForceRefresh); EncryptionKeyStoreProviderImpl getEncryptionKeyStoreProviderImpl(CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient); + + boolean isMixedArrayEncryptionEnabled(CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient); } } diff --git a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionProcessor.java b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionProcessor.java index 07656f30264d6..8f6ccff3ce42f 100644 --- a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionProcessor.java +++ b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionProcessor.java @@ -59,6 +59,7 @@ public class EncryptionProcessor { private final CosmosAsyncContainer cosmosAsyncContainer; private final EncryptionSettings encryptionSettings; private final AtomicBoolean isEncryptionSettingsInitDone; + private final boolean mixedArrayEncryptionEnabled; private ClientEncryptionPolicy clientEncryptionPolicy; private String containerRid; private String databaseRid; @@ -78,6 +79,8 @@ public EncryptionProcessor(CosmosAsyncContainer cosmosAsyncContainer, if (encryptionCosmosClient == null) { throw new IllegalStateException("encryptionCosmosClient is null"); } + this.mixedArrayEncryptionEnabled = + cosmosEncryptionAsyncClientAccessor.isMixedArrayEncryptionEnabled(encryptionCosmosClient); this.cosmosAsyncContainer = cosmosAsyncContainer; this.encryptionCosmosClient = encryptionCosmosClient; this.isEncryptionSettingsInitDone = new AtomicBoolean(false); @@ -365,43 +368,7 @@ public JsonNode encryptAndSerializePatchProperty(EncryptionSettings encryptionSe else if (propertyValueHolder.isArray()) { assert propertyValueHolder instanceof ArrayNode; ArrayNode arrayNode = (ArrayNode) propertyValueHolder; - if (arrayNode.elements().next().isObject() || arrayNode.elements().next().isArray()) { - List encryptedArray = new ArrayList<>(); - for (Iterator arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { - JsonNode nodeInArray = arrayIterator.next(); - if (nodeInArray.isArray()) { - encryptedArray.add(encryptAndSerializePatchProperty(encryptionSettings, nodeInArray, propertyName)); - } else { - for (Iterator> it = nodeInArray.fields(); it.hasNext(); ) { - Map.Entry child = it.next(); - if (child.getValue().isObject() || child.getValue().isArray()) { - JsonNode encryptedValue = encryptAndSerializePatchProperty(encryptionSettings, - child.getValue(), child.getKey()); - ((ObjectNode) nodeInArray).set(child.getKey(), encryptedValue); - - } else if (!child.getValue().isNull()) { - encryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), - child.getKey()); - } - } - encryptedArray.add(nodeInArray); - } - } - arrayNode.removeAll(); - for (JsonNode encryptedValue : encryptedArray) { - arrayNode.add(encryptedValue); - } - } else { - List encryptedArray = new ArrayList<>(); - for (Iterator it = arrayNode.elements(); it.hasNext(); ) { - encryptedArray.add(encryptAndSerializeValue(encryptionSettings, null, it.next(), - StringUtils.EMPTY)); - } - arrayNode.removeAll(); - for (byte[] encryptedValue : encryptedArray) { - arrayNode.add(encryptedValue); - } - } + encryptPatchArray(encryptionSettings, arrayNode, propertyName); return arrayNode; } else { encryptAndSerializeValue(encryptionSettings, null, propertyValueHolder, propertyName); @@ -424,46 +391,143 @@ public void encryptAndSerializeProperty(EncryptionSettings encryptionSettings, J } } } else if (propertyValueHolder.isArray()) { - ArrayNode arrayNode = (ArrayNode) propertyValueHolder; - Iterator checkArrayIterator = arrayNode.elements(); - boolean hasElements = checkArrayIterator.hasNext(); - if (hasElements) { - JsonNode nextNode = checkArrayIterator.next(); - hasElements &= nextNode.isObject() || nextNode.isArray(); + encryptArray(encryptionSettings, (ArrayNode) propertyValueHolder, propertyName); + } else { + encryptAndSerializeValue(encryptionSettings, (ObjectNode) objectNode, propertyValueHolder, propertyName); + } + } + + private void encryptPatchArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, + String propertyName) throws MicrosoftDataEncryptionException, JsonProcessingException { + if (this.mixedArrayEncryptionEnabled) { + encryptMixedPatchArray(encryptionSettings, arrayNode, propertyName); + } else { + encryptLegacyPatchArray(encryptionSettings, arrayNode, propertyName); + } + } + + private void encryptMixedPatchArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, + String propertyName) throws MicrosoftDataEncryptionException, JsonProcessingException { + ArrayNode encryptedArray = arrayNode.arrayNode(); + for (Iterator arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { + JsonNode nodeInArray = arrayIterator.next(); + if (nodeInArray.isObject() || nodeInArray.isArray()) { + encryptedArray.add(encryptAndSerializePatchProperty(encryptionSettings, nodeInArray, propertyName)); + } else if (!nodeInArray.isNull()) { + encryptedArray.add(encryptAndSerializeValue(encryptionSettings, null, nodeInArray, StringUtils.EMPTY)); + } else { + encryptedArray.add(nodeInArray); } - if (hasElements) { - for (Iterator arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { - JsonNode nodeInArray = arrayIterator.next(); - if (nodeInArray.isArray()) { - encryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, - nodeInArray, StringUtils.EMPTY); - } else { - for (Iterator> it = nodeInArray.fields(); it.hasNext(); ) { - Map.Entry child = it.next(); - if (child.getValue().isObject() || child.getValue().isArray()) { - encryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, - child.getValue(), propertyName); - } else if (!child.getValue().isNull()) { - encryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), - child.getKey()); - } + } + arrayNode.removeAll(); + arrayNode.addAll(encryptedArray); + } + + private void encryptLegacyPatchArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, + String propertyName) throws MicrosoftDataEncryptionException, JsonProcessingException { + if (arrayNode.size() == 0) { + return; + } + if (arrayNode.elements().next().isObject() || arrayNode.elements().next().isArray()) { + List encryptedArray = new ArrayList<>(); + for (Iterator arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { + JsonNode nodeInArray = arrayIterator.next(); + if (nodeInArray.isArray()) { + encryptedArray.add(encryptAndSerializePatchProperty(encryptionSettings, nodeInArray, propertyName)); + } else { + for (Iterator> it = nodeInArray.fields(); it.hasNext(); ) { + Map.Entry child = it.next(); + if (child.getValue().isObject() || child.getValue().isArray()) { + JsonNode encryptedValue = encryptAndSerializePatchProperty(encryptionSettings, + child.getValue(), child.getKey()); + ((ObjectNode) nodeInArray).set(child.getKey(), encryptedValue); + } else if (!child.getValue().isNull()) { + encryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), + child.getKey()); } } + encryptedArray.add(nodeInArray); } - } else { - List encryptedArray = new ArrayList<>(); - for (Iterator it = arrayNode.elements(); it.hasNext(); ) { - encryptedArray.add(encryptAndSerializeValue(encryptionSettings, null, it.next(), - StringUtils.EMPTY)); - } - arrayNode.removeAll(); - for (byte[] encryptedValue : encryptedArray) { - arrayNode.add(encryptedValue); + } + arrayNode.removeAll(); + for (JsonNode encryptedValue : encryptedArray) { + arrayNode.add(encryptedValue); + } + } else { + List encryptedArray = new ArrayList<>(); + for (Iterator it = arrayNode.elements(); it.hasNext(); ) { + encryptedArray.add(encryptAndSerializeValue(encryptionSettings, null, it.next(), StringUtils.EMPTY)); + } + arrayNode.removeAll(); + for (byte[] encryptedValue : encryptedArray) { + arrayNode.add(encryptedValue); + } + } + } + + private void encryptLegacyArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, + String propertyName) throws MicrosoftDataEncryptionException, JsonProcessingException { + Iterator checkArrayIterator = arrayNode.elements(); + boolean hasElements = checkArrayIterator.hasNext(); + if (hasElements) { + JsonNode nextNode = checkArrayIterator.next(); + hasElements &= nextNode.isObject() || nextNode.isArray(); + } + if (hasElements) { + for (Iterator arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { + JsonNode nodeInArray = arrayIterator.next(); + if (nodeInArray.isArray()) { + encryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); + } else { + for (Iterator> it = nodeInArray.fields(); it.hasNext(); ) { + Map.Entry child = it.next(); + if (child.getValue().isObject() || child.getValue().isArray()) { + encryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, + child.getValue(), propertyName); + } else if (!child.getValue().isNull()) { + encryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), + child.getKey()); + } + } } } } else { - encryptAndSerializeValue(encryptionSettings, (ObjectNode) objectNode, propertyValueHolder, propertyName); + List encryptedArray = new ArrayList<>(); + for (Iterator it = arrayNode.elements(); it.hasNext(); ) { + encryptedArray.add(encryptAndSerializeValue(encryptionSettings, null, it.next(), StringUtils.EMPTY)); + } + arrayNode.removeAll(); + for (byte[] encryptedValue : encryptedArray) { + arrayNode.add(encryptedValue); + } + } + } + + private void encryptArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, + String propertyName) throws MicrosoftDataEncryptionException, JsonProcessingException { + if (this.mixedArrayEncryptionEnabled) { + encryptMixedArray(encryptionSettings, arrayNode); + } else { + encryptLegacyArray(encryptionSettings, arrayNode, propertyName); + } + } + + private void encryptMixedArray(EncryptionSettings encryptionSettings, + ArrayNode arrayNode) throws MicrosoftDataEncryptionException, JsonProcessingException { + ArrayNode encryptedArray = arrayNode.arrayNode(); + for (Iterator arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { + JsonNode nodeInArray = arrayIterator.next(); + if (nodeInArray.isObject() || nodeInArray.isArray()) { + encryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); + encryptedArray.add(nodeInArray); + } else if (!nodeInArray.isNull()) { + encryptedArray.add(encryptAndSerializeValue(encryptionSettings, null, nodeInArray, StringUtils.EMPTY)); + } else { + encryptedArray.add(nodeInArray); + } } + arrayNode.removeAll(); + arrayNode.addAll(encryptedArray); } public String encryptAndSerializeValue(EncryptionSettings encryptionSettings, String propertyValue, String propertyName) throws MicrosoftDataEncryptionException { @@ -581,45 +645,93 @@ public void decryptAndSerializeProperty(EncryptionSettings encryptionSettings, J } } } else if (propertyValueHolder.isArray()) { - ArrayNode arrayNode = (ArrayNode) propertyValueHolder; - Iterator checkArrayIterator = arrayNode.elements(); - boolean hasElements = checkArrayIterator.hasNext(); - if (hasElements) { - JsonNode nextNode = checkArrayIterator.next(); - hasElements &= nextNode.isObject() || nextNode.isArray(); + decryptArray(encryptionSettings, (ArrayNode) propertyValueHolder, propertyName); + } else { + decryptAndSerializeValue(encryptionSettings, (ObjectNode) objectNode, propertyValueHolder, propertyName); + } + } + + private void decryptArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, + String propertyName) throws MicrosoftDataEncryptionException, IOException { + if (this.mixedArrayEncryptionEnabled) { + decryptMixedArray(encryptionSettings, arrayNode, propertyName); + } else { + decryptLegacyArray(encryptionSettings, arrayNode, propertyName); + } + } + + private void decryptMixedArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, + String propertyName) throws MicrosoftDataEncryptionException, IOException { + List decryptedArray = new ArrayList<>(); + int index = 0; + for (Iterator arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); index++) { + JsonNode nodeInArray = arrayIterator.next(); + if (nodeInArray.isObject() || nodeInArray.isArray()) { + decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, propertyName); + decryptedArray.add(nodeInArray); + } else if (!nodeInArray.isNull()) { + decryptedArray.add(decryptArrayValue(encryptionSettings, nodeInArray, propertyName, index)); + } else { + decryptedArray.add(nodeInArray); } - if (hasElements) { - for (Iterator arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { - JsonNode nodeInArray = arrayIterator.next(); - if (nodeInArray.isArray()) { - decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, - nodeInArray, StringUtils.EMPTY); - } else { - for (Iterator> it = nodeInArray.fields(); it.hasNext(); ) { - Map.Entry child = it.next(); - if (child.getValue().isObject() || child.getValue().isArray()) { - decryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, - child.getValue(), propertyName); - } else if (!child.getValue().isNull()) { - decryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), - child.getKey()); - } + } + arrayNode.removeAll(); + for (JsonNode decryptedValue : decryptedArray) { + arrayNode.add(decryptedValue); + } + } + + private void decryptLegacyArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, + String propertyName) throws MicrosoftDataEncryptionException, IOException { + Iterator checkArrayIterator = arrayNode.elements(); + boolean hasElements = checkArrayIterator.hasNext(); + if (hasElements) { + JsonNode nextNode = checkArrayIterator.next(); + hasElements &= nextNode.isObject() || nextNode.isArray(); + } + if (hasElements) { + for (Iterator arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { + JsonNode nodeInArray = arrayIterator.next(); + if (nodeInArray.isArray()) { + decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); + } else { + for (Iterator> it = nodeInArray.fields(); it.hasNext(); ) { + Map.Entry child = it.next(); + if (child.getValue().isObject() || child.getValue().isArray()) { + decryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, + child.getValue(), propertyName); + } else if (!child.getValue().isNull()) { + decryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), + child.getKey()); } } } - } else { - List decryptedArray = new ArrayList<>(); - for (Iterator it = arrayNode.elements(); it.hasNext(); ) { - decryptedArray.add(decryptAndSerializeValue(encryptionSettings, null, it.next(), - StringUtils.EMPTY)); - } - arrayNode.removeAll(); - for (JsonNode encryptedValue : decryptedArray) { - arrayNode.add(encryptedValue); - } } } else { - decryptAndSerializeValue(encryptionSettings, (ObjectNode) objectNode, propertyValueHolder, propertyName); + List decryptedArray = new ArrayList<>(); + int index = 0; + for (Iterator it = arrayNode.elements(); it.hasNext(); index++) { + decryptedArray.add(decryptArrayValue(encryptionSettings, it.next(), propertyName, index)); + } + arrayNode.removeAll(); + for (JsonNode decryptedValue : decryptedArray) { + arrayNode.add(decryptedValue); + } + } + } + + private JsonNode decryptArrayValue(EncryptionSettings encryptionSettings, JsonNode nodeInArray, + String propertyName, int index) { + try { + return decryptAndSerializeValue(encryptionSettings, null, nodeInArray, StringUtils.EMPTY); + } catch (MicrosoftDataEncryptionException | IOException | IllegalArgumentException ex) { + throw new IllegalStateException("Unable to decrypt array element at index " + index + + " in encrypted property '/" + propertyName + "'. For confirmed legacy mixed arrays, migrate " + + "the item or temporarily set " + + "-D" + EncryptionConfigs.MIXED_ARRAYS_ENABLED + "=false or " + + EncryptionConfigs.MIXED_ARRAYS_ENABLED_VARIABLE + "=false before creating clients. " + + "Opt-out restores legacy reads/writes and may leave scalars unencrypted. " + + "Check the cause for key or ciphertext errors.", ex); } } @@ -635,6 +747,9 @@ public JsonNode decryptAndSerializeValue(EncryptionSettings encryptionSettings, } else { cipherTextWithTypeMarker = propertyValueHolder.binaryValue(); } + if (cipherTextWithTypeMarker == null || cipherTextWithTypeMarker.length == 0) { + throw new IllegalArgumentException("Expected a non-empty ciphertext value."); + } cipherText = new byte[cipherTextWithTypeMarker.length - 1]; System.arraycopy(cipherTextWithTypeMarker, 1, cipherText, 0, cipherTextWithTypeMarker.length - 1); diff --git a/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/CosmosEncryptionAsyncClientUnitTest.java b/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/CosmosEncryptionAsyncClientUnitTest.java index f6776bd82617a..0417d813d4f00 100644 --- a/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/CosmosEncryptionAsyncClientUnitTest.java +++ b/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/CosmosEncryptionAsyncClientUnitTest.java @@ -8,9 +8,6 @@ import com.azure.cosmos.CosmosAsyncClientEncryptionKey; import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosAsyncDatabase; -import com.azure.cosmos.CosmosBridgeInternal; -import com.azure.cosmos.encryption.implementation.Constants; -import com.azure.cosmos.implementation.AsyncDocumentClient; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.RequestOptions; import com.azure.cosmos.models.CosmosClientEncryptionKeyProperties; @@ -19,8 +16,6 @@ import org.testng.annotations.Test; import reactor.core.publisher.Mono; -import static org.assertj.core.api.Assertions.assertThat; - public class CosmosEncryptionAsyncClientUnitTest { private final static ImplementationBridgeHelpers.CosmosAsyncClientEncryptionKeyHelper.CosmosAsyncClientEncryptionKeyAccessor cosmosAsyncClientEncryptionKeyAccessor = ImplementationBridgeHelpers.CosmosAsyncClientEncryptionKeyHelper.getCosmosAsyncClientEncryptionKeyAccessor(); @@ -60,55 +55,4 @@ public void clientEncryptionPropertiesAsync() { Mockito.verify(spyEncryptionAsyncClient, Mockito.times(2)).fetchClientEncryptionKeyPropertiesAsync(Mockito.any(CosmosAsyncContainer.class), Mockito.anyString(), Mockito.any(RequestOptions.class)); } - @Test(groups = {"unit"}, timeOut = TestSuiteBase.TIMEOUT) - public void encryptionClientAppendsUserAgentSuffix() { - // Setup: mock CosmosAsyncClient with a real AsyncDocumentClient to verify UA suffix - CosmosAsyncClient mockAsyncClient = Mockito.mock(CosmosAsyncClient.class); - AsyncDocumentClient mockDocClient = Mockito.mock(AsyncDocumentClient.class); - KeyEncryptionKeyResolver mockKeyResolver = Mockito.mock(KeyEncryptionKeyResolver.class); - - org.mockito.MockedStatic bridgeMock = Mockito.mockStatic(CosmosBridgeInternal.class); - try { - bridgeMock.when(() -> CosmosBridgeInternal.getAsyncDocumentClient(mockAsyncClient)) - .thenReturn(mockDocClient); - - new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); - - // Verify appendUserAgentSuffix was called with the encryption SDK suffix - Mockito.verify(mockDocClient, Mockito.times(1)) - .appendUserAgentSuffix(Constants.USER_AGENT_SUFFIX); - } finally { - bridgeMock.close(); - } - } - - @Test(groups = {"unit"}, timeOut = TestSuiteBase.TIMEOUT) - public void encryptionUserAgentSuffixContainsVersionInfo() { - // Verify the suffix constants are properly loaded from properties - assertThat(Constants.CURRENT_NAME).isNotEmpty(); - assertThat(Constants.CURRENT_VERSION).isNotEmpty(); - assertThat(Constants.USER_AGENT_SUFFIX).isEqualTo(Constants.CURRENT_NAME + "/" + Constants.CURRENT_VERSION); - assertThat(Constants.USER_AGENT_SUFFIX).startsWith("azure-cosmos-encryption/"); - } - - @Test(groups = {"unit"}, timeOut = TestSuiteBase.TIMEOUT) - public void encryptionClientHandlesAppendFailureGracefully() { - // If getAsyncDocumentClient throws, encryption client should still be created - CosmosAsyncClient mockAsyncClient = Mockito.mock(CosmosAsyncClient.class); - KeyEncryptionKeyResolver mockKeyResolver = Mockito.mock(KeyEncryptionKeyResolver.class); - - org.mockito.MockedStatic bridgeMock = Mockito.mockStatic(CosmosBridgeInternal.class); - try { - bridgeMock.when(() -> CosmosBridgeInternal.getAsyncDocumentClient(mockAsyncClient)) - .thenThrow(new RuntimeException("simulated failure")); - - // Should not throw — the failure is caught and logged - CosmosEncryptionAsyncClient client = - new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); - assertThat(client).isNotNull(); - assertThat(client.getCosmosAsyncClient()).isSameAs(mockAsyncClient); - } finally { - bridgeMock.close(); - } - } } diff --git a/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/EncryptionMixedArrayE2ETest.java b/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/EncryptionMixedArrayE2ETest.java new file mode 100644 index 0000000000000..7c2a22b014234 --- /dev/null +++ b/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/EncryptionMixedArrayE2ETest.java @@ -0,0 +1,232 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.encryption; + +import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.GatewayConnectionConfig; +import com.azure.cosmos.Http2ConnectionConfig; +import com.azure.cosmos.encryption.models.CosmosEncryptionAlgorithm; +import com.azure.cosmos.encryption.models.CosmosEncryptionType; +import com.azure.cosmos.implementation.TestConfigurations; +import com.azure.cosmos.models.ClientEncryptionIncludedPath; +import com.azure.cosmos.models.ClientEncryptionPolicy; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.CosmosItemRequestOptions; +import com.azure.cosmos.models.CosmosItemResponse; +import com.azure.cosmos.models.CosmosPatchItemRequestOptions; +import com.azure.cosmos.models.CosmosPatchOperations; +import com.azure.cosmos.models.EncryptionKeyWrapMetadata; +import com.azure.cosmos.models.PartitionKey; +import com.azure.cosmos.models.ThroughputProperties; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.time.Duration; +import java.time.Instant; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.assertj.core.api.Assertions.assertThat; + +public class EncryptionMixedArrayE2ETest { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String MIXED_ARRAYS_ENABLED = "COSMOS.ENCRYPTION_MIXED_ARRAYS_ENABLED"; + private static final String HTTP2_ENABLED = "COSMOS.HTTP2_ENABLED"; + private static final String THINCLIENT_ENABLED = "COSMOS.THINCLIENT_ENABLED"; + private static final Pattern FEATURE_MASK = Pattern.compile("\\|F([0-9A-F]+)$"); + private static final Duration TIMEOUT = Duration.ofSeconds(60); + private final String runId = "encma-" + UUID.randomUUID().toString().substring(0, 8); + private final String databaseId = runId; + private final String containerId = "mixed-arrays"; + private String endpoint; + private String key; + private CosmosAsyncClient adminClient; + private boolean databaseCreated; + + @BeforeClass(groups = "encryption-live", timeOut = 180000) + public void createIsolatedEncryptionContainer() throws Exception { + endpoint = TestConfigurations.HOST; + key = TestConfigurations.MASTER_KEY; + assertThat(endpoint).as("ACCOUNT_HOST in the live-test configuration").isNotBlank(); + assertThat(key).as("ACCOUNT_KEY in the live-test configuration").isNotBlank(); + assertThat(java.net.URI.create(endpoint).getHost()).as("Service telemetry requires a live account") + .isNotIn("localhost", "127.0.0.1"); + + Map previous = configure("GatewayV1", false); + try { + adminClient = clientBuilder("GatewayV1", runId + "-setup").buildAsyncClient(); + adminClient.createDatabase(databaseId).block(TIMEOUT); + databaseCreated = true; + CosmosEncryptionAsyncClient encryptionClient = wrap(adminClient); + CosmosEncryptionAsyncDatabase database = encryptionClient.getCosmosEncryptionAsyncDatabase(databaseId); + database.createClientEncryptionKey("key1", CosmosEncryptionAlgorithm.AEAD_AES_256_CBC_HMAC_SHA256.getName(), + new EncryptionKeyWrapMetadata("TEST_KEY_RESOLVER", "key1", "tempmetadata1", "RSA-OAEP")).block(TIMEOUT); + ClientEncryptionIncludedPath includedPath = new ClientEncryptionIncludedPath() + .setPath("/sensitive") + .setClientEncryptionKeyId("key1") + .setEncryptionType(CosmosEncryptionType.DETERMINISTIC.getName()) + .setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAD_AES_256_CBC_HMAC_SHA256.getName()); + CosmosContainerProperties container = new CosmosContainerProperties(containerId, "/pk"); + container.setClientEncryptionPolicy(new ClientEncryptionPolicy(Collections.singletonList(includedPath), 2)); + adminClient.getDatabase(databaseId).createContainer(container, ThroughputProperties.createManualThroughput(400)) + .block(TIMEOUT); + System.out.println("ENCRYPTION_E2E_SETUP runId=" + runId + " account=" + + java.net.URI.create(endpoint).getHost().split("\\.")[0] + " utc=" + Instant.now()); + } finally { + restore(previous); + } + } + + @DataProvider(name = "connectionModes") + public Object[][] connectionModes() { + return new Object[][] { + {"GatewayV1", false}, {"GatewayV1", true}, + {"GatewayV2", false}, {"GatewayV2", true}, + {"Direct", false}, {"Direct", true} + }; + } + + @Test(groups = "encryption-live", dataProvider = "connectionModes", timeOut = 240000) + public void mixedArraysAndUserAgent(String mode, boolean optOut) throws Exception { + String caseId = mode + (optOut ? "-out" : "-in"); + Map previous = configure(mode, optOut); + Instant started = Instant.now(); + try (CosmosAsyncClient client = clientBuilder(mode, runId + "-" + caseId).buildAsyncClient()) { + CosmosEncryptionAsyncContainer container = wrap(client).getCosmosEncryptionAsyncDatabase(databaseId) + .getCosmosEncryptionAsyncContainer(containerId); + PartitionKey partitionKey = new PartitionKey(caseId); + ObjectNode document = MAPPER.createObjectNode(); + document.put("id", caseId); + document.put("pk", caseId); + JsonNode original = MAPPER.readTree( + "[{\"label\":\"CREATE_SECRET\"},42,\"SCALAR_SECRET\",true,null,[\"NESTED_SECRET\"]]"); + document.set("sensitive", original.deepCopy()); + + CosmosItemResponse created = container.createItem(document, partitionKey, + new CosmosItemRequestOptions()).block(TIMEOUT); + assertThat(created.getItem().get("sensitive").toString()).isEqualTo(original.toString()); + record(mode, optOut, "create", started, created); + + CosmosItemResponse raw = container.getCosmosAsyncContainer() + .readItem(caseId, partitionKey, JsonNode.class).block(TIMEOUT); + assertStoredArray(raw.getItem().get("sensitive"), optOut, "CREATE_SECRET", 42); + record(mode, optOut, "raw-read-create", started, raw); + + CosmosItemResponse read = container.readItem(caseId, partitionKey, JsonNode.class).block(TIMEOUT); + assertThat(read.getItem().get("sensitive").toString()).isEqualTo(original.toString()); + record(mode, optOut, "read-create", started, read); + + JsonNode patched = MAPPER.readTree( + "[{\"label\":\"PATCH_SECRET\"},43,\"SCALAR_SECRET\",true,null,[\"NESTED_SECRET\"]]"); + CosmosItemResponse patch = container.patchItem(caseId, partitionKey, + CosmosPatchOperations.create().set("/sensitive", patched.deepCopy()), + new CosmosPatchItemRequestOptions(), JsonNode.class).block(TIMEOUT); + assertThat(patch.getItem().get("sensitive").toString()).isEqualTo(patched.toString()); + record(mode, optOut, "patch", started, patch); + + raw = container.getCosmosAsyncContainer().readItem(caseId, partitionKey, JsonNode.class).block(TIMEOUT); + assertStoredArray(raw.getItem().get("sensitive"), optOut, "PATCH_SECRET", 43); + record(mode, optOut, "raw-read-patch", started, raw); + read = container.readItem(caseId, partitionKey, JsonNode.class).block(TIMEOUT); + assertThat(read.getItem().get("sensitive").toString()).isEqualTo(patched.toString()); + record(mode, optOut, "read-patch", started, read); + } finally { + restore(previous); + } + } + + private void assertStoredArray(JsonNode array, boolean optOut, String objectSecret, int number) { + assertThat(array.get(0).get("label").asText()).isNotEqualTo(objectSecret); + assertThat(array.get(5).get(0).asText()).isNotEqualTo("NESTED_SECRET"); + assertThat(array.get(4).isNull()).isTrue(); + if (optOut) { + assertThat(array.get(1).asInt()).isEqualTo(number); + assertThat(array.get(2).asText()).isEqualTo("SCALAR_SECRET"); + assertThat(array.get(3).asBoolean()).isTrue(); + } else { + assertThat(array.get(1).isTextual()).isTrue(); + assertThat(array.get(3).isTextual()).isTrue(); + assertThat(array.toString()).doesNotContain(objectSecret, "SCALAR_SECRET", "NESTED_SECRET"); + } + } + + private void record(String mode, boolean optOut, String operation, Instant started, + CosmosItemResponse response) throws Exception { + String userAgent = response.getDiagnostics().getUserAgent(); + Matcher matcher = FEATURE_MASK.matcher(userAgent); + int flags = matcher.find() ? Integer.parseInt(matcher.group(1), 16) : 0; + assertThat((flags & 0x80) != 0).as("Opt-out bit in the response diagnostics").isEqualTo(optOut); + Map result = new LinkedHashMap<>(); + result.put("runId", runId); + result.put("mode", mode); + result.put("optOut", optOut); + result.put("operation", operation); + result.put("startedUtc", started.toString()); + result.put("finishedUtc", Instant.now().toString()); + result.put("activityId", response.getActivityId()); + result.put("status", response.getStatusCode()); + result.put("userAgent", userAgent); + System.out.println("ENCRYPTION_E2E " + MAPPER.writeValueAsString(result)); + } + + private CosmosClientBuilder clientBuilder(String mode, String suffix) { + CosmosClientBuilder builder = new CosmosClientBuilder().endpoint(endpoint).key(key) + .consistencyLevel(ConsistencyLevel.SESSION).contentResponseOnWriteEnabled(true).userAgentSuffix(suffix); + return "Direct".equals(mode) ? builder.directMode() + : builder.gatewayMode(new GatewayConnectionConfig() + .setHttp2ConnectionConfig(new Http2ConnectionConfig().setEnabled("GatewayV2".equals(mode)))); + } + + private CosmosEncryptionAsyncClient wrap(CosmosAsyncClient client) { + return new CosmosEncryptionClientBuilder().cosmosAsyncClient(client) + .keyEncryptionKeyResolver(new TestSuiteBase.TestKeyEncryptionKeyResolver()) + .keyEncryptionKeyResolverName("TEST_KEY_RESOLVER").buildAsyncClient(); + } + + private Map configure(String mode, boolean optOut) { + Map previous = new LinkedHashMap<>(); + previous.put(MIXED_ARRAYS_ENABLED, System.getProperty(MIXED_ARRAYS_ENABLED)); + previous.put(HTTP2_ENABLED, System.getProperty(HTTP2_ENABLED)); + previous.put(THINCLIENT_ENABLED, System.getProperty(THINCLIENT_ENABLED)); + System.setProperty(MIXED_ARRAYS_ENABLED, Boolean.toString(!optOut)); + System.setProperty(HTTP2_ENABLED, Boolean.toString("GatewayV2".equals(mode))); + System.setProperty(THINCLIENT_ENABLED, Boolean.toString("GatewayV2".equals(mode))); + return previous; + } + + private void restore(Map previous) { + previous.forEach((name, value) -> { + if (value == null) { + System.clearProperty(name); + } else { + System.setProperty(name, value); + } + }); + } + + @AfterClass(groups = "encryption-live", alwaysRun = true, timeOut = 120000) + public void deleteIsolatedDatabase() { + if (adminClient != null) { + try { + if (databaseCreated) { + adminClient.getDatabase(databaseId).delete().block(TIMEOUT); + System.out.println("ENCRYPTION_E2E_CLEANUP database=" + databaseId + " deleted=true"); + } + } finally { + adminClient.close(); + } + } + } +} diff --git a/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/implementation/EncryptionProcessorAndSettingsTest.java b/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/implementation/EncryptionProcessorAndSettingsTest.java index 26281a6245b01..397afdd5d0bf0 100644 --- a/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/implementation/EncryptionProcessorAndSettingsTest.java +++ b/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/implementation/EncryptionProcessorAndSettingsTest.java @@ -8,7 +8,9 @@ import com.azure.cosmos.encryption.CosmosEncryptionAsyncClient; import com.azure.cosmos.encryption.EncryptionAsyncApiCrudTest; import com.azure.cosmos.encryption.implementation.keyprovider.EncryptionKeyStoreProviderImpl; +import com.azure.cosmos.encryption.implementation.mdesrc.cryptography.AeadAes256CbcHmac256EncryptionAlgorithm; import com.azure.cosmos.encryption.implementation.mdesrc.cryptography.EncryptionKeyStoreProvider; +import com.azure.cosmos.encryption.implementation.mdesrc.cryptography.MicrosoftDataEncryptionException; import com.azure.cosmos.encryption.models.CosmosEncryptionAlgorithm; import com.azure.cosmos.encryption.models.CosmosEncryptionType; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; @@ -22,13 +24,16 @@ import com.fasterxml.jackson.core.json.JsonReadFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import org.assertj.core.api.Assertions; import org.mockito.Mockito; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import reactor.core.publisher.Mono; +import java.io.IOException; import java.security.InvalidKeyException; import java.time.Duration; import java.time.Instant; @@ -37,6 +42,7 @@ import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; public class EncryptionProcessorAndSettingsTest { @@ -273,4 +279,266 @@ public void encryptEmptyArray() throws Exception { CosmosItemSerializer.DEFAULT_SERIALIZER).block().getLeft()); assertThat(output).isEqualTo(json); } + + @Test(groups = {"unit"}, timeOut = TIMEOUT) + public void encryptPatchMixedArray() throws Exception { + EncryptionProcessor encryptionProcessor = createEncryptionProcessor(); + JsonNode patchValue = OBJECT_MAPPER.readTree( + "[{\"label\":\"patched\"},\"PATCH_SECRET\",[\"NESTED_SECRET\"],null,42,{\"tail\":\"TAIL_SECRET\"}]"); + JsonNode expectedValue = patchValue.deepCopy(); + + JsonNode encryptedPatchValue = encryptionProcessor.encryptPatchNode(patchValue, "/sensitiveString").block(); + + assertThat(encryptedPatchValue.get(0).get("label").isBinary()).isTrue(); + assertThat(encryptedPatchValue.get(1).isBinary()).isTrue(); + assertThat(encryptedPatchValue.get(2).get(0).isBinary()).isTrue(); + assertThat(encryptedPatchValue.get(3).isNull()).isTrue(); + assertThat(encryptedPatchValue.get(4).isBinary()).isTrue(); + assertThat(encryptedPatchValue.get(5).get("tail").isBinary()).isTrue(); + + ObjectNode patchedDocument = OBJECT_MAPPER.createObjectNode(); + patchedDocument.put("id", "patchItem"); + patchedDocument.set("sensitiveString", encryptedPatchValue); + JsonNode decryptedPatchedDocument = encryptionProcessor.decrypt(patchedDocument, + CosmosItemSerializer.DEFAULT_SERIALIZER).block().getRight(); + assertThat(decryptedPatchedDocument.get("sensitiveString").toString()).isEqualTo(expectedValue.toString()); + + ObjectNode document = OBJECT_MAPPER.createObjectNode(); + document.put("id", "createItem"); + document.set("sensitiveString", expectedValue.deepCopy()); + byte[] encryptedDocumentBytes = encryptionProcessor.encrypt(document).block(); + JsonNode encryptedDocument = OBJECT_MAPPER.readTree(encryptedDocumentBytes); + assertThat(encryptedDocument.toString()).doesNotContain("patched", "PATCH_SECRET", "NESTED_SECRET", + "TAIL_SECRET"); + JsonNode decryptedDocument = encryptionProcessor.decrypt(encryptedDocumentBytes, + CosmosItemSerializer.DEFAULT_SERIALIZER).block().getRight(); + assertThat(decryptedDocument.get("sensitiveString").toString()).isEqualTo(expectedValue.toString()); + } + + @DataProvider(name = "legacyMixedArrays") + public Object[][] legacyMixedArrays() { + return new Object[][] { + {"[{\"label\":\"secret\"},42]", IllegalArgumentException.class}, + {"[{\"label\":\"secret\"},true]", IllegalArgumentException.class}, + {"[{\"label\":\"secret\"},\"LEGACY_SECRET!\"]", IOException.class}, + {"[{\"label\":\"secret\"},\"\"]", IllegalArgumentException.class}, + {"[{\"label\":\"secret\"},\"YWJjZA==\"]", MicrosoftDataEncryptionException.class}, + {"[[\"secret\"],42]", IllegalArgumentException.class} + }; + } + + @Test(groups = {"unit"}, dataProvider = "legacyMixedArrays", timeOut = TIMEOUT) + public void decryptLegacyMixedArrayReportsMigration(String arrayJson, + Class expectedCause) throws Exception { + EncryptionProcessor encryptionProcessor = createEncryptionProcessor(); + ArrayNode legacyArray = (ArrayNode) OBJECT_MAPPER.readTree(arrayJson); + // Old writers encrypted the leading container but skipped subsequent scalar elements. + legacyArray.set(0, encryptionProcessor.encryptPatchNode(legacyArray.get(0), "/sensitiveString/0").block()); + ObjectNode document = OBJECT_MAPPER.createObjectNode(); + document.put("id", "legacyItem"); + document.set("sensitiveString", legacyArray); + byte[] storedDocument = OBJECT_MAPPER.writeValueAsBytes(document); + + assertThatThrownBy(() -> encryptionProcessor.decrypt(storedDocument, + CosmosItemSerializer.DEFAULT_SERIALIZER).block()) + .isInstanceOf(IllegalStateException.class) + .hasCauseInstanceOf(expectedCause) + .hasMessageContaining("index 1") + .hasMessageContaining("encrypted property '/sensitiveString'") + .hasMessageContaining("For confirmed legacy mixed arrays") + .hasMessageContaining("migrate the item") + .hasMessageContaining("may leave scalars unencrypted") + .hasMessageContaining("-DCOSMOS.ENCRYPTION_MIXED_ARRAYS_ENABLED=false") + .hasMessageContaining("COSMOS_ENCRYPTION_MIXED_ARRAYS_ENABLED=false") + .hasMessageNotContaining("secret") + .hasMessageNotContaining("LEGACY_SECRET!") + .hasMessageNotContaining("YWJjZA=="); + + EncryptionProcessor legacyReader = createEncryptionProcessor(false); + JsonNode decryptedDocument = legacyReader.decrypt(storedDocument, + CosmosItemSerializer.DEFAULT_SERIALIZER).block().getRight(); + assertThat(decryptedDocument.get("sensitiveString").toString()) + .isEqualTo(OBJECT_MAPPER.readTree(arrayJson).toString()); + } + + @DataProvider(name = "mixedArrayModes") + public Object[][] mixedArrayModes() { + return new Object[][] {{true}, {false}}; + } + + @Test(groups = {"unit"}, dataProvider = "mixedArrayModes", timeOut = TIMEOUT) + public void encryptEmptyItemAndPatchArrays(boolean mixedArraysEnabled) throws Exception { + EncryptionProcessor encryptionProcessor = createEncryptionProcessor(mixedArraysEnabled); + JsonNode encryptedPatch = encryptionProcessor.encryptPatchNode( + OBJECT_MAPPER.createArrayNode(), "/sensitiveString").block(); + assertThat(encryptedPatch.toString()).isEqualTo("[]"); + + ObjectNode document = OBJECT_MAPPER.createObjectNode(); + document.put("id", "emptyArrayItem"); + document.set("sensitiveString", encryptedPatch); + byte[] encryptedBytes = encryptionProcessor.encrypt(document).block(); + JsonNode decryptedDocument = encryptionProcessor.decrypt(encryptedBytes, + CosmosItemSerializer.DEFAULT_SERIALIZER).block().getRight(); + assertThat(decryptedDocument.get("sensitiveString").toString()).isEqualTo("[]"); + } + + @Test(groups = {"unit"}, dataProvider = "mixedArrayModes", timeOut = TIMEOUT) + public void decryptArrayPreservesAuthenticationFailure(boolean mixedArraysEnabled) throws Exception { + EncryptionProcessor encryptionProcessor = createEncryptionProcessor(mixedArraysEnabled); + EncryptionSettings settings = Mockito.mock(EncryptionSettings.class); + AeadAes256CbcHmac256EncryptionAlgorithm algorithm = Mockito.mock(AeadAes256CbcHmac256EncryptionAlgorithm.class); + Mockito.when(settings.getAeadAes256CbcHmac256EncryptionAlgorithm()).thenReturn(algorithm); + MicrosoftDataEncryptionException authenticationFailure = + new MicrosoftDataEncryptionException("Authentication failed"); + Mockito.when(algorithm.decrypt(Mockito.any(byte[].class))).thenThrow(authenticationFailure); + JsonNode array = OBJECT_MAPPER.readTree("[\"AQID\"]"); + + assertThatThrownBy(() -> encryptionProcessor.decryptAndSerializeProperty(settings, null, array, + "sensitiveString")) + .isInstanceOf(IllegalStateException.class) + .hasCause(authenticationFailure) + .hasMessageContaining("Check the cause for key or ciphertext errors"); + } + + @DataProvider(name = "legacyArrayWrites") + public Object[][] legacyArrayWrites() { + String objectFirst = "[{\"label\":\"secret\"},42,\"LEGACY_SECRET\",true,null,[\"nested\"]," + + "{\"tail\":\"secret\"}]"; + String nestedArray = "{\"nested\":[[\"secret\"],42,\"LEGACY_SECRET\",null]}"; + return new Object[][] { + {objectFirst, false}, {objectFirst, true}, + {nestedArray, false}, {nestedArray, true}, + {"[\"secret\",42,true]", false}, {"[\"secret\",42,true]", true} + }; + } + + @Test(groups = {"unit"}, dataProvider = "legacyArrayWrites", timeOut = TIMEOUT) + public void legacyOptOutAppliesToItemAndPatchWrites(String valueJson, boolean patch) throws Exception { + EncryptionProcessor legacyProcessor = createEncryptionProcessor(false); + JsonNode originalValue = OBJECT_MAPPER.readTree(valueJson); + ObjectNode document = OBJECT_MAPPER.createObjectNode(); + document.put("id", "legacyItem"); + document.set("sensitiveString", originalValue.deepCopy()); + + if (patch) { + document.set("sensitiveString", + legacyProcessor.encryptPatchNode(document.get("sensitiveString"), "/sensitiveString").block()); + } else { + document = (ObjectNode) OBJECT_MAPPER.readTree(legacyProcessor.encrypt(document).block()); + } + + JsonNode encryptedValue = document.get("sensitiveString"); + JsonNode encryptedArray = encryptedValue.isObject() ? encryptedValue.get("nested") : encryptedValue; + if (originalValue.isObject() || originalValue.get(0).isContainerNode()) { + assertThat(encryptedArray.get(1).asInt()).isEqualTo(42); + assertThat(encryptedArray.get(2).asText()).isEqualTo("LEGACY_SECRET"); + } else { + assertThat(encryptedArray.get(0).asText()).isNotEqualTo("secret"); + } + + JsonNode decryptedDocument = legacyProcessor.decrypt(OBJECT_MAPPER.writeValueAsBytes(document), + CosmosItemSerializer.DEFAULT_SERIALIZER).block().getRight(); + assertThat(decryptedDocument.get("sensitiveString").toString()).isEqualTo(originalValue.toString()); + } + + @Test(groups = {"unit"}, timeOut = TIMEOUT) + public void migrateLegacyMixedArrayWithOptOut() throws Exception { + EncryptionProcessor legacyProcessor = createEncryptionProcessor(false); + EncryptionProcessor fixedProcessor = createEncryptionProcessor(true); + ObjectNode document = (ObjectNode) OBJECT_MAPPER.readTree( + "{\"id\":\"migrateItem\",\"sensitiveString\":[{\"label\":\"secret\"},42,\"LEGACY_SECRET\"]}"); + String expectedDocument = document.toString(); + byte[] legacyBytes = legacyProcessor.encrypt(document).block(); + JsonNode decryptedLegacyDocument = legacyProcessor.decrypt(legacyBytes, + CosmosItemSerializer.DEFAULT_SERIALIZER).block().getRight(); + + byte[] migratedBytes = fixedProcessor.encrypt(decryptedLegacyDocument).block(); + assertThat(OBJECT_MAPPER.readTree(migratedBytes).toString()).doesNotContain("secret", "LEGACY_SECRET"); + assertThat(OBJECT_MAPPER.readTree(migratedBytes).get("sensitiveString").get(1).isTextual()).isTrue(); + JsonNode decryptedMigratedDocument = fixedProcessor.decrypt(migratedBytes, + CosmosItemSerializer.DEFAULT_SERIALIZER).block().getRight(); + assertThat(decryptedMigratedDocument.toString()).isEqualTo(expectedDocument); + } + + @DataProvider(name = "legacyUnsupportedArrays") + public Object[][] legacyUnsupportedArrays() { + return new Object[][] { + {"[42,{\"label\":\"secret\"}]", false}, {"[42,{\"label\":\"secret\"}]", true}, + {"[\"secret\",[42]]", false}, {"[\"secret\",[42]]", true}, + {"[null]", false}, {"[null]", true} + }; + } + + @Test(groups = {"unit"}, dataProvider = "legacyUnsupportedArrays", timeOut = TIMEOUT) + public void legacyOptOutPreservesUnsupportedArrayFailures(String valueJson, boolean patch) throws Exception { + EncryptionProcessor legacyProcessor = createEncryptionProcessor(false); + JsonNode value = OBJECT_MAPPER.readTree(valueJson); + if (patch) { + assertThatThrownBy(() -> legacyProcessor.encryptPatchNode(value, "/sensitiveString").block()) + .hasMessageContaining("Invalid or Unsupported Data Type"); + } else { + ObjectNode document = OBJECT_MAPPER.createObjectNode(); + document.put("id", "legacyItem"); + document.set("sensitiveString", value); + assertThatThrownBy(() -> legacyProcessor.encrypt(document).block()) + .hasMessageContaining("Invalid or Unsupported Data Type"); + } + } + + @DataProvider(name = "mixedArrayConfigurationValues") + public Object[][] mixedArrayConfigurationValues() { + return new Object[][] { + {null, null, true}, {"", "", true}, + {"false", null, false}, {null, "false", false}, {"", "false", false}, + {"true", "false", true}, {"false", "true", false}, + {"FALSE", null, false}, {null, "TRUE", true} + }; + } + + @Test(groups = {"unit"}, dataProvider = "mixedArrayConfigurationValues", timeOut = TIMEOUT) + public void mixedArrayConfigurationPrecedence(String systemProperty, String environmentVariable, boolean expected) { + assertThat(EncryptionConfigs.isMixedArrayEncryptionEnabled(systemProperty, environmentVariable)) + .isEqualTo(expected); + } + + @Test(groups = {"unit"}, timeOut = TIMEOUT) + public void invalidMixedArrayConfigurationFailsExplicitly() { + assertThatThrownBy(() -> EncryptionConfigs.isMixedArrayEncryptionEnabled("tru", "false")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Only 'true' or 'false'"); + assertThatThrownBy(() -> EncryptionConfigs.isMixedArrayEncryptionEnabled(null, "0")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(EncryptionConfigs.MIXED_ARRAYS_ENABLED_VARIABLE); + } + + private EncryptionProcessor createEncryptionProcessor(boolean mixedArraysEnabled) throws JsonProcessingException { + String previousValue = System.getProperty(EncryptionConfigs.MIXED_ARRAYS_ENABLED); + try { + System.setProperty(EncryptionConfigs.MIXED_ARRAYS_ENABLED, Boolean.toString(mixedArraysEnabled)); + return createEncryptionProcessor(); + } finally { + if (previousValue == null) { + System.clearProperty(EncryptionConfigs.MIXED_ARRAYS_ENABLED); + } else { + System.setProperty(EncryptionConfigs.MIXED_ARRAYS_ENABLED, previousValue); + } + } + } + + private EncryptionProcessor createEncryptionProcessor() throws JsonProcessingException { + CosmosAsyncContainer cosmosAsyncContainer = Mockito.mock(CosmosAsyncContainer.class); + CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = Mockito.mock(CosmosEncryptionAsyncClient.class); + Mockito.when(cosmosEncryptionAsyncClientAccessor.isMixedArrayEncryptionEnabled(cosmosEncryptionAsyncClient)) + .thenReturn(EncryptionConfigs.isMixedArrayEncryptionEnabled()); + Mockito.when(cosmosEncryptionAsyncClient.getKeyEncryptionKeyResolver()).thenReturn(keyEncryptionKeyResolver); + Mockito.when(cosmosEncryptionAsyncClientAccessor.getContainerPropertiesAsync(cosmosEncryptionAsyncClient, + Mockito.any(CosmosAsyncContainer.class), Mockito.anyBoolean())).thenReturn(Mono.just(generateContainerWithCosmosEncryptionPolicy())); + Mockito.when(cosmosEncryptionAsyncClientAccessor.getClientEncryptionPropertiesAsync(cosmosEncryptionAsyncClient, + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(CosmosAsyncContainer.class), Mockito.anyBoolean(), Mockito.nullable(String.class), Mockito.anyBoolean())).thenReturn(Mono.just(generateClientEncryptionKeyProperties())); + EncryptionKeyStoreProviderImpl encryptionKeyStoreProvider = new EncryptionKeyStoreProviderImpl(keyEncryptionKeyResolver, "TEST_KEY_RESOLVER"); + Mockito.when(cosmosEncryptionAsyncClientAccessor.getEncryptionKeyStoreProviderImpl(cosmosEncryptionAsyncClient)).thenReturn(encryptionKeyStoreProvider); + return new EncryptionProcessor(cosmosAsyncContainer, cosmosEncryptionAsyncClient); + } } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RxGatewayStoreModelTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RxGatewayStoreModelTest.java index cff68d9b48166..6cc6d0487bd3a 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RxGatewayStoreModelTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RxGatewayStoreModelTest.java @@ -35,6 +35,7 @@ import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; @@ -48,6 +49,74 @@ public class RxGatewayStoreModelTest { private final static int TIMEOUT = 10000; + @Test(groups = "unit") + public void latestUserAgentIsAppliedToGatewayRequest() throws Exception { + DiagnosticsClientContext clientContext = mockDiagnosticsClientContext(); + UserAgentContainer userAgentContainer = new UserAgentContainer(); + userAgentContainer.setSuffix("test-application"); + RxGatewayStoreModel storeModel = new RxGatewayStoreModel( + clientContext, + Mockito.mock(ISessionContainer.class), + ConsistencyLevel.SESSION, + QueryCompatibilityMode.Default, + userAgentContainer, + Mockito.mock(GlobalEndpointManager.class), + Mockito.mock(HttpClient.class), + ApiType.SQL, + null); + + userAgentContainer.setFeatureEnabledFlagsAsSuffix( + Collections.singleton(UserAgentFeatureFlags.ThinClient)); + userAgentContainer.addFeatureEnabledFlag(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); + + RxDocumentServiceRequest request = RxDocumentServiceRequest.create( + clientContext, + OperationType.Read, + ResourceType.Document, + "/dbs/db/colls/col/docs/doc", + null, + (Object) null); + + HttpRequest httpRequest = storeModel.wrapInHttpRequest(request, new URI("https://localhost")); + + assertThat(httpRequest.headers().value(HttpConstants.HttpHeaders.USER_AGENT)) + .isEqualTo(userAgentContainer.getUserAgent()) + .endsWith("test-application|F84"); + } + + @Test(groups = "unit") + public void requestUserAgentOverrideIsPreservedCaseInsensitively() throws Exception { + DiagnosticsClientContext clientContext = mockDiagnosticsClientContext(); + UserAgentContainer userAgentContainer = new UserAgentContainer(); + RxGatewayStoreModel storeModel = new RxGatewayStoreModel( + clientContext, + Mockito.mock(ISessionContainer.class), + ConsistencyLevel.SESSION, + QueryCompatibilityMode.Default, + userAgentContainer, + Mockito.mock(GlobalEndpointManager.class), + Mockito.mock(HttpClient.class), + ApiType.SQL, + null); + + String requestUserAgent = userAgentContainer.getUserAgent(); + userAgentContainer.setFeatureEnabledFlagsAsSuffix( + Collections.singleton(UserAgentFeatureFlags.PerPartitionCircuitBreaker)); + + RxDocumentServiceRequest request = RxDocumentServiceRequest.create( + clientContext, + OperationType.Read, + ResourceType.DatabaseAccount, + "", + Collections.singletonMap("user-agent", requestUserAgent), + (Object) null); + + HttpRequest httpRequest = storeModel.wrapInHttpRequest(request, new URI("https://localhost")); + + assertThat(httpRequest.headers().value(HttpConstants.HttpHeaders.USER_AGENT)) + .isEqualTo(requestUserAgent); + } + @DataProvider(name = "sessionTokenConfigProvider") public Object[][] sessionTokenConfigProvider() { return new Object[][]{ diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientStoreModelTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientStoreModelTest.java index f657036d81f55..57ab8daeffbeb 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientStoreModelTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientStoreModelTest.java @@ -193,7 +193,7 @@ public void testNullAdditionalHeadersThinClientStoreModel() throws Exception { } @Test(groups = "unit") - public void thinClientDoesNotAddNoRetry449Header() throws Exception { + public void thinClientUsesLatestUserAgentAndDoesNotAddNoRetry449Header() throws Exception { DiagnosticsClientContext clientContext = Mockito.mock(DiagnosticsClientContext.class); Mockito.doReturn(new DiagnosticsClientContext.DiagnosticsClientConfig()).when(clientContext).getConfig(); Mockito @@ -219,15 +219,21 @@ public void thinClientDoesNotAddNoRetry449Header() throws Exception { Mockito.when(httpClient.send(requestCaptor.capture(), any())) .thenReturn(Mono.error(new ConnectTimeoutException())); + UserAgentContainer userAgentContainer = new UserAgentContainer(); + userAgentContainer.setSuffix("test-application"); ThinClientStoreModel storeModel = new ThinClientStoreModel( clientContext, sessionContainer, ConsistencyLevel.SESSION, - new UserAgentContainer(), + userAgentContainer, globalEndpointManager, httpClient, null); + userAgentContainer.setFeatureEnabledFlagsAsSuffix( + Collections.singleton(UserAgentFeatureFlags.ThinClient)); + userAgentContainer.addFeatureEnabledFlag(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); + RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName( clientContext, OperationType.Read, @@ -249,6 +255,10 @@ public void thinClientDoesNotAddNoRetry449Header() throws Exception { .isNull(); HttpHeaders httpHeaders = ReflectionUtils.getHttpHeaders(requestCaptor.getValue()); + assertThat(httpHeaders.value(HttpConstants.HttpHeaders.USER_AGENT)) + .as("ThinClient HTTP framing headers should use the latest evaluated user agent") + .isEqualTo(userAgentContainer.getUserAgent()) + .endsWith("test-application|F84"); assertThat(httpHeaders.toMap().get(HttpConstants.HttpHeaders.NO_RETRY_449)) .as("ThinClient HTTP framing headers should not include the Gateway V1 no-retry-449 header") .isNull(); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/UserAgentContainerTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/UserAgentContainerTest.java index df28f25d69041..25717fb729498 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/UserAgentContainerTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/UserAgentContainerTest.java @@ -15,6 +15,10 @@ import java.util.List; import java.util.Locale; import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import static org.assertj.core.api.Assertions.assertThat; @@ -29,6 +33,8 @@ public Object[][] userAgentSuffixFeatureEnablementFlags() { {Arrays.asList(UserAgentFeatureFlags.PerPartitionCircuitBreaker, UserAgentFeatureFlags.PerPartitionAutomaticFailover), "|F3"}, {Arrays.asList(UserAgentFeatureFlags.PerPartitionAutomaticFailover), "|F1"}, {Arrays.asList(UserAgentFeatureFlags.PerPartitionCircuitBreaker), "|F2"}, + {Arrays.asList(UserAgentFeatureFlags.EncryptionMixedArrayOptOut), "|F80"}, + {Arrays.asList(UserAgentFeatureFlags.ThinClient, UserAgentFeatureFlags.EncryptionMixedArrayOptOut), "|F84"}, {new ArrayList<>(), ""}, {null, ""} }; @@ -173,6 +179,86 @@ public void appendUserAgentSuffix() { assertThat(userAgentContainer.getUserAgent()).contains("azure-cosmos-encryption/2.28.0"); } + @Test(groups = {"unit"}) + public void appendSuffixAtomicallyPreservesFeatureFlags() { + UserAgentContainer userAgentContainer = new UserAgentContainer(); + userAgentContainer.setSuffix("my-app"); + userAgentContainer.setFeatureEnabledFlagsAsSuffix( + new HashSet<>(Arrays.asList(UserAgentFeatureFlags.PerPartitionCircuitBreaker))); + + userAgentContainer.appendSuffix("azure-cosmos-encryption/2.28.0"); + userAgentContainer.appendSuffix("azure-cosmos-encryption/2.28.0"); + + assertThat(userAgentContainer.getSuffix()) + .isEqualTo("my-app azure-cosmos-encryption/2.28.0"); + assertThat(userAgentContainer.getUserAgent()) + .endsWith("my-app azure-cosmos-encryption/2.28.0|F2"); + } + + @Test(groups = {"unit"}, timeOut = TIMEOUT) + public void explicitFeatureFlagSurvivesFeatureAndSuffixUpdates() { + UserAgentContainer userAgentContainer = new UserAgentContainer(); + userAgentContainer.addFeatureEnabledFlag(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); + userAgentContainer.addFeatureEnabledFlag(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); + assertThat(userAgentContainer.getUserAgent()).endsWith("|F80"); + + userAgentContainer.setSuffix("my-app"); + userAgentContainer.setFeatureEnabledFlagsAsSuffix( + new HashSet<>(Arrays.asList(UserAgentFeatureFlags.ThinClient))); + userAgentContainer.appendSuffix("azure-cosmos-encryption/3.0.0"); + assertThat(userAgentContainer.getUserAgent()).endsWith("my-app azure-cosmos-encryption/3.0.0|F84"); + assertThat(userAgentContainer.getSuffix()).isEqualTo("my-app azure-cosmos-encryption/3.0.0"); + + userAgentContainer.setFeatureEnabledFlagsAsSuffix( + new HashSet<>(Arrays.asList(UserAgentFeatureFlags.PerPartitionCircuitBreaker))); + assertThat(userAgentContainer.getUserAgent()).endsWith("my-app azure-cosmos-encryption/3.0.0|F82"); + userAgentContainer.setSuffix("new-app"); + assertThat(userAgentContainer.getUserAgent()).endsWith("new-app|F80"); + } + + @Test(groups = {"unit"}, timeOut = TIMEOUT) + public void concurrentReadersObserveCompleteUserAgentSnapshots() throws Exception { + UserAgentContainer userAgentContainer = new UserAgentContainer(); + userAgentContainer.setSuffix("my-app"); + userAgentContainer.setFeatureEnabledFlagsAsSuffix( + new HashSet<>(Arrays.asList(UserAgentFeatureFlags.PerPartitionCircuitBreaker))); + userAgentContainer.addFeatureEnabledFlag(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); + + ExecutorService executor = Executors.newFixedThreadPool(5); + CountDownLatch start = new CountDownLatch(1); + List> futures = new ArrayList<>(); + + try { + futures.add(executor.submit(() -> { + start.await(); + for (int i = 0; i < 1_000; i++) { + userAgentContainer.appendSuffix("suffix-" + i); + } + return null; + })); + + for (int reader = 0; reader < 4; reader++) { + futures.add(executor.submit(() -> { + start.await(); + for (int i = 0; i < 10_000; i++) { + String userAgent = userAgentContainer.getUserAgent(); + if (!userAgent.endsWith("|F82")) { + throw new AssertionError("Observed incomplete user-agent snapshot: " + userAgent); + } + } + return null; + })); + } + + start.countDown(); + for (Future future : futures) { + future.get(); + } + } finally { + executor.shutdownNow(); + } + } + private String getUserAgentFixedPart() { String osName = System.getProperty("os.name"); if (osName == null) { diff --git a/sdk/cosmos/azure-cosmos/CHANGELOG.md b/sdk/cosmos/azure-cosmos/CHANGELOG.md index 27ed8439dfde3..14bd38797317b 100644 --- a/sdk/cosmos/azure-cosmos/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos/CHANGELOG.md @@ -15,6 +15,7 @@ * Fixed the Direct mode (RNTBD) encoding of the `x-ms-cosmos-workload-id` header, which was sent with the wrong token ID (`0x00DC`) and type (`Byte`) instead of `0x00E7` and `UShort`. - See [PR 50673](https://github.com/Azure/azure-sdk-for-java/pull/50673) #### Other Changes +* Updated Gateway and thin-client request headers to include user-agent feature flags. - See PR [50580](https://github.com/Azure/azure-sdk-for-java/pull/50580). * Updated Netty to `4.2.19.Final`, Reactor Netty to `1.3.7`, and Reactor Core to `3.8.7`. Migrated direct TCP event loops to the Netty 4.2 I/O handler API while preserving pooled buffers and explicit TLS validation settings. * Added a compact `ppaf` bookmark to each data-plane attempt in `CosmosDiagnostics`, containing the current per-partition write region, failed regions, and the time it was designated, or an empty object when no override is active. diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosAsyncClient.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosAsyncClient.java index 9d0b08d1d4f17..a97230c981384 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosAsyncClient.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosAsyncClient.java @@ -20,6 +20,7 @@ import com.azure.cosmos.implementation.RequestOptions; import com.azure.cosmos.implementation.ResourceType; import com.azure.cosmos.implementation.Strings; +import com.azure.cosmos.implementation.UserAgentFeatureFlags; import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.implementation.WriteRetryPolicy; import com.azure.cosmos.implementation.clienttelemetry.ClientMetricsDiagnosticsHandler; @@ -909,6 +910,16 @@ public String getUserAgent(CosmosAsyncClient client) { return client.getUserAgent(); } + @Override + public void appendUserAgentSuffix(CosmosAsyncClient client, String suffix) { + client.asyncDocumentClient.appendUserAgentSuffix(suffix); + } + + @Override + public void addUserAgentFeatureFlag(CosmosAsyncClient client, UserAgentFeatureFlags userAgentFeatureFlag) { + client.asyncDocumentClient.addUserAgentFeatureFlag(userAgentFeatureFlag); + } + @Override public CosmosMeterOptions getMeterOptions(CosmosAsyncClient client, CosmosMetricName name) { return clientTelemetryConfigAccessor() diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/AsyncDocumentClient.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/AsyncDocumentClient.java index 25c438f9249de..840e67ee702ab 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/AsyncDocumentClient.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/AsyncDocumentClient.java @@ -420,6 +420,13 @@ default void appendUserAgentSuffix(String suffix) { // no-op default for binary compatibility } + /** + * Adds an explicitly enabled user-agent feature or configuration flag. + * + * @param userAgentFeatureFlag the flag to add + */ + void addUserAgentFeatureFlag(UserAgentFeatureFlags userAgentFeatureFlag); + /** * Gets the boolean which indicates whether to only return the headers and status code in Cosmos DB response * in case of Create, Update and Delete operations on CosmosItem. diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ImplementationBridgeHelpers.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ImplementationBridgeHelpers.java index 92ef82a656991..eb743be4229be 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ImplementationBridgeHelpers.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ImplementationBridgeHelpers.java @@ -1503,6 +1503,8 @@ public interface CosmosAsyncClientAccessor { boolean isEndpointDiscoveryEnabled(CosmosAsyncClient client); String getConnectionMode(CosmosAsyncClient client); String getUserAgent(CosmosAsyncClient client); + void appendUserAgentSuffix(CosmosAsyncClient client, String suffix); + void addUserAgentFeatureFlag(CosmosAsyncClient client, UserAgentFeatureFlags userAgentFeatureFlag); CosmosMeterOptions getMeterOptions(CosmosAsyncClient client, CosmosMetricName name); boolean isEffectiveContentResponseOnWriteEnabled( CosmosAsyncClient client, diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java index e1e42c1ad93dd..c9440826ff0d6 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java @@ -1217,39 +1217,12 @@ public void appendUserAgentSuffix(String suffix) { return; } - // Check for duplicate using token matching to prevent unbounded growth when - // multiple encryption clients wrap the same CosmosAsyncClient - String currentSuffix = this.userAgentContainer.getSuffix(); - if (StringUtils.isNotEmpty(currentSuffix)) { - for (String token : currentSuffix.split("\\s+")) { - if (trimmedSuffix.equals(token)) { - return; - } - } - } - - // Preserve feature flags ("|F...") which are appended to userAgent directly - // by setFeatureEnabledFlagsAsSuffix and would be lost when setSuffix overwrites userAgent - String currentUserAgent = this.userAgentContainer.getUserAgent(); - String featureFlagsSuffix = null; - int featureFlagsIndex = currentUserAgent.indexOf("|F"); - if (featureFlagsIndex >= 0) { - featureFlagsSuffix = currentUserAgent.substring(featureFlagsIndex); - } - - String newSuffix; - if (StringUtils.isNotEmpty(currentSuffix)) { - newSuffix = currentSuffix + " " + trimmedSuffix; - } else { - newSuffix = trimmedSuffix; - } - - this.userAgentContainer.setSuffix(newSuffix); + this.userAgentContainer.appendSuffix(trimmedSuffix); + } - // Re-apply feature flags since setSuffix overwrites the userAgent string - if (StringUtils.isNotEmpty(featureFlagsSuffix)) { - this.addUserAgentSuffix(this.userAgentContainer, EnumSet.allOf(UserAgentFeatureFlags.class)); - } + @Override + public void addUserAgentFeatureFlag(UserAgentFeatureFlags userAgentFeatureFlag) { + this.userAgentContainer.addFeatureEnabledFlag(userAgentFeatureFlag); } @Override @@ -1702,6 +1675,9 @@ private static Flux> getFeedResponseFluxWithTimeout( private void addUserAgentSuffix(UserAgentContainer userAgentContainer, Set userAgentFeatureFlags) { + // The encryption SDK registers its opt-out explicitly, not through core feature evaluation. + userAgentFeatureFlags.remove(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); + if (!this.globalPartitionEndpointManagerForPerPartitionAutomaticFailover.isPerPartitionAutomaticFailoverEnabled()) { userAgentFeatureFlags.remove(UserAgentFeatureFlags.PerPartitionAutomaticFailover); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxGatewayStoreModel.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxGatewayStoreModel.java index a25ba5c25d8b4..1f708e178de4e 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxGatewayStoreModel.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxGatewayStoreModel.java @@ -107,6 +107,7 @@ private static ImplementationBridgeHelpers.CosmosExceptionHelper.CosmosException private final Map additionalHeaders; private final CosmosClientTelemetryConfig clientTelemetryConfig; private final ConcurrentHashMap serviceEndpointMetricTags; + private final UserAgentContainer userAgentContainer; public RxGatewayStoreModel( DiagnosticsClientContext clientContext, @@ -143,6 +144,7 @@ public RxGatewayStoreModel( userAgentContainer = new UserAgentContainer(); } + this.userAgentContainer = userAgentContainer; this.defaultHeaders = this.getDefaultHeaders(apiType, userAgentContainer); this.defaultConsistencyLevel = defaultConsistencyLevel; @@ -166,6 +168,7 @@ public RxGatewayStoreModel(RxGatewayStoreModel inner) { this.httpClient = inner.httpClient; this.sessionContainer = inner.sessionContainer; this.additionalHeaders = inner.additionalHeaders; + this.userAgentContainer = inner.userAgentContainer; } public Tag getServiceEndpointMetricTag(URI requestUri) { @@ -569,6 +572,8 @@ private HttpHeaders getHttpRequestHeaders(Map headers) { } } + httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, this.getCurrentUserAgent()); + // Add override headers. if (headers != null) { for (Entry entry : headers.entrySet()) { @@ -1168,6 +1173,10 @@ public Map getDefaultHeaders() { return this.defaultHeaders; } + protected String getCurrentUserAgent() { + return this.userAgentContainer.getUserAgent(); + } + private void captureSessionToken(RxDocumentServiceRequest request, Map responseHeaders) { if (request.getResourceType() == ResourceType.DocumentCollection && request.getOperationType() == OperationType.Delete) { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ThinClientStoreModel.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ThinClientStoreModel.java index f72b9d67b8dc0..c3d123cc7ace0 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ThinClientStoreModel.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ThinClientStoreModel.java @@ -435,6 +435,7 @@ private HttpHeaders getHttpHeaders() { httpHeaders.set(header.getKey(), header.getValue()); } + httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, this.getCurrentUserAgent()); return httpHeaders; } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserAgentContainer.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserAgentContainer.java index ddffd20ae2e67..350e594e6e498 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserAgentContainer.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserAgentContainer.java @@ -7,9 +7,9 @@ import java.text.Normalizer; import java.util.Locale; +import java.util.Objects; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Pattern; /** @@ -21,12 +21,12 @@ public class UserAgentContainer { private static final int MAX_USER_AGENT_LENGTH = 255; private final int maxSuffixLength; private final String baseUserAgent; - private final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(); - private final ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock(); - private final ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock(); - private String suffix; - private String userAgent; + private final ReentrantLock writeLock = new ReentrantLock(); + private volatile String suffix; + private volatile String userAgent; private String baseUserAgentWithSuffix; + private int featureFlags; + private int additionalFeatureFlags; public final static String AZSDK_USERAGENT_PREFIX = "azsdk-java-"; public final static String BASE_USER_AGENT_STRING = Utils.getUserAgent( @@ -57,14 +57,29 @@ public void setFeatureEnabledFlagsAsSuffix(Set userAgentF writeLock.lock(); try { - int value = 0; + this.featureFlags = 0; for (UserAgentFeatureFlags userAgentFeatureFlag : userAgentFeatureFlags) { - value += userAgentFeatureFlag.getValue(); + this.featureFlags |= userAgentFeatureFlag.getValue(); } - this.userAgent = !Strings.isNullOrEmpty(this.baseUserAgentWithSuffix) ? this.baseUserAgentWithSuffix : this.baseUserAgent; - this.userAgent = this.userAgent + "|F" + Integer.toHexString(value).toUpperCase(Locale.ROOT); + this.userAgent = getUserAgentWithFeatureFlags(); + } finally { + writeLock.unlock(); + } + } + + /** + * Adds an explicitly enabled flag, preserving it when evaluated feature flags are refreshed. + * + * @param userAgentFeatureFlag the flag to add + */ + public void addFeatureEnabledFlag(UserAgentFeatureFlags userAgentFeatureFlag) { + Objects.requireNonNull(userAgentFeatureFlag, "userAgentFeatureFlag"); + writeLock.lock(); + try { + this.additionalFeatureFlags |= userAgentFeatureFlag.getValue(); + this.userAgent = getUserAgentWithFeatureFlags(); } finally { writeLock.unlock(); } @@ -73,29 +88,61 @@ public void setFeatureEnabledFlagsAsSuffix(Set userAgentF public void setSuffix(String suffix) { writeLock.lock(); try { - if (suffix == null) { - suffix = ""; - } + this.featureFlags = 0; + this.userAgent = this.setSuffixInternal(suffix) + getFeatureFlagsSuffix(); + } finally { + writeLock.unlock(); + } + } + + public void appendSuffix(String suffix) { + if (Strings.isNullOrEmpty(suffix)) { + return; + } - if (suffix.length() > maxSuffixLength) { - suffix = suffix.substring(0, maxSuffixLength); + writeLock.lock(); + try { + for (String token : this.suffix.split("\\s+")) { + if (suffix.equals(token)) { + return; + } } - this.suffix = suffix; - this.userAgent = stripNonAsciiCharacters(baseUserAgent.concat(" ").concat(this.suffix)); - this.baseUserAgentWithSuffix = this.userAgent; + String appendedSuffix = Strings.isNullOrEmpty(this.suffix) + ? suffix + : this.suffix + " " + suffix; + this.userAgent = this.setSuffixInternal(appendedSuffix) + getFeatureFlagsSuffix(); } finally { writeLock.unlock(); } } public String getUserAgent() { - readLock.lock(); - try { - return this.userAgent; - } finally { - readLock.unlock(); + return this.userAgent; + } + + private String getUserAgentWithFeatureFlags() { + return (!Strings.isNullOrEmpty(this.baseUserAgentWithSuffix) + ? this.baseUserAgentWithSuffix : this.baseUserAgent) + getFeatureFlagsSuffix(); + } + + private String getFeatureFlagsSuffix() { + int value = this.featureFlags | this.additionalFeatureFlags; + return value == 0 ? "" : "|F" + Integer.toHexString(value).toUpperCase(Locale.ROOT); + } + + private String setSuffixInternal(String suffix) { + if (suffix == null) { + suffix = ""; } + + if (suffix.length() > maxSuffixLength) { + suffix = suffix.substring(0, maxSuffixLength); + } + + this.suffix = suffix; + this.baseUserAgentWithSuffix = stripNonAsciiCharacters(baseUserAgent.concat(" ").concat(this.suffix)); + return this.baseUserAgentWithSuffix; } private static String stripNonAsciiCharacters(String input) { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserAgentFeatureFlags.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserAgentFeatureFlags.java index 450ee186186fb..3579918f124b4 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserAgentFeatureFlags.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserAgentFeatureFlags.java @@ -4,7 +4,7 @@ package com.azure.cosmos.implementation; /** - * An enum representing various flags whose opt-in context will appear in the user agent suffix. + * An enum representing feature and configuration flags that appear in the user agent suffix. *

* IMPORTANT: When adding a new flag, please ensure the following: *

    @@ -24,7 +24,8 @@ public enum UserAgentFeatureFlags { // Bit 6 (1 << 6) is reserved in the Java SDK for HTTP/2 PING keepalive health. // Cross-SDK reservation in .NET (UserAgentFeatureFlags.cs) will be tracked // separately and is not a blocker for surfacing this flag in Java telemetry. - Http2PingHealth(1 << 6); + Http2PingHealth(1 << 6), + EncryptionMixedArrayOptOut(1 << 7); private final int value;