From 5fe1bc5ea13be3ad99d2781cbd1762b64cff6a64 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Thu, 12 Nov 2026 15:30:47 -0500 Subject: [PATCH 01/24] Fix mixed-array client-side encryption Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure-cosmos-encryption/CHANGELOG.md | 1 + .../implementation/EncryptionProcessor.java | 129 ++++-------------- .../EncryptionProcessorAndSettingsTest.java | 48 +++++++ 3 files changed, 74 insertions(+), 104 deletions(-) diff --git a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md index 6ba5e91018f4f..facbb3598a86a 100644 --- a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md @@ -7,6 +7,7 @@ #### Breaking Changes #### Bugs Fixed +* Fixed client-side encryption and decryption of mixed-type arrays in item and patch serialization. #### Other Changes 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..fd20d2112e24a 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 @@ -365,46 +365,19 @@ 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); + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode nodeInArray = arrayNode.get(i); + if (nodeInArray.isObject() || nodeInArray.isArray()) { + arrayNode.set(i, encryptAndSerializePatchProperty(encryptionSettings, nodeInArray, propertyName)); + } else if (!nodeInArray.isNull()) { + arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, + nodeInArray, StringUtils.EMPTY))); } } return arrayNode; - } else { - encryptAndSerializeValue(encryptionSettings, null, propertyValueHolder, propertyName); + } else if (!propertyValueHolder.isNull()) { + return BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, propertyValueHolder, + propertyName)); } return propertyValueHolder; } @@ -425,40 +398,14 @@ 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(); - } - 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 { - 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); + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode nodeInArray = arrayNode.get(i); + if (nodeInArray.isObject() || nodeInArray.isArray()) { + encryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, + StringUtils.EMPTY); + } else if (!nodeInArray.isNull()) { + arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, + nodeInArray, StringUtils.EMPTY))); } } } else { @@ -582,41 +529,15 @@ 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(); - } - 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(), + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode nodeInArray = arrayNode.get(i); + if (nodeInArray.isObject() || nodeInArray.isArray()) { + decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, + StringUtils.EMPTY); + } else if (!nodeInArray.isNull()) { + arrayNode.set(i, decryptAndSerializeValue(encryptionSettings, null, nodeInArray, StringUtils.EMPTY)); } - arrayNode.removeAll(); - for (JsonNode encryptedValue : decryptedArray) { - arrayNode.add(encryptedValue); - } } } else { decryptAndSerializeValue(encryptionSettings, (ObjectNode) objectNode, propertyValueHolder, propertyName); 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..96a2b4e026891 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 @@ -273,4 +273,52 @@ public void encryptEmptyArray() throws Exception { CosmosItemSerializer.DEFAULT_SERIALIZER).block().getLeft()); assertThat(output).isEqualTo(json); } + + @Test(groups = {"unit"}, timeOut = TIMEOUT) + public void encryptPatchMixedArray() throws Exception { + CosmosAsyncContainer cosmosAsyncContainer = Mockito.mock(CosmosAsyncContainer.class); + CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = Mockito.mock(CosmosEncryptionAsyncClient.class); + 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); + + EncryptionProcessor encryptionProcessor = new EncryptionProcessor(cosmosAsyncContainer, + cosmosEncryptionAsyncClient); + 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()); + } } From e3f6230ec31261638763b9ed33309620120d6fea Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Tue, 17 Nov 2026 20:14:36 -0500 Subject: [PATCH 02/24] Report legacy mixed-array decryption failures Fail array decryption with actionable migration guidance while preserving the original cause. Document the upgrade break and cover legacy scalar representations and authentication failures. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure-cosmos-encryption/CHANGELOG.md | 1 + sdk/cosmos/azure-cosmos-encryption/README.md | 23 +++++ .../implementation/EncryptionProcessor.java | 17 +++- .../EncryptionProcessorAndSettingsTest.java | 91 ++++++++++++++++--- 4 files changed, 115 insertions(+), 17 deletions(-) diff --git a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md index facbb3598a86a..3bf52c7b3c679 100644 --- a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md @@ -5,6 +5,7 @@ #### Features Added #### Breaking Changes +* Reading legacy mixed-type arrays containing unencrypted scalar elements now fails with `IllegalStateException` and migration guidance. These items must be read with the SDK version that wrote them and rewritten with the corrected writer. See [Legacy mixed-type arrays](README.md#legacy-mixed-type-arrays). #### Bugs Fixed * Fixed client-side encryption and decryption of mixed-type arrays in item and patch serialization. diff --git a/sdk/cosmos/azure-cosmos-encryption/README.md b/sdk/cosmos/azure-cosmos-encryption/README.md index f7b6414ad14f6..a67ed6a9e35ab 100644 --- a/sdk/cosmos/azure-cosmos-encryption/README.md +++ b/sdk/cosmos/azure-cosmos-encryption/README.md @@ -151,6 +151,29 @@ 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. + +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 to recover their decrypted values. +3. Rewrite the complete decrypted items using the corrected SDK's encryption-enabled writer. Use ETags to prevent + overwriting concurrent changes; do not first read the legacy items through the corrected reader. +4. Resume normal access using the corrected SDK 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/implementation/EncryptionProcessor.java b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionProcessor.java index fd20d2112e24a..770d6b00f2577 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 @@ -533,10 +533,18 @@ public void decryptAndSerializeProperty(EncryptionSettings encryptionSettings, J JsonNode nodeInArray = arrayNode.get(i); if (nodeInArray.isObject() || nodeInArray.isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, - StringUtils.EMPTY); + propertyName); } else if (!nodeInArray.isNull()) { - arrayNode.set(i, decryptAndSerializeValue(encryptionSettings, null, nodeInArray, - StringUtils.EMPTY)); + try { + arrayNode.set(i, decryptAndSerializeValue(encryptionSettings, null, nodeInArray, + StringUtils.EMPTY)); + } catch (MicrosoftDataEncryptionException | IOException | IllegalArgumentException ex) { + throw new IllegalStateException("Unable to decrypt array element at index " + i + + " in encrypted property '/" + propertyName + "'. Mixed-type arrays written by previous " + + "SDK versions may contain unencrypted scalar values. If this is legacy data, read the " + + "item using the SDK version that wrote it and rewrite the decrypted item using the " + + "current SDK. Otherwise, check the encryption key and ciphertext integrity.", ex); + } } } } else { @@ -556,6 +564,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/implementation/EncryptionProcessorAndSettingsTest.java b/sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/implementation/EncryptionProcessorAndSettingsTest.java index 96a2b4e026891..0c9de36eb2711 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 { @@ -276,20 +282,7 @@ public void encryptEmptyArray() throws Exception { @Test(groups = {"unit"}, timeOut = TIMEOUT) public void encryptPatchMixedArray() throws Exception { - CosmosAsyncContainer cosmosAsyncContainer = Mockito.mock(CosmosAsyncContainer.class); - CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = Mockito.mock(CosmosEncryptionAsyncClient.class); - 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); - - EncryptionProcessor encryptionProcessor = new EncryptionProcessor(cosmosAsyncContainer, - cosmosEncryptionAsyncClient); + EncryptionProcessor encryptionProcessor = createEncryptionProcessor(); JsonNode patchValue = OBJECT_MAPPER.readTree( "[{\"label\":\"patched\"},\"PATCH_SECRET\",[\"NESTED_SECRET\"],null,42,{\"tail\":\"TAIL_SECRET\"}]"); JsonNode expectedValue = patchValue.deepCopy(); @@ -321,4 +314,74 @@ public void encryptPatchMixedArray() throws Exception { 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("SDK version that wrote it") + .hasMessageContaining("rewrite the decrypted item") + .hasMessageNotContaining("secret") + .hasMessageNotContaining("LEGACY_SECRET!") + .hasMessageNotContaining("YWJjZA=="); + } + + @Test(groups = {"unit"}, timeOut = TIMEOUT) + public void decryptArrayPreservesAuthenticationFailure() throws Exception { + EncryptionProcessor encryptionProcessor = createEncryptionProcessor(); + 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 encryption key and ciphertext integrity"); + } + + private EncryptionProcessor createEncryptionProcessor() throws JsonProcessingException { + CosmosAsyncContainer cosmosAsyncContainer = Mockito.mock(CosmosAsyncContainer.class); + CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = Mockito.mock(CosmosEncryptionAsyncClient.class); + 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); + } } From a561f5c5b23871d65214a3351508d83099d53db0 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Tue, 17 Nov 2026 20:43:37 -0500 Subject: [PATCH 03/24] Fix encryption changelog migration link Use an absolute URL to satisfy the Verify Links check. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md index 3bf52c7b3c679..a11a6b0e4e241 100644 --- a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md @@ -5,7 +5,7 @@ #### Features Added #### Breaking Changes -* Reading legacy mixed-type arrays containing unencrypted scalar elements now fails with `IllegalStateException` and migration guidance. These items must be read with the SDK version that wrote them and rewritten with the corrected writer. See [Legacy mixed-type arrays](README.md#legacy-mixed-type-arrays). +* Reading legacy mixed-type arrays containing unencrypted scalar elements now fails with `IllegalStateException` and migration guidance. These items must be read with the SDK version that wrote them and rewritten with the corrected writer. See [Legacy mixed-type arrays](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/cosmos/azure-cosmos-encryption/README.md#legacy-mixed-type-arrays). #### Bugs Fixed * Fixed client-side encryption and decryption of mixed-type arrays in item and patch serialization. From 4b8cf091bf6d6222f8e42c4e90d76eaa67c9f3d0 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Tue, 17 Nov 2026 20:45:16 -0500 Subject: [PATCH 04/24] Align encryption changelog PR references Match azure-cosmos changelog formatting for the mixed-array fix and upgrade guidance. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md index a11a6b0e4e241..6cccd0192769b 100644 --- a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md @@ -5,10 +5,10 @@ #### Features Added #### Breaking Changes -* Reading legacy mixed-type arrays containing unencrypted scalar elements now fails with `IllegalStateException` and migration guidance. These items must be read with the SDK version that wrote them and rewritten with the corrected writer. See [Legacy mixed-type arrays](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/cosmos/azure-cosmos-encryption/README.md#legacy-mixed-type-arrays). +* Reading legacy mixed-type arrays containing unencrypted scalar elements now fails with `IllegalStateException` and migration guidance. These items must be read with the SDK version that wrote them and rewritten with the corrected writer. See [Legacy mixed-type arrays](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 in item and patch serialization. +* Fixed client-side encryption and decryption of mixed-type arrays in item and patch serialization. - See [PR 51247](https://github.com/Azure/azure-sdk-for-java/pull/51247) #### Other Changes From eb0f6b26a5444fdaf7a291584ae7c50bb59ffa7c Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Thu, 19 Nov 2026 07:41:22 -0500 Subject: [PATCH 05/24] Add mixed-array encryption compatibility opt-out Support JVM and environment opt-out with a shared client configuration snapshot. Preserve legacy traversal for coordinated migration and identify explicit opt-out in the user agent. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure-cosmos-encryption/CHANGELOG.md | 4 +- sdk/cosmos/azure-cosmos-encryption/README.md | 33 +++- .../CosmosEncryptionAsyncClient.java | 21 ++- .../encryption/implementation/Constants.java | 1 + .../implementation/EncryptionConfigs.java | 51 ++++++ ...EncryptionImplementationBridgeHelpers.java | 2 + .../implementation/EncryptionProcessor.java | 34 +++- .../CosmosEncryptionAsyncClientUnitTest.java | 80 +++++++++- .../EncryptionProcessorAndSettingsTest.java | 146 +++++++++++++++++- 9 files changed, 346 insertions(+), 26 deletions(-) create mode 100644 sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionConfigs.java diff --git a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md index 6cccd0192769b..8725d1b06b22e 100644 --- a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md @@ -5,10 +5,10 @@ #### Features Added #### Breaking Changes -* Reading legacy mixed-type arrays containing unencrypted scalar elements now fails with `IllegalStateException` and migration guidance. These items must be read with the SDK version that wrote them and rewritten with the corrected writer. See [Legacy mixed-type arrays](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) +* 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 in item and patch serialization. - See [PR 51247](https://github.com/Azure/azure-sdk-for-java/pull/51247) +* 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 a67ed6a9e35ab..e74fa95e3a370 100644 --- a/sdk/cosmos/azure-cosmos-encryption/README.md +++ b/sdk/cosmos/azure-cosmos-encryption/README.md @@ -163,13 +163,38 @@ The corrected reader decrypts every non-null scalar array element. If an element 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. Explicit opt-out adds `encryption-mixed-arrays-disabled` to the underlying +Cosmos client's user-agent suffix, alongside the encryption SDK version. Default and explicit `true` settings +do not add this marker. The suffix is client-wide, including requests sharing that underlying Cosmos client. +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 to recover their decrypted values. -3. Rewrite the complete decrypted items using the corrected SDK's encryption-enabled writer. Use ETags to prevent - overwriting concurrent changes; do not first read the legacy items through the corrected reader. -4. Resume normal access using the corrected SDK after the affected items have been migrated. +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. 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..88eab2afb0984 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 @@ -14,8 +14,10 @@ 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.AsyncDocumentClient; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.RequestOptions; @@ -46,6 +48,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 +65,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 +97,10 @@ EncryptionKeyStoreProviderImpl getEncryptionKeyStoreProviderImpl() { return encryptionKeyStoreProviderImpl; } + boolean isMixedArrayEncryptionEnabled() { + return this.mixedArrayEncryptionEnabled; + } + Mono getContainerPropertiesAsync( CosmosAsyncContainer container, boolean shouldForceRefresh) { @@ -195,9 +203,11 @@ public CosmosAsyncClient getCosmosAsyncClient() { private void appendEncryptionUserAgentSuffix() { try { - CosmosBridgeInternal - .getAsyncDocumentClient(this.cosmosAsyncClient) - .appendUserAgentSuffix(Constants.USER_AGENT_SUFFIX); + AsyncDocumentClient documentClient = CosmosBridgeInternal.getAsyncDocumentClient(this.cosmosAsyncClient); + documentClient.appendUserAgentSuffix(Constants.USER_AGENT_SUFFIX); + if (!this.mixedArrayEncryptionEnabled) { + documentClient.appendUserAgentSuffix(Constants.MIXED_ARRAYS_DISABLED_USER_AGENT_SUFFIX); + } } catch (Exception e) { LOGGER.warn("Failed to append encryption SDK user agent suffix", e); } @@ -273,6 +283,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/Constants.java b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/Constants.java index 65c3275693b7d..2006f4b7eb644 100644 --- a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/Constants.java +++ b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/Constants.java @@ -15,6 +15,7 @@ public class Constants { public static final String CURRENT_NAME = PROPERTIES.getOrDefault("name", "azure-cosmos-encryption"); public static final String CURRENT_VERSION = PROPERTIES.getOrDefault("version", "unknown"); public static final String USER_AGENT_SUFFIX = CURRENT_NAME + "/" + CURRENT_VERSION; + public static final String MIXED_ARRAYS_DISABLED_USER_AGENT_SUFFIX = "encryption-mixed-arrays-disabled"; public static final String INTENDED_COLLECTION_RID_HEADER = "x-ms-cosmos-intended-collection-rid"; 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 770d6b00f2577..d88c7545c0e58 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,11 +368,13 @@ public JsonNode encryptAndSerializePatchProperty(EncryptionSettings encryptionSe else if (propertyValueHolder.isArray()) { assert propertyValueHolder instanceof ArrayNode; ArrayNode arrayNode = (ArrayNode) propertyValueHolder; + boolean traverseContainers = shouldTraverseArrayContainers(arrayNode); + boolean processScalars = this.mixedArrayEncryptionEnabled || !traverseContainers; for (int i = 0; i < arrayNode.size(); i++) { JsonNode nodeInArray = arrayNode.get(i); - if (nodeInArray.isObject() || nodeInArray.isArray()) { + if (traverseContainers && (nodeInArray.isObject() || nodeInArray.isArray())) { arrayNode.set(i, encryptAndSerializePatchProperty(encryptionSettings, nodeInArray, propertyName)); - } else if (!nodeInArray.isNull()) { + } else if (processScalars && (!this.mixedArrayEncryptionEnabled || !nodeInArray.isNull())) { arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, nodeInArray, StringUtils.EMPTY))); } @@ -398,12 +403,14 @@ public void encryptAndSerializeProperty(EncryptionSettings encryptionSettings, J } } else if (propertyValueHolder.isArray()) { ArrayNode arrayNode = (ArrayNode) propertyValueHolder; + boolean traverseContainers = shouldTraverseArrayContainers(arrayNode); + boolean processScalars = this.mixedArrayEncryptionEnabled || !traverseContainers; for (int i = 0; i < arrayNode.size(); i++) { JsonNode nodeInArray = arrayNode.get(i); - if (nodeInArray.isObject() || nodeInArray.isArray()) { + if (traverseContainers && (nodeInArray.isObject() || nodeInArray.isArray())) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); - } else if (!nodeInArray.isNull()) { + } else if (processScalars && (!this.mixedArrayEncryptionEnabled || !nodeInArray.isNull())) { arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, nodeInArray, StringUtils.EMPTY))); } @@ -413,6 +420,12 @@ public void encryptAndSerializeProperty(EncryptionSettings encryptionSettings, J } } + private boolean shouldTraverseArrayContainers(ArrayNode arrayNode) { + // Legacy traversal chooses one strategy for the entire array from its first element. + return this.mixedArrayEncryptionEnabled || (arrayNode.size() > 0 + && (arrayNode.get(0).isObject() || arrayNode.get(0).isArray())); + } + public String encryptAndSerializeValue(EncryptionSettings encryptionSettings, String propertyValue, String propertyName) throws MicrosoftDataEncryptionException { JsonNode propertyValueHolder = toJsonNode(propertyValue.getBytes(StandardCharsets.US_ASCII), TypeMarker.STRING); if (propertyName.equals(Constants.PROPERTY_NAME_ID)) { @@ -529,12 +542,14 @@ public void decryptAndSerializeProperty(EncryptionSettings encryptionSettings, J } } else if (propertyValueHolder.isArray()) { ArrayNode arrayNode = (ArrayNode) propertyValueHolder; + boolean traverseContainers = shouldTraverseArrayContainers(arrayNode); + boolean processScalars = this.mixedArrayEncryptionEnabled || !traverseContainers; for (int i = 0; i < arrayNode.size(); i++) { JsonNode nodeInArray = arrayNode.get(i); - if (nodeInArray.isObject() || nodeInArray.isArray()) { + if (traverseContainers && (nodeInArray.isObject() || nodeInArray.isArray())) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, propertyName); - } else if (!nodeInArray.isNull()) { + } else if (processScalars && (!this.mixedArrayEncryptionEnabled || !nodeInArray.isNull())) { try { arrayNode.set(i, decryptAndSerializeValue(encryptionSettings, null, nodeInArray, StringUtils.EMPTY)); @@ -543,7 +558,12 @@ public void decryptAndSerializeProperty(EncryptionSettings encryptionSettings, J + " in encrypted property '/" + propertyName + "'. Mixed-type arrays written by previous " + "SDK versions may contain unencrypted scalar values. If this is legacy data, read the " + "item using the SDK version that wrote it and rewrite the decrypted item using the " - + "current SDK. Otherwise, check the encryption key and ciphertext integrity.", ex); + + "current SDK. Alternatively, temporarily restore legacy reads AND writes by setting " + + "-D" + EncryptionConfigs.MIXED_ARRAYS_ENABLED + "=false or " + + EncryptionConfigs.MIXED_ARRAYS_ENABLED_VARIABLE + "=false before creating clients. " + + "Legacy mode can leave scalar array elements unencrypted and cannot correctly read " + + "mixed arrays written with the fix enabled. Otherwise, check the encryption key and " + + "ciphertext integrity.", ex); } } } 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..71af4ad745708 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 @@ -10,18 +10,27 @@ import com.azure.cosmos.CosmosAsyncDatabase; import com.azure.cosmos.CosmosBridgeInternal; import com.azure.cosmos.encryption.implementation.Constants; +import com.azure.cosmos.encryption.implementation.EncryptionProcessor; +import com.azure.cosmos.encryption.implementation.EncryptionSettings; import com.azure.cosmos.implementation.AsyncDocumentClient; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.RequestOptions; +import com.azure.cosmos.implementation.RxDocumentClientImpl; +import com.azure.cosmos.implementation.UserAgentContainer; import com.azure.cosmos.models.CosmosClientEncryptionKeyProperties; import com.azure.cosmos.models.CosmosClientEncryptionKeyResponse; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.reflect.FieldUtils; import org.mockito.Mockito; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import reactor.core.publisher.Mono; import static org.assertj.core.api.Assertions.assertThat; public class CosmosEncryptionAsyncClientUnitTest { + private static final String MIXED_ARRAYS_ENABLED_PROPERTY = "COSMOS.ENCRYPTION_MIXED_ARRAYS_ENABLED"; private final static ImplementationBridgeHelpers.CosmosAsyncClientEncryptionKeyHelper.CosmosAsyncClientEncryptionKeyAccessor cosmosAsyncClientEncryptionKeyAccessor = ImplementationBridgeHelpers.CosmosAsyncClientEncryptionKeyHelper.getCosmosAsyncClientEncryptionKeyAccessor(); @@ -60,25 +69,82 @@ 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 + @DataProvider(name = "mixedArrayUserAgentSettings") + public Object[][] mixedArrayUserAgentSettings() { + return new Object[][] {{null, false}, {"true", false}, {"false", true}}; + } + + @Test(groups = {"unit"}, dataProvider = "mixedArrayUserAgentSettings", timeOut = TestSuiteBase.TIMEOUT) + public void encryptionClientAppendsUserAgentSuffix(String setting, boolean optOutExpected) throws Exception { CosmosAsyncClient mockAsyncClient = Mockito.mock(CosmosAsyncClient.class); - AsyncDocumentClient mockDocClient = Mockito.mock(AsyncDocumentClient.class); + RxDocumentClientImpl mockDocClient = Mockito.mock(RxDocumentClientImpl.class); KeyEncryptionKeyResolver mockKeyResolver = Mockito.mock(KeyEncryptionKeyResolver.class); + UserAgentContainer userAgent = new UserAgentContainer(); + userAgent.setSuffix("customer-app"); + FieldUtils.writeField(mockDocClient, "userAgentContainer", userAgent, true); + Mockito.doCallRealMethod().when(mockDocClient).appendUserAgentSuffix(Mockito.anyString()); + String previousValue = System.getProperty(MIXED_ARRAYS_ENABLED_PROPERTY); org.mockito.MockedStatic bridgeMock = Mockito.mockStatic(CosmosBridgeInternal.class); try { + if (setting == null) { + System.clearProperty(MIXED_ARRAYS_ENABLED_PROPERTY); + } else { + System.setProperty(MIXED_ARRAYS_ENABLED_PROPERTY, setting); + } bridgeMock.when(() -> CosmosBridgeInternal.getAsyncDocumentClient(mockAsyncClient)) .thenReturn(mockDocClient); new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); + 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); + assertThat(userAgent.getUserAgent()) + .contains("customer-app", Constants.USER_AGENT_SUFFIX); + assertThat(userAgent.getSuffix().split("\\s+")) + .containsOnlyOnce("customer-app", Constants.USER_AGENT_SUFFIX); + if (optOutExpected) { + assertThat(userAgent.getSuffix().split("\\s+")).containsOnlyOnce("encryption-mixed-arrays-disabled"); + } else { + assertThat(userAgent.getUserAgent()).doesNotContain("encryption-mixed-arrays-disabled"); + } } finally { bridgeMock.close(); + restoreMixedArraySetting(previousValue); + } + } + + @Test(groups = {"unit"}, timeOut = TestSuiteBase.TIMEOUT) + public void encryptionOptOutSnapshotMatchesUserAgent() throws Exception { + CosmosAsyncClient mockAsyncClient = Mockito.mock(CosmosAsyncClient.class); + AsyncDocumentClient mockDocClient = Mockito.mock(AsyncDocumentClient.class); + KeyEncryptionKeyResolver mockKeyResolver = Mockito.mock(KeyEncryptionKeyResolver.class); + String previousValue = System.getProperty(MIXED_ARRAYS_ENABLED_PROPERTY); + try (org.mockito.MockedStatic bridgeMock = Mockito.mockStatic(CosmosBridgeInternal.class)) { + bridgeMock.when(() -> CosmosBridgeInternal.getAsyncDocumentClient(mockAsyncClient)) + .thenReturn(mockDocClient); + System.setProperty(MIXED_ARRAYS_ENABLED_PROPERTY, "false"); + CosmosEncryptionAsyncClient client = + new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); + System.setProperty(MIXED_ARRAYS_ENABLED_PROPERTY, "true"); + + EncryptionProcessor processor = new EncryptionProcessor(Mockito.mock(CosmosAsyncContainer.class), client); + JsonNode array = new ObjectMapper().readTree("[{},42]"); + JsonNode encryptedArray = processor.encryptAndSerializePatchProperty( + Mockito.mock(EncryptionSettings.class), array, "sensitiveString"); + + assertThat(client.isMixedArrayEncryptionEnabled()).isFalse(); + assertThat(encryptedArray.get(1).asInt()).isEqualTo(42); + Mockito.verify(mockDocClient).appendUserAgentSuffix(Constants.MIXED_ARRAYS_DISABLED_USER_AGENT_SUFFIX); + } finally { + restoreMixedArraySetting(previousValue); + } + } + + private void restoreMixedArraySetting(String previousValue) { + if (previousValue == null) { + System.clearProperty(MIXED_ARRAYS_ENABLED_PROPERTY); + } else { + System.setProperty(MIXED_ARRAYS_ENABLED_PROPERTY, previousValue); } } 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 0c9de36eb2711..4445229968ac3 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 @@ -347,14 +347,27 @@ public void decryptLegacyMixedArrayReportsMigration(String arrayJson, .hasMessageContaining("encrypted property '/sensitiveString'") .hasMessageContaining("SDK version that wrote it") .hasMessageContaining("rewrite the decrypted item") + .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()); } - @Test(groups = {"unit"}, timeOut = TIMEOUT) - public void decryptArrayPreservesAuthenticationFailure() throws Exception { - EncryptionProcessor encryptionProcessor = createEncryptionProcessor(); + @DataProvider(name = "mixedArrayModes") + public Object[][] mixedArrayModes() { + return new Object[][] {{true}, {false}}; + } + + @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); @@ -370,9 +383,136 @@ public void decryptArrayPreservesAuthenticationFailure() throws Exception { .hasMessageContaining("check the encryption key and ciphertext integrity"); } + @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())); From f45ac08dc1c79ebc2e417bd2157f42cb1e36bf7a Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Thu, 24 Sep 2026 15:59:31 -0400 Subject: [PATCH 06/24] Fix Cosmos gateway user agent propagation Resolve the user agent from the shared container when gateway and thin-client requests are serialized so feature flags evaluated after store-model construction reach the wire. Add coverage for database-account and thin-client HTTP headers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit be7befe4ad93b8478d8732847f8485de97f51136) --- .../RxGatewayStoreModelTest.java | 33 +++++++++++++++++++ .../ThinClientStoreModelTest.java | 11 +++++-- .../implementation/RxGatewayStoreModel.java | 14 ++++++-- .../implementation/ThinClientStoreModel.java | 26 +++++---------- 4 files changed, 63 insertions(+), 21 deletions(-) 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..4273ac8788d0b 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,38 @@ public class RxGatewayStoreModelTest { private final static int TIMEOUT = 10000; + @Test(groups = "unit") + public void latestUserAgentIsAppliedToDatabaseAccountRequest() 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); + + userAgentContainer.setFeatureEnabledFlagsAsSuffix( + Collections.singleton(UserAgentFeatureFlags.ThinClient)); + + RxDocumentServiceRequest request = RxDocumentServiceRequest.create( + clientContext, + OperationType.Read, + ResourceType.DatabaseAccount, + "", + null, + (Object) null); + + HttpRequest httpRequest = storeModel.wrapInHttpRequest(request, new URI("https://localhost")); + + assertThat(httpRequest.headers().value(HttpConstants.HttpHeaders.USER_AGENT)) + .isEqualTo(userAgentContainer.getUserAgent()); + } + @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..b9e32409bc530 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,19 @@ public void thinClientDoesNotAddNoRetry449Header() throws Exception { Mockito.when(httpClient.send(requestCaptor.capture(), any())) .thenReturn(Mono.error(new ConnectTimeoutException())); + UserAgentContainer userAgentContainer = new UserAgentContainer(); ThinClientStoreModel storeModel = new ThinClientStoreModel( clientContext, sessionContainer, ConsistencyLevel.SESSION, - new UserAgentContainer(), + userAgentContainer, globalEndpointManager, httpClient, null); + userAgentContainer.setFeatureEnabledFlagsAsSuffix( + Collections.singleton(UserAgentFeatureFlags.ThinClient)); + RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName( clientContext, OperationType.Read, @@ -249,6 +253,9 @@ 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()); 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/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..86c04c75bffd1 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) { @@ -561,10 +564,13 @@ private HttpHeaders getHttpRequestHeaders(Map headers) { for (Entry entry : this.defaultHeaders.entrySet()) { if (!headers.containsKey(entry.getKey())) { // populate default header only if there is no overwrite by the request header + String value = HttpConstants.HttpHeaders.USER_AGENT.equals(entry.getKey()) + ? this.userAgentContainer.getUserAgent() + : entry.getValue(); if (headersNeedToBeEscaped.contains(entry.getKey())) { - httpHeaders.set(entry.getKey(), Utils.escapeNonAscii(entry.getValue())); + httpHeaders.set(entry.getKey(), Utils.escapeNonAscii(value)); } else { - httpHeaders.set(entry.getKey(), entry.getValue()); + httpHeaders.set(entry.getKey(), value); } } } @@ -1168,6 +1174,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 05195d37ee05e..ea8e0f8d6bdd4 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 @@ -44,7 +44,6 @@ public class ThinClientStoreModel extends RxGatewayStoreModel { ResourceLeakDetector.Level.ADVANCED.ordinal(); private volatile String globalDatabaseAccountName = null; - private final Map defaultHeaders; public ThinClientStoreModel( DiagnosticsClientContext clientContext, @@ -79,13 +78,6 @@ public ThinClientStoreModel( additionalHeaders, clientTelemetryConfig); - String userAgent = userAgentContainer != null - ? userAgentContainer.getUserAgent() - : UserAgentContainer.BASE_USER_AGENT_STRING; - - this.defaultHeaders = Collections.singletonMap( - HttpConstants.HttpHeaders.USER_AGENT, userAgent - ); } @Override @@ -109,7 +101,11 @@ protected Map getDefaultHeaders( // missing headers for routing (like partitionId or replicaId) // Since the Thin client proxy also needs to set the user-agent header to a different value // it is not added to the rntbd headers - just http-headers in the SDK - return this.defaultHeaders; + String userAgent = userAgentContainer != null + ? userAgentContainer.getUserAgent() + : UserAgentContainer.BASE_USER_AGENT_STRING; + + return Collections.singletonMap(HttpConstants.HttpHeaders.USER_AGENT, userAgent); } @Override @@ -327,18 +323,14 @@ public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI reque @Override public Map getDefaultHeaders() { - return this.defaultHeaders; + return Collections.singletonMap( + HttpConstants.HttpHeaders.USER_AGENT, + this.getCurrentUserAgent()); } private HttpHeaders getHttpHeaders() { HttpHeaders httpHeaders = new HttpHeaders(); - // todo: select only required headers from defaults - Map defaultHeaders = this.getDefaultHeaders(); - - for (Map.Entry header : defaultHeaders.entrySet()) { - httpHeaders.set(header.getKey(), header.getValue()); - } - + httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, this.getCurrentUserAgent()); return httpHeaders; } } From 4f22182cf443b5be2cd2e9c81841f215a94272b8 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Thu, 24 Sep 2026 16:05:03 -0400 Subject: [PATCH 07/24] Simplify Cosmos gateway default headers Avoid overridable default-header construction in the gateway base constructor. Keep transport defaults static and resolve only the mutable user-agent value when each request is serialized. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit 9b2ee77d39b77e62d81dcf30f27472326b8f43ac) --- .../implementation/RxGatewayStoreModel.java | 4 ++-- .../implementation/ThinClientStoreModel.java | 18 ------------------ 2 files changed, 2 insertions(+), 20 deletions(-) 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 86c04c75bffd1..7949a85645434 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 @@ -145,7 +145,7 @@ public RxGatewayStoreModel( } this.userAgentContainer = userAgentContainer; - this.defaultHeaders = this.getDefaultHeaders(apiType, userAgentContainer); + this.defaultHeaders = createDefaultHeaders(apiType, userAgentContainer); this.defaultConsistencyLevel = defaultConsistencyLevel; this.globalEndpointManager = globalEndpointManager; @@ -214,7 +214,7 @@ public void close() { this.serviceEndpointMetricTags.clear(); } - protected Map getDefaultHeaders( + private static Map createDefaultHeaders( ApiType apiType, UserAgentContainer userAgentContainer) { 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 ea8e0f8d6bdd4..ebf8d4d704baf 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 @@ -90,24 +90,6 @@ protected void applyGatewayRetryWithHeaders(RxDocumentServiceRequest request) { // ThinClient does not use the Gateway V1 server-side 449 retry loop. } - @Override - protected Map getDefaultHeaders( - ApiType apiType, - UserAgentContainer userAgentContainer) { - - // For ThinClient http/2 used for framing only - // All operation-level headers are only added to the rntbd-encoded message - // the thin client proxy will parse the rntbd headers (not the content!) and substitute any - // missing headers for routing (like partitionId or replicaId) - // Since the Thin client proxy also needs to set the user-agent header to a different value - // it is not added to the rntbd headers - just http-headers in the SDK - String userAgent = userAgentContainer != null - ? userAgentContainer.getUserAgent() - : UserAgentContainer.BASE_USER_AGENT_STRING; - - return Collections.singletonMap(HttpConstants.HttpHeaders.USER_AGENT, userAgent); - } - @Override public URI getRootUri(RxDocumentServiceRequest request) { // need to have thin client endpoint here From 34812111a8332dee954b16d4b43a776a6da09e86 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Thu, 24 Sep 2026 16:10:38 -0400 Subject: [PATCH 08/24] Refresh Cosmos user agent at serialization boundary Preserve the existing default-header construction and merge paths. Replace only the serialized User-Agent value immediately before gateway and thin-client HTTP requests are created. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit 234ba13e2ae38aac3ba7558359cafabe2685dabf) --- .../implementation/RxGatewayStoreModel.java | 14 ++++---- .../implementation/ThinClientStoreModel.java | 33 +++++++++++++++++-- 2 files changed, 37 insertions(+), 10 deletions(-) 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 7949a85645434..e55f83f41e4da 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 @@ -145,7 +145,7 @@ public RxGatewayStoreModel( } this.userAgentContainer = userAgentContainer; - this.defaultHeaders = createDefaultHeaders(apiType, userAgentContainer); + this.defaultHeaders = this.getDefaultHeaders(apiType, userAgentContainer); this.defaultConsistencyLevel = defaultConsistencyLevel; this.globalEndpointManager = globalEndpointManager; @@ -214,7 +214,7 @@ public void close() { this.serviceEndpointMetricTags.clear(); } - private static Map createDefaultHeaders( + protected Map getDefaultHeaders( ApiType apiType, UserAgentContainer userAgentContainer) { @@ -282,6 +282,9 @@ public void setCollectionCache(RxClientCollectionCache collectionCache) { public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI requestUri) throws Exception { HttpMethod method = getHttpMethod(request); HttpHeaders httpHeaders = this.getHttpRequestHeaders(request.getHeaders()); + if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.USER_AGENT)) { + httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, this.getCurrentUserAgent()); + } Flux contentAsByteArray = request.getContentAsByteArrayFlux(); return new HttpRequest(method, @@ -564,13 +567,10 @@ private HttpHeaders getHttpRequestHeaders(Map headers) { for (Entry entry : this.defaultHeaders.entrySet()) { if (!headers.containsKey(entry.getKey())) { // populate default header only if there is no overwrite by the request header - String value = HttpConstants.HttpHeaders.USER_AGENT.equals(entry.getKey()) - ? this.userAgentContainer.getUserAgent() - : entry.getValue(); if (headersNeedToBeEscaped.contains(entry.getKey())) { - httpHeaders.set(entry.getKey(), Utils.escapeNonAscii(value)); + httpHeaders.set(entry.getKey(), Utils.escapeNonAscii(entry.getValue())); } else { - httpHeaders.set(entry.getKey(), value); + httpHeaders.set(entry.getKey(), entry.getValue()); } } } 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 ebf8d4d704baf..54dfc28fbf007 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 @@ -44,6 +44,7 @@ public class ThinClientStoreModel extends RxGatewayStoreModel { ResourceLeakDetector.Level.ADVANCED.ordinal(); private volatile String globalDatabaseAccountName = null; + private final Map defaultHeaders; public ThinClientStoreModel( DiagnosticsClientContext clientContext, @@ -78,6 +79,13 @@ public ThinClientStoreModel( additionalHeaders, clientTelemetryConfig); + String userAgent = userAgentContainer != null + ? userAgentContainer.getUserAgent() + : UserAgentContainer.BASE_USER_AGENT_STRING; + + this.defaultHeaders = Collections.singletonMap( + HttpConstants.HttpHeaders.USER_AGENT, userAgent + ); } @Override @@ -90,6 +98,20 @@ protected void applyGatewayRetryWithHeaders(RxDocumentServiceRequest request) { // ThinClient does not use the Gateway V1 server-side 449 retry loop. } + @Override + protected Map getDefaultHeaders( + ApiType apiType, + UserAgentContainer userAgentContainer) { + + // For ThinClient http/2 used for framing only + // All operation-level headers are only added to the rntbd-encoded message + // the thin client proxy will parse the rntbd headers (not the content!) and substitute any + // missing headers for routing (like partitionId or replicaId) + // Since the Thin client proxy also needs to set the user-agent header to a different value + // it is not added to the rntbd headers - just http-headers in the SDK + return this.defaultHeaders; + } + @Override public URI getRootUri(RxDocumentServiceRequest request) { // need to have thin client endpoint here @@ -305,13 +327,18 @@ public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI reque @Override public Map getDefaultHeaders() { - return Collections.singletonMap( - HttpConstants.HttpHeaders.USER_AGENT, - this.getCurrentUserAgent()); + return this.defaultHeaders; } private HttpHeaders getHttpHeaders() { HttpHeaders httpHeaders = new HttpHeaders(); + // todo: select only required headers from defaults + Map defaultHeaders = this.getDefaultHeaders(); + + for (Map.Entry header : defaultHeaders.entrySet()) { + httpHeaders.set(header.getKey(), header.getValue()); + } + httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, this.getCurrentUserAgent()); return httpHeaders; } From 258767bb761d71b5a0b84353fab0e6f355273d56 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Thu, 24 Sep 2026 16:59:45 -0400 Subject: [PATCH 09/24] Update Cosmos changelog for user agent propagation Document that Gateway and thin-client request headers now include feature flags evaluated after transport initialization. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit 43e221c719866d98424ac175c06bb67e795d114d) --- sdk/cosmos/azure-cosmos/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/cosmos/azure-cosmos/CHANGELOG.md b/sdk/cosmos/azure-cosmos/CHANGELOG.md index 1c4347d60bde6..cfed9d280e556 100644 --- a/sdk/cosmos/azure-cosmos/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos/CHANGELOG.md @@ -14,6 +14,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 evaluated after transport initialization. - 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. From e7cac69c83d76d3ae9c9542596c25215224486c0 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Thu, 24 Sep 2026 17:01:14 -0400 Subject: [PATCH 10/24] Refine Cosmos user agent changelog entry Keep the entry focused on the externally visible header behavior. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit 04364a7ea77d7bd005de1a04aff5e78e4f9bd4c2) --- sdk/cosmos/azure-cosmos/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/cosmos/azure-cosmos/CHANGELOG.md b/sdk/cosmos/azure-cosmos/CHANGELOG.md index cfed9d280e556..63b6f3c0ba12a 100644 --- a/sdk/cosmos/azure-cosmos/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos/CHANGELOG.md @@ -14,7 +14,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 evaluated after transport initialization. - See PR [50580](https://github.com/Azure/azure-sdk-for-java/pull/50580). +* 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. From 2f1446c30e13a763097ca826fbe87cb8f4404c9c Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Mon, 28 Sep 2026 20:13:40 -0400 Subject: [PATCH 11/24] Harden Cosmos user agent propagation Publish suffix updates atomically, preserve case-insensitive request overrides, and evaluate configuration-known feature flags before the bootstrap account request. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit aedf49cc99588d4418e3554c5e18c2ddc614cbfc) --- .../RxGatewayStoreModelTest.java | 32 +++++++++++ .../UserAgentContainerTest.java | 16 ++++++ .../implementation/RxDocumentClientImpl.java | 36 ++----------- .../implementation/RxGatewayStoreModel.java | 12 ++++- .../implementation/UserAgentContainer.java | 54 ++++++++++++++++--- 5 files changed, 108 insertions(+), 42 deletions(-) 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 4273ac8788d0b..339600401f739 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 @@ -81,6 +81,38 @@ public void latestUserAgentIsAppliedToDatabaseAccountRequest() throws Exception .isEqualTo(userAgentContainer.getUserAgent()); } + @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); + + userAgentContainer.setFeatureEnabledFlagsAsSuffix( + Collections.singleton(UserAgentFeatureFlags.PerPartitionCircuitBreaker)); + + RxDocumentServiceRequest request = RxDocumentServiceRequest.create( + clientContext, + OperationType.Read, + ResourceType.DatabaseAccount, + "", + Collections.singletonMap("user-agent", "request-user-agent"), + (Object) null); + + HttpRequest httpRequest = storeModel.wrapInHttpRequest(request, new URI("https://localhost")); + + assertThat(httpRequest.headers().value(HttpConstants.HttpHeaders.USER_AGENT)) + .isEqualTo("request-user-agent"); + } + @DataProvider(name = "sessionTokenConfigProvider") public Object[][] sessionTokenConfigProvider() { return new Object[][]{ 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..3191a3a42820c 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 @@ -173,6 +173,22 @@ 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"); + } + private String getUserAgentFixedPart() { String osName = System.getProperty("os.name"); if (osName == null) { 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..89595fd8ea41b 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 @@ -944,6 +944,8 @@ public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Func }); this.globalEndpointManager.setPerPartitionAutomaticFailoverConfigModifier(this.perPartitionFailoverConfigModifier); + // Include configuration-known flags on the bootstrap account request; account-derived flags are reevaluated later. + this.addUserAgentSuffix(this.userAgentContainer, EnumSet.allOf(UserAgentFeatureFlags.class)); this.globalEndpointManager.init(); this.initializePerPartitionCircuitBreaker(); @@ -1217,39 +1219,7 @@ 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); - - // Re-apply feature flags since setSuffix overwrites the userAgent string - if (StringUtils.isNotEmpty(featureFlagsSuffix)) { - this.addUserAgentSuffix(this.userAgentContainer, EnumSet.allOf(UserAgentFeatureFlags.class)); - } + this.userAgentContainer.appendSuffix(trimmedSuffix); } @Override 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 e55f83f41e4da..e72c2b8d31dc8 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 @@ -282,7 +282,7 @@ public void setCollectionCache(RxClientCollectionCache collectionCache) { public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI requestUri) throws Exception { HttpMethod method = getHttpMethod(request); HttpHeaders httpHeaders = this.getHttpRequestHeaders(request.getHeaders()); - if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.USER_AGENT)) { + if (!containsHeaderIgnoreCase(request.getHeaders(), HttpConstants.HttpHeaders.USER_AGENT)) { httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, this.getCurrentUserAgent()); } @@ -294,6 +294,16 @@ public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI reque contentAsByteArray); } + private static boolean containsHeaderIgnoreCase(Map headers, String headerName) { + for (String name : headers.keySet()) { + if (headerName.equalsIgnoreCase(name)) { + return true; + } + } + + return false; + } + @Override public StoreResponse unwrapToStoreResponse( String endpoint, 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..809d8d8080f88 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 @@ -45,7 +45,12 @@ public UserAgentContainer() { } public String getSuffix() { - return this.suffix; + readLock.lock(); + try { + return this.suffix; + } finally { + readLock.unlock(); + } } public void setFeatureEnabledFlagsAsSuffix(Set userAgentFeatureFlags) { @@ -73,17 +78,36 @@ public void setFeatureEnabledFlagsAsSuffix(Set userAgentF public void setSuffix(String suffix) { writeLock.lock(); try { - if (suffix == null) { - suffix = ""; + this.setSuffixInternal(suffix); + } finally { + writeLock.unlock(); + } + } + + public void appendSuffix(String suffix) { + if (Strings.isNullOrEmpty(suffix)) { + return; + } + + writeLock.lock(); + try { + for (String token : this.suffix.split("\\s+")) { + if (suffix.equals(token)) { + return; + } } - if (suffix.length() > maxSuffixLength) { - suffix = suffix.substring(0, maxSuffixLength); + String featureFlagsSuffix = ""; + int featureFlagsIndex = this.userAgent.indexOf("|F"); + if (featureFlagsIndex >= 0) { + featureFlagsSuffix = this.userAgent.substring(featureFlagsIndex); } - 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.setSuffixInternal(appendedSuffix); + this.userAgent += featureFlagsSuffix; } finally { writeLock.unlock(); } @@ -98,6 +122,20 @@ public String getUserAgent() { } } + private void setSuffixInternal(String suffix) { + if (suffix == null) { + suffix = ""; + } + + if (suffix.length() > maxSuffixLength) { + suffix = suffix.substring(0, maxSuffixLength); + } + + this.suffix = suffix; + this.userAgent = stripNonAsciiCharacters(baseUserAgent.concat(" ").concat(this.suffix)); + this.baseUserAgentWithSuffix = this.userAgent; + } + private static String stripNonAsciiCharacters(String input) { // replace accents and diacriticals with their ASCII match (+ marker which we will remove in next step) String normalized = input == null ? null : Normalizer.normalize(input, Normalizer.Form.NFKD); From a68e4272c46e7bf180d34e537366fedf0361b0e6 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Mon, 28 Sep 2026 20:59:37 -0400 Subject: [PATCH 12/24] Remove user agent hot-path locking Publish complete user-agent snapshots through a volatile reference while retaining a writer lock for compound updates. Avoid scanning request headers by using the merged case-insensitive header value to detect SDK defaults. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit 44fe92a0c0a05bf99607fb2f48342404479cb242) --- .../UserAgentContainerTest.java | 46 +++++++++++++++++++ .../implementation/RxGatewayStoreModel.java | 14 ++---- .../implementation/UserAgentContainer.java | 40 ++++++---------- 3 files changed, 63 insertions(+), 37 deletions(-) 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 3191a3a42820c..bf722877272bb 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; @@ -189,6 +193,48 @@ public void appendSuffixAtomicallyPreservesFeatureFlags() { .endsWith("my-app azure-cosmos-encryption/2.28.0|F2"); } + @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))); + + 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("|F2")) { + 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/src/main/java/com/azure/cosmos/implementation/RxGatewayStoreModel.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxGatewayStoreModel.java index e72c2b8d31dc8..3502302c9bdcb 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 @@ -282,7 +282,9 @@ public void setCollectionCache(RxClientCollectionCache collectionCache) { public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI requestUri) throws Exception { HttpMethod method = getHttpMethod(request); HttpHeaders httpHeaders = this.getHttpRequestHeaders(request.getHeaders()); - if (!containsHeaderIgnoreCase(request.getHeaders(), HttpConstants.HttpHeaders.USER_AGENT)) { + if (Objects.equals( + httpHeaders.value(HttpConstants.HttpHeaders.USER_AGENT), + this.defaultHeaders.get(HttpConstants.HttpHeaders.USER_AGENT))) { httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, this.getCurrentUserAgent()); } @@ -294,16 +296,6 @@ public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI reque contentAsByteArray); } - private static boolean containsHeaderIgnoreCase(Map headers, String headerName) { - for (String name : headers.keySet()) { - if (headerName.equalsIgnoreCase(name)) { - return true; - } - } - - return false; - } - @Override public StoreResponse unwrapToStoreResponse( String endpoint, 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 809d8d8080f88..2cc4a373b4bd9 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 @@ -9,7 +9,6 @@ import java.util.Locale; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Pattern; /** @@ -21,11 +20,9 @@ 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; public final static String AZSDK_USERAGENT_PREFIX = "azsdk-java-"; @@ -45,12 +42,7 @@ public UserAgentContainer() { } public String getSuffix() { - readLock.lock(); - try { - return this.suffix; - } finally { - readLock.unlock(); - } + return this.suffix; } public void setFeatureEnabledFlagsAsSuffix(Set userAgentFeatureFlags) { @@ -68,8 +60,10 @@ public void setFeatureEnabledFlagsAsSuffix(Set userAgentF value += userAgentFeatureFlag.getValue(); } - this.userAgent = !Strings.isNullOrEmpty(this.baseUserAgentWithSuffix) ? this.baseUserAgentWithSuffix : this.baseUserAgent; - this.userAgent = this.userAgent + "|F" + Integer.toHexString(value).toUpperCase(Locale.ROOT); + String userAgentSnapshot = !Strings.isNullOrEmpty(this.baseUserAgentWithSuffix) + ? this.baseUserAgentWithSuffix + : this.baseUserAgent; + this.userAgent = userAgentSnapshot + "|F" + Integer.toHexString(value).toUpperCase(Locale.ROOT); } finally { writeLock.unlock(); } @@ -78,7 +72,7 @@ public void setFeatureEnabledFlagsAsSuffix(Set userAgentF public void setSuffix(String suffix) { writeLock.lock(); try { - this.setSuffixInternal(suffix); + this.userAgent = this.setSuffixInternal(suffix); } finally { writeLock.unlock(); } @@ -106,23 +100,17 @@ public void appendSuffix(String suffix) { String appendedSuffix = Strings.isNullOrEmpty(this.suffix) ? suffix : this.suffix + " " + suffix; - this.setSuffixInternal(appendedSuffix); - this.userAgent += featureFlagsSuffix; + this.userAgent = this.setSuffixInternal(appendedSuffix) + featureFlagsSuffix; } finally { writeLock.unlock(); } } public String getUserAgent() { - readLock.lock(); - try { - return this.userAgent; - } finally { - readLock.unlock(); - } + return this.userAgent; } - private void setSuffixInternal(String suffix) { + private String setSuffixInternal(String suffix) { if (suffix == null) { suffix = ""; } @@ -132,8 +120,8 @@ private void setSuffixInternal(String suffix) { } this.suffix = suffix; - this.userAgent = stripNonAsciiCharacters(baseUserAgent.concat(" ").concat(this.suffix)); - this.baseUserAgentWithSuffix = this.userAgent; + this.baseUserAgentWithSuffix = stripNonAsciiCharacters(baseUserAgent.concat(" ").concat(this.suffix)); + return this.baseUserAgentWithSuffix; } private static String stripNonAsciiCharacters(String input) { From 29456f6cd9954c59e2761d8da4b11618a8e922d8 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Wed, 30 Sep 2026 11:20:49 -0400 Subject: [PATCH 13/24] Simplify Gateway user agent refresh Apply the current SDK user agent before request overrides are merged. This removes value-equality inference while preserving explicit overrides through the existing case-insensitive HTTP header handling. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit c7fa98ed5f9c2f3015219241031489d6609382af) --- .../cosmos/implementation/RxGatewayStoreModelTest.java | 5 +++-- .../azure/cosmos/implementation/RxGatewayStoreModel.java | 7 ++----- 2 files changed, 5 insertions(+), 7 deletions(-) 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 339600401f739..f2a014a186cf0 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 @@ -96,6 +96,7 @@ public void requestUserAgentOverrideIsPreservedCaseInsensitively() throws Except ApiType.SQL, null); + String requestUserAgent = userAgentContainer.getUserAgent(); userAgentContainer.setFeatureEnabledFlagsAsSuffix( Collections.singleton(UserAgentFeatureFlags.PerPartitionCircuitBreaker)); @@ -104,13 +105,13 @@ public void requestUserAgentOverrideIsPreservedCaseInsensitively() throws Except OperationType.Read, ResourceType.DatabaseAccount, "", - Collections.singletonMap("user-agent", "request-user-agent"), + 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("request-user-agent"); + .isEqualTo(requestUserAgent); } @DataProvider(name = "sessionTokenConfigProvider") 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 3502302c9bdcb..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 @@ -282,11 +282,6 @@ public void setCollectionCache(RxClientCollectionCache collectionCache) { public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI requestUri) throws Exception { HttpMethod method = getHttpMethod(request); HttpHeaders httpHeaders = this.getHttpRequestHeaders(request.getHeaders()); - if (Objects.equals( - httpHeaders.value(HttpConstants.HttpHeaders.USER_AGENT), - this.defaultHeaders.get(HttpConstants.HttpHeaders.USER_AGENT))) { - httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, this.getCurrentUserAgent()); - } Flux contentAsByteArray = request.getContentAsByteArrayFlux(); return new HttpRequest(method, @@ -577,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()) { From 602b152f32d55531c3414e76a3c41f57909e8e17 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Wed, 30 Sep 2026 11:26:45 -0400 Subject: [PATCH 14/24] Test combined Cosmos user agent suffixes Verify Gateway and thin-client wire headers contain both the CosmosClientBuilder application suffix and feature flags added later by UserAgentContainer. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit b8b6c8f3692f79745c71f549955acda2dd02659d) --- .../azure/cosmos/implementation/RxGatewayStoreModelTest.java | 4 +++- .../azure/cosmos/implementation/ThinClientStoreModelTest.java | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) 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 f2a014a186cf0..eb78edba0dbbf 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 @@ -53,6 +53,7 @@ public class RxGatewayStoreModelTest { public void latestUserAgentIsAppliedToDatabaseAccountRequest() throws Exception { DiagnosticsClientContext clientContext = mockDiagnosticsClientContext(); UserAgentContainer userAgentContainer = new UserAgentContainer(); + userAgentContainer.setSuffix("test-application"); RxGatewayStoreModel storeModel = new RxGatewayStoreModel( clientContext, Mockito.mock(ISessionContainer.class), @@ -78,7 +79,8 @@ public void latestUserAgentIsAppliedToDatabaseAccountRequest() throws Exception HttpRequest httpRequest = storeModel.wrapInHttpRequest(request, new URI("https://localhost")); assertThat(httpRequest.headers().value(HttpConstants.HttpHeaders.USER_AGENT)) - .isEqualTo(userAgentContainer.getUserAgent()); + .isEqualTo(userAgentContainer.getUserAgent()) + .endsWith("test-application|F4"); } @Test(groups = "unit") 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 b9e32409bc530..08ad288dff5c3 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 @@ -220,6 +220,7 @@ public void thinClientUsesLatestUserAgentAndDoesNotAddNoRetry449Header() throws .thenReturn(Mono.error(new ConnectTimeoutException())); UserAgentContainer userAgentContainer = new UserAgentContainer(); + userAgentContainer.setSuffix("test-application"); ThinClientStoreModel storeModel = new ThinClientStoreModel( clientContext, sessionContainer, @@ -255,7 +256,8 @@ public void thinClientUsesLatestUserAgentAndDoesNotAddNoRetry449Header() throws 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()); + .isEqualTo(userAgentContainer.getUserAgent()) + .endsWith("test-application|F4"); 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(); From fd02f5eece43be42b66fb05d40ddd4d8c712a46b Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Wed, 30 Sep 2026 11:52:47 -0400 Subject: [PATCH 15/24] Limit Cosmos user agent refresh scope Allow the bootstrap DatabaseAccount request to precede feature evaluation and keep coverage focused on normal post-initialization Gateway requests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit 5d8cf1c946fa203923f253710cf372c19afee900) --- .../cosmos/implementation/RxGatewayStoreModelTest.java | 6 +++--- .../azure/cosmos/implementation/RxDocumentClientImpl.java | 2 -- 2 files changed, 3 insertions(+), 5 deletions(-) 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 eb78edba0dbbf..0c58fee9f9e6e 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 @@ -50,7 +50,7 @@ public class RxGatewayStoreModelTest { private final static int TIMEOUT = 10000; @Test(groups = "unit") - public void latestUserAgentIsAppliedToDatabaseAccountRequest() throws Exception { + public void latestUserAgentIsAppliedToGatewayRequest() throws Exception { DiagnosticsClientContext clientContext = mockDiagnosticsClientContext(); UserAgentContainer userAgentContainer = new UserAgentContainer(); userAgentContainer.setSuffix("test-application"); @@ -71,8 +71,8 @@ public void latestUserAgentIsAppliedToDatabaseAccountRequest() throws Exception RxDocumentServiceRequest request = RxDocumentServiceRequest.create( clientContext, OperationType.Read, - ResourceType.DatabaseAccount, - "", + ResourceType.Document, + "/dbs/db/colls/col/docs/doc", null, (Object) null); 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 89595fd8ea41b..967eb3dd00785 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 @@ -944,8 +944,6 @@ public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Func }); this.globalEndpointManager.setPerPartitionAutomaticFailoverConfigModifier(this.perPartitionFailoverConfigModifier); - // Include configuration-known flags on the bootstrap account request; account-derived flags are reevaluated later. - this.addUserAgentSuffix(this.userAgentContainer, EnumSet.allOf(UserAgentFeatureFlags.class)); this.globalEndpointManager.init(); this.initializePerPartitionCircuitBreaker(); From f3564d7d8d2fb30659493396a46444c547478b9e Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Wed, 30 Sep 2026 12:28:23 -0400 Subject: [PATCH 16/24] Minimize Cosmos feature suffix publication Keep the original feature-suffix expression while publishing the complete volatile user-agent value in one assignment. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit c655610a6fd262fb4bc9638563dcaa3b20ed4bed) --- .../com/azure/cosmos/implementation/UserAgentContainer.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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 2cc4a373b4bd9..79ec4d536d977 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 @@ -60,10 +60,9 @@ public void setFeatureEnabledFlagsAsSuffix(Set userAgentF value += userAgentFeatureFlag.getValue(); } - String userAgentSnapshot = !Strings.isNullOrEmpty(this.baseUserAgentWithSuffix) + this.userAgent = (!Strings.isNullOrEmpty(this.baseUserAgentWithSuffix) ? this.baseUserAgentWithSuffix - : this.baseUserAgent; - this.userAgent = userAgentSnapshot + "|F" + Integer.toHexString(value).toUpperCase(Locale.ROOT); + : this.baseUserAgent) + "|F" + Integer.toHexString(value).toUpperCase(Locale.ROOT); } finally { writeLock.unlock(); } From a3a6d0108d7ccd10fa52ad3914e28352d3fe7e8c Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Thu, 19 Nov 2026 07:50:25 -0500 Subject: [PATCH 17/24] Test encryption opt-out marker in Gateway user agents Verify late user-agent suffix updates reach Gateway and GatewayV2 HTTP headers alongside feature flags. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure/cosmos/implementation/RxGatewayStoreModelTest.java | 3 ++- .../azure/cosmos/implementation/ThinClientStoreModelTest.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) 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 0c58fee9f9e6e..2f83d2f829968 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 @@ -67,6 +67,7 @@ public void latestUserAgentIsAppliedToGatewayRequest() throws Exception { userAgentContainer.setFeatureEnabledFlagsAsSuffix( Collections.singleton(UserAgentFeatureFlags.ThinClient)); + userAgentContainer.appendSuffix("encryption-mixed-arrays-disabled"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( clientContext, @@ -80,7 +81,7 @@ public void latestUserAgentIsAppliedToGatewayRequest() throws Exception { assertThat(httpRequest.headers().value(HttpConstants.HttpHeaders.USER_AGENT)) .isEqualTo(userAgentContainer.getUserAgent()) - .endsWith("test-application|F4"); + .endsWith("test-application encryption-mixed-arrays-disabled|F4"); } @Test(groups = "unit") 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 08ad288dff5c3..8b25b59e0b6cb 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 @@ -232,6 +232,7 @@ public void thinClientUsesLatestUserAgentAndDoesNotAddNoRetry449Header() throws userAgentContainer.setFeatureEnabledFlagsAsSuffix( Collections.singleton(UserAgentFeatureFlags.ThinClient)); + userAgentContainer.appendSuffix("encryption-mixed-arrays-disabled"); RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName( clientContext, @@ -257,7 +258,7 @@ public void thinClientUsesLatestUserAgentAndDoesNotAddNoRetry449Header() throws 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|F4"); + .endsWith("test-application encryption-mixed-arrays-disabled|F4"); 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(); From 9379934807fe1c23575ec990678834ae9f6808b7 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Thu, 19 Nov 2026 08:12:51 -0500 Subject: [PATCH 18/24] Encode encryption opt-out as a user-agent feature bit Replace the textual mixed-array opt-out marker with flag 0x80. Preserve explicit configuration flags across feature refreshes and suffix updates, with Gateway and encryption regression coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sdk/cosmos/azure-cosmos-encryption/README.md | 7 +-- .../CosmosEncryptionAsyncClient.java | 3 +- .../encryption/implementation/Constants.java | 1 - .../CosmosEncryptionAsyncClientUnitTest.java | 16 ++++--- .../RxGatewayStoreModelTest.java | 4 +- .../ThinClientStoreModelTest.java | 4 +- .../UserAgentContainerTest.java | 26 +++++++++- .../implementation/AsyncDocumentClient.java | 7 +++ .../implementation/RxDocumentClientImpl.java | 8 ++++ .../implementation/UserAgentContainer.java | 48 ++++++++++++++----- .../implementation/UserAgentFeatureFlags.java | 5 +- 11 files changed, 97 insertions(+), 32 deletions(-) diff --git a/sdk/cosmos/azure-cosmos-encryption/README.md b/sdk/cosmos/azure-cosmos-encryption/README.md index e74fa95e3a370..26ed8e502c12f 100644 --- a/sdk/cosmos/azure-cosmos-encryption/README.md +++ b/sdk/cosmos/azure-cosmos-encryption/README.md @@ -174,9 +174,10 @@ The fix is enabled by default. To temporarily restore legacy array traversal for 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. Explicit opt-out adds `encryption-mixed-arrays-disabled` to the underlying -Cosmos client's user-agent suffix, alongside the encryption SDK version. Default and explicit `true` settings -do not add this marker. The suffix is client-wide, including requests sharing that underlying Cosmos client. +to change modes consistently. Explicit opt-out sets bit `0x80` (`EncryptionMixedArrayOptOut`) in the underlying +Cosmos client's compact user-agent feature mask (`|F80` alone, or `|F84` together with ThinClient). +Default and explicit `true` settings do not set this bit. The mask is client-wide, including requests sharing +that underlying Cosmos client; the encryption SDK version suffix remains unchanged. 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 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 88eab2afb0984..63b97e6d0756b 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 @@ -22,6 +22,7 @@ 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; @@ -206,7 +207,7 @@ private void appendEncryptionUserAgentSuffix() { AsyncDocumentClient documentClient = CosmosBridgeInternal.getAsyncDocumentClient(this.cosmosAsyncClient); documentClient.appendUserAgentSuffix(Constants.USER_AGENT_SUFFIX); if (!this.mixedArrayEncryptionEnabled) { - documentClient.appendUserAgentSuffix(Constants.MIXED_ARRAYS_DISABLED_USER_AGENT_SUFFIX); + documentClient.addUserAgentFeatureFlag(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); } } catch (Exception e) { LOGGER.warn("Failed to append encryption SDK user agent suffix", e); diff --git a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/Constants.java b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/Constants.java index 2006f4b7eb644..65c3275693b7d 100644 --- a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/Constants.java +++ b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/Constants.java @@ -15,7 +15,6 @@ public class Constants { public static final String CURRENT_NAME = PROPERTIES.getOrDefault("name", "azure-cosmos-encryption"); public static final String CURRENT_VERSION = PROPERTIES.getOrDefault("version", "unknown"); public static final String USER_AGENT_SUFFIX = CURRENT_NAME + "/" + CURRENT_VERSION; - public static final String MIXED_ARRAYS_DISABLED_USER_AGENT_SUFFIX = "encryption-mixed-arrays-disabled"; public static final String INTENDED_COLLECTION_RID_HEADER = "x-ms-cosmos-intended-collection-rid"; 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 71af4ad745708..21be6c7823cac 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 @@ -17,6 +17,7 @@ import com.azure.cosmos.implementation.RequestOptions; import com.azure.cosmos.implementation.RxDocumentClientImpl; import com.azure.cosmos.implementation.UserAgentContainer; +import com.azure.cosmos.implementation.UserAgentFeatureFlags; import com.azure.cosmos.models.CosmosClientEncryptionKeyProperties; import com.azure.cosmos.models.CosmosClientEncryptionKeyResponse; import com.fasterxml.jackson.databind.JsonNode; @@ -27,6 +28,8 @@ import org.testng.annotations.Test; import reactor.core.publisher.Mono; +import java.util.EnumSet; + import static org.assertj.core.api.Assertions.assertThat; public class CosmosEncryptionAsyncClientUnitTest { @@ -81,8 +84,11 @@ public void encryptionClientAppendsUserAgentSuffix(String setting, boolean optOu KeyEncryptionKeyResolver mockKeyResolver = Mockito.mock(KeyEncryptionKeyResolver.class); UserAgentContainer userAgent = new UserAgentContainer(); userAgent.setSuffix("customer-app"); + userAgent.setFeatureEnabledFlagsAsSuffix(EnumSet.of(UserAgentFeatureFlags.ThinClient)); FieldUtils.writeField(mockDocClient, "userAgentContainer", userAgent, true); Mockito.doCallRealMethod().when(mockDocClient).appendUserAgentSuffix(Mockito.anyString()); + Mockito.doCallRealMethod().when(mockDocClient) + .addUserAgentFeatureFlag(Mockito.any(UserAgentFeatureFlags.class)); String previousValue = System.getProperty(MIXED_ARRAYS_ENABLED_PROPERTY); org.mockito.MockedStatic bridgeMock = Mockito.mockStatic(CosmosBridgeInternal.class); @@ -101,12 +107,8 @@ public void encryptionClientAppendsUserAgentSuffix(String setting, boolean optOu assertThat(userAgent.getUserAgent()) .contains("customer-app", Constants.USER_AGENT_SUFFIX); assertThat(userAgent.getSuffix().split("\\s+")) - .containsOnlyOnce("customer-app", Constants.USER_AGENT_SUFFIX); - if (optOutExpected) { - assertThat(userAgent.getSuffix().split("\\s+")).containsOnlyOnce("encryption-mixed-arrays-disabled"); - } else { - assertThat(userAgent.getUserAgent()).doesNotContain("encryption-mixed-arrays-disabled"); - } + .containsExactly("customer-app", Constants.USER_AGENT_SUFFIX); + assertThat(userAgent.getUserAgent()).endsWith(optOutExpected ? "|F84" : "|F4"); } finally { bridgeMock.close(); restoreMixedArraySetting(previousValue); @@ -134,7 +136,7 @@ public void encryptionOptOutSnapshotMatchesUserAgent() throws Exception { assertThat(client.isMixedArrayEncryptionEnabled()).isFalse(); assertThat(encryptedArray.get(1).asInt()).isEqualTo(42); - Mockito.verify(mockDocClient).appendUserAgentSuffix(Constants.MIXED_ARRAYS_DISABLED_USER_AGENT_SUFFIX); + Mockito.verify(mockDocClient).addUserAgentFeatureFlag(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); } finally { restoreMixedArraySetting(previousValue); } 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 2f83d2f829968..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 @@ -67,7 +67,7 @@ public void latestUserAgentIsAppliedToGatewayRequest() throws Exception { userAgentContainer.setFeatureEnabledFlagsAsSuffix( Collections.singleton(UserAgentFeatureFlags.ThinClient)); - userAgentContainer.appendSuffix("encryption-mixed-arrays-disabled"); + userAgentContainer.addFeatureEnabledFlag(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( clientContext, @@ -81,7 +81,7 @@ public void latestUserAgentIsAppliedToGatewayRequest() throws Exception { assertThat(httpRequest.headers().value(HttpConstants.HttpHeaders.USER_AGENT)) .isEqualTo(userAgentContainer.getUserAgent()) - .endsWith("test-application encryption-mixed-arrays-disabled|F4"); + .endsWith("test-application|F84"); } @Test(groups = "unit") 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 8b25b59e0b6cb..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 @@ -232,7 +232,7 @@ public void thinClientUsesLatestUserAgentAndDoesNotAddNoRetry449Header() throws userAgentContainer.setFeatureEnabledFlagsAsSuffix( Collections.singleton(UserAgentFeatureFlags.ThinClient)); - userAgentContainer.appendSuffix("encryption-mixed-arrays-disabled"); + userAgentContainer.addFeatureEnabledFlag(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName( clientContext, @@ -258,7 +258,7 @@ public void thinClientUsesLatestUserAgentAndDoesNotAddNoRetry449Header() throws 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 encryption-mixed-arrays-disabled|F4"); + .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 bf722877272bb..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 @@ -33,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, ""} }; @@ -193,12 +195,34 @@ public void appendSuffixAtomicallyPreservesFeatureFlags() { .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); @@ -218,7 +242,7 @@ public void concurrentReadersObserveCompleteUserAgentSnapshots() throws Exceptio start.await(); for (int i = 0; i < 10_000; i++) { String userAgent = userAgentContainer.getUserAgent(); - if (!userAgent.endsWith("|F2")) { + if (!userAgent.endsWith("|F82")) { throw new AssertionError("Observed incomplete user-agent snapshot: " + userAgent); } } 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/RxDocumentClientImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java index 967eb3dd00785..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 @@ -1220,6 +1220,11 @@ public void appendUserAgentSuffix(String suffix) { this.userAgentContainer.appendSuffix(trimmedSuffix); } + @Override + public void addUserAgentFeatureFlag(UserAgentFeatureFlags userAgentFeatureFlag) { + this.userAgentContainer.addFeatureEnabledFlag(userAgentFeatureFlag); + } + @Override public CosmosDiagnostics getMostRecentlyCreatedDiagnostics() { return mostRecentlyCreatedDiagnostics.get(); @@ -1670,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/UserAgentContainer.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserAgentContainer.java index 79ec4d536d977..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,6 +7,7 @@ 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.regex.Pattern; @@ -24,6 +25,8 @@ public class UserAgentContainer { 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( @@ -54,15 +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) + "|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(); } @@ -71,7 +88,8 @@ public void setFeatureEnabledFlagsAsSuffix(Set userAgentF public void setSuffix(String suffix) { writeLock.lock(); try { - this.userAgent = this.setSuffixInternal(suffix); + this.featureFlags = 0; + this.userAgent = this.setSuffixInternal(suffix) + getFeatureFlagsSuffix(); } finally { writeLock.unlock(); } @@ -90,16 +108,10 @@ public void appendSuffix(String suffix) { } } - String featureFlagsSuffix = ""; - int featureFlagsIndex = this.userAgent.indexOf("|F"); - if (featureFlagsIndex >= 0) { - featureFlagsSuffix = this.userAgent.substring(featureFlagsIndex); - } - String appendedSuffix = Strings.isNullOrEmpty(this.suffix) ? suffix : this.suffix + " " + suffix; - this.userAgent = this.setSuffixInternal(appendedSuffix) + featureFlagsSuffix; + this.userAgent = this.setSuffixInternal(appendedSuffix) + getFeatureFlagsSuffix(); } finally { writeLock.unlock(); } @@ -109,6 +121,16 @@ public String getUserAgent() { 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 = ""; 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; From 6e2e75a0e44eda78fab2b7aa75afdca2b0e93a8d Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Thu, 19 Nov 2026 08:51:59 -0500 Subject: [PATCH 19/24] Route encryption user-agent updates through wrapped client Use CosmosAsyncClient internal accessors instead of CosmosBridgeInternal, update forwarding tests, and remove user-agent details from the encryption README. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sdk/cosmos/azure-cosmos-encryption/README.md | 5 +-- sdk/cosmos/azure-cosmos-encryption/pom.xml | 1 + .../CosmosEncryptionAsyncClient.java | 8 ++--- .../CosmosEncryptionAsyncClientUnitTest.java | 36 +++++++------------ .../com/azure/cosmos/CosmosAsyncClient.java | 11 ++++++ .../ImplementationBridgeHelpers.java | 2 ++ 6 files changed, 30 insertions(+), 33 deletions(-) diff --git a/sdk/cosmos/azure-cosmos-encryption/README.md b/sdk/cosmos/azure-cosmos-encryption/README.md index 26ed8e502c12f..cf267ba84a866 100644 --- a/sdk/cosmos/azure-cosmos-encryption/README.md +++ b/sdk/cosmos/azure-cosmos-encryption/README.md @@ -174,10 +174,7 @@ The fix is enabled by default. To temporarily restore legacy array traversal for 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. Explicit opt-out sets bit `0x80` (`EncryptionMixedArrayOptOut`) in the underlying -Cosmos client's compact user-agent feature mask (`|F80` alone, or `|F84` together with ThinClient). -Default and explicit `true` settings do not set this bit. The mask is client-wide, including requests sharing -that underlying Cosmos client; the encryption SDK version suffix remains unchanged. +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 diff --git a/sdk/cosmos/azure-cosmos-encryption/pom.xml b/sdk/cosmos/azure-cosmos-encryption/pom.xml index 09fa7dec9777e..cb630c9b0d5ba 100644 --- a/sdk/cosmos/azure-cosmos-encryption/pom.xml +++ b/sdk/cosmos/azure-cosmos-encryption/pom.xml @@ -48,6 +48,7 @@ Licensed under the MIT License. --add-opens com.azure.cosmos.encryption/com.azure.cosmos.encryption.keyprovider=ALL-UNNAMED --add-opens com.azure.cosmos.encryption/com.azure.cosmos.encryption.util=ALL-UNNAMED --add-opens com.azure.cosmos.encryption/com.azure.cosmos.encryption.models=ALL-UNNAMED + --add-opens com.azure.cosmos/com.azure.cosmos=ALL-UNNAMED --add-opens com.azure.cosmos/com.azure.cosmos.implementation=ALL-UNNAMED --add-modules java.management --add-reads com.azure.cosmos.encryption=java.management 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 63b97e6d0756b..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,14 +10,12 @@ 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.AsyncDocumentClient; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.RequestOptions; @@ -204,10 +202,10 @@ public CosmosAsyncClient getCosmosAsyncClient() { private void appendEncryptionUserAgentSuffix() { try { - AsyncDocumentClient documentClient = CosmosBridgeInternal.getAsyncDocumentClient(this.cosmosAsyncClient); - documentClient.appendUserAgentSuffix(Constants.USER_AGENT_SUFFIX); + cosmosAsyncClientAccessor.appendUserAgentSuffix(this.cosmosAsyncClient, Constants.USER_AGENT_SUFFIX); if (!this.mixedArrayEncryptionEnabled) { - documentClient.addUserAgentFeatureFlag(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); + cosmosAsyncClientAccessor.addUserAgentFeatureFlag(this.cosmosAsyncClient, + UserAgentFeatureFlags.EncryptionMixedArrayOptOut); } } catch (Exception e) { LOGGER.warn("Failed to append encryption SDK user agent suffix", e); 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 21be6c7823cac..783e127401202 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,7 +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.encryption.implementation.EncryptionProcessor; import com.azure.cosmos.encryption.implementation.EncryptionSettings; @@ -86,21 +85,18 @@ public void encryptionClientAppendsUserAgentSuffix(String setting, boolean optOu userAgent.setSuffix("customer-app"); userAgent.setFeatureEnabledFlagsAsSuffix(EnumSet.of(UserAgentFeatureFlags.ThinClient)); FieldUtils.writeField(mockDocClient, "userAgentContainer", userAgent, true); + FieldUtils.writeField(mockAsyncClient, "asyncDocumentClient", mockDocClient, true); Mockito.doCallRealMethod().when(mockDocClient).appendUserAgentSuffix(Mockito.anyString()); Mockito.doCallRealMethod().when(mockDocClient) .addUserAgentFeatureFlag(Mockito.any(UserAgentFeatureFlags.class)); String previousValue = System.getProperty(MIXED_ARRAYS_ENABLED_PROPERTY); - org.mockito.MockedStatic bridgeMock = Mockito.mockStatic(CosmosBridgeInternal.class); try { if (setting == null) { System.clearProperty(MIXED_ARRAYS_ENABLED_PROPERTY); } else { System.setProperty(MIXED_ARRAYS_ENABLED_PROPERTY, setting); } - bridgeMock.when(() -> CosmosBridgeInternal.getAsyncDocumentClient(mockAsyncClient)) - .thenReturn(mockDocClient); - new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); @@ -110,7 +106,6 @@ public void encryptionClientAppendsUserAgentSuffix(String setting, boolean optOu .containsExactly("customer-app", Constants.USER_AGENT_SUFFIX); assertThat(userAgent.getUserAgent()).endsWith(optOutExpected ? "|F84" : "|F4"); } finally { - bridgeMock.close(); restoreMixedArraySetting(previousValue); } } @@ -119,11 +114,10 @@ public void encryptionClientAppendsUserAgentSuffix(String setting, boolean optOu public void encryptionOptOutSnapshotMatchesUserAgent() throws Exception { CosmosAsyncClient mockAsyncClient = Mockito.mock(CosmosAsyncClient.class); AsyncDocumentClient mockDocClient = Mockito.mock(AsyncDocumentClient.class); + FieldUtils.writeField(mockAsyncClient, "asyncDocumentClient", mockDocClient, true); KeyEncryptionKeyResolver mockKeyResolver = Mockito.mock(KeyEncryptionKeyResolver.class); String previousValue = System.getProperty(MIXED_ARRAYS_ENABLED_PROPERTY); - try (org.mockito.MockedStatic bridgeMock = Mockito.mockStatic(CosmosBridgeInternal.class)) { - bridgeMock.when(() -> CosmosBridgeInternal.getAsyncDocumentClient(mockAsyncClient)) - .thenReturn(mockDocClient); + try { System.setProperty(MIXED_ARRAYS_ENABLED_PROPERTY, "false"); CosmosEncryptionAsyncClient client = new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); @@ -160,23 +154,17 @@ public void encryptionUserAgentSuffixContainsVersionInfo() { } @Test(groups = {"unit"}, timeOut = TestSuiteBase.TIMEOUT) - public void encryptionClientHandlesAppendFailureGracefully() { - // If getAsyncDocumentClient throws, encryption client should still be created + public void encryptionClientHandlesAppendFailureGracefully() throws Exception { CosmosAsyncClient mockAsyncClient = Mockito.mock(CosmosAsyncClient.class); + AsyncDocumentClient mockDocClient = Mockito.mock(AsyncDocumentClient.class); KeyEncryptionKeyResolver mockKeyResolver = Mockito.mock(KeyEncryptionKeyResolver.class); + FieldUtils.writeField(mockAsyncClient, "asyncDocumentClient", mockDocClient, true); + Mockito.doThrow(new RuntimeException("simulated failure")) + .when(mockDocClient).appendUserAgentSuffix(Constants.USER_AGENT_SUFFIX); - 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(); - } + CosmosEncryptionAsyncClient client = + new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); + assertThat(client).isNotNull(); + assertThat(client.getCosmosAsyncClient()).isSameAs(mockAsyncClient); } } 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/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, From f35f2a5d24720294a607260817e969a438641d74 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Tue, 24 Nov 2026 10:16:51 -0500 Subject: [PATCH 20/24] Separate legacy and corrected encryption array traversal Route array encryption and decryption through explicit mode-selection helpers, keeping traversal config-free and sharing the existing decryption error guidance. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../implementation/EncryptionProcessor.java | 183 ++++++++++++------ 1 file changed, 129 insertions(+), 54 deletions(-) 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 d88c7545c0e58..9a713f5c46f1d 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 @@ -368,17 +368,7 @@ public JsonNode encryptAndSerializePatchProperty(EncryptionSettings encryptionSe else if (propertyValueHolder.isArray()) { assert propertyValueHolder instanceof ArrayNode; ArrayNode arrayNode = (ArrayNode) propertyValueHolder; - boolean traverseContainers = shouldTraverseArrayContainers(arrayNode); - boolean processScalars = this.mixedArrayEncryptionEnabled || !traverseContainers; - for (int i = 0; i < arrayNode.size(); i++) { - JsonNode nodeInArray = arrayNode.get(i); - if (traverseContainers && (nodeInArray.isObject() || nodeInArray.isArray())) { - arrayNode.set(i, encryptAndSerializePatchProperty(encryptionSettings, nodeInArray, propertyName)); - } else if (processScalars && (!this.mixedArrayEncryptionEnabled || !nodeInArray.isNull())) { - arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, - nodeInArray, StringUtils.EMPTY))); - } - } + encryptPatchArray(encryptionSettings, arrayNode, propertyName); return arrayNode; } else if (!propertyValueHolder.isNull()) { return BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, propertyValueHolder, @@ -402,28 +392,86 @@ public void encryptAndSerializeProperty(EncryptionSettings encryptionSettings, J } } } else if (propertyValueHolder.isArray()) { - ArrayNode arrayNode = (ArrayNode) propertyValueHolder; - boolean traverseContainers = shouldTraverseArrayContainers(arrayNode); - boolean processScalars = this.mixedArrayEncryptionEnabled || !traverseContainers; - for (int i = 0; i < arrayNode.size(); i++) { - JsonNode nodeInArray = arrayNode.get(i); - if (traverseContainers && (nodeInArray.isObject() || nodeInArray.isArray())) { - encryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, - StringUtils.EMPTY); - } else if (processScalars && (!this.mixedArrayEncryptionEnabled || !nodeInArray.isNull())) { - arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, - nodeInArray, StringUtils.EMPTY))); - } - } + encryptArray(encryptionSettings, (ArrayNode) propertyValueHolder); } else { encryptAndSerializeValue(encryptionSettings, (ObjectNode) objectNode, propertyValueHolder, propertyName); } } - private boolean shouldTraverseArrayContainers(ArrayNode arrayNode) { - // Legacy traversal chooses one strategy for the entire array from its first element. - return this.mixedArrayEncryptionEnabled || (arrayNode.size() > 0 - && (arrayNode.get(0).isObject() || arrayNode.get(0).isArray())); + private static boolean isLegacyContainerArray(ArrayNode arrayNode) { + return arrayNode.size() > 0 && (arrayNode.get(0).isObject() || arrayNode.get(0).isArray()); + } + + 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 { + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode nodeInArray = arrayNode.get(i); + if (nodeInArray.isObject() || nodeInArray.isArray()) { + arrayNode.set(i, encryptAndSerializePatchProperty(encryptionSettings, nodeInArray, propertyName)); + } else if (!nodeInArray.isNull()) { + arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, + nodeInArray, StringUtils.EMPTY))); + } + } + } + + private void encryptLegacyPatchArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, + String propertyName) throws MicrosoftDataEncryptionException, JsonProcessingException { + boolean containerArray = isLegacyContainerArray(arrayNode); + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode nodeInArray = arrayNode.get(i); + if (!containerArray) { + arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, + nodeInArray, StringUtils.EMPTY))); + } else if (nodeInArray.isObject() || nodeInArray.isArray()) { + arrayNode.set(i, encryptAndSerializePatchProperty(encryptionSettings, nodeInArray, propertyName)); + } + } + } + + private void encryptLegacyArray(EncryptionSettings encryptionSettings, + ArrayNode arrayNode) throws MicrosoftDataEncryptionException, JsonProcessingException { + boolean containerArray = isLegacyContainerArray(arrayNode); + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode nodeInArray = arrayNode.get(i); + if (!containerArray) { + arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, + nodeInArray, StringUtils.EMPTY))); + } else if (nodeInArray.isObject() || nodeInArray.isArray()) { + encryptAndSerializeProperty(encryptionSettings, null, nodeInArray, StringUtils.EMPTY); + } + } + } + + private void encryptArray(EncryptionSettings encryptionSettings, + ArrayNode arrayNode) throws MicrosoftDataEncryptionException, JsonProcessingException { + if (this.mixedArrayEncryptionEnabled) { + encryptMixedArray(encryptionSettings, arrayNode); + } else { + encryptLegacyArray(encryptionSettings, arrayNode); + } + } + + private void encryptMixedArray(EncryptionSettings encryptionSettings, + ArrayNode arrayNode) throws MicrosoftDataEncryptionException, JsonProcessingException { + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode nodeInArray = arrayNode.get(i); + if (nodeInArray.isObject() || nodeInArray.isArray()) { + encryptAndSerializeProperty(encryptionSettings, null, nodeInArray, StringUtils.EMPTY); + } else if (!nodeInArray.isNull()) { + arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, + nodeInArray, StringUtils.EMPTY))); + } + } } public String encryptAndSerializeValue(EncryptionSettings encryptionSettings, String propertyValue, String propertyName) throws MicrosoftDataEncryptionException { @@ -541,37 +589,64 @@ public void decryptAndSerializeProperty(EncryptionSettings encryptionSettings, J } } } else if (propertyValueHolder.isArray()) { - ArrayNode arrayNode = (ArrayNode) propertyValueHolder; - boolean traverseContainers = shouldTraverseArrayContainers(arrayNode); - boolean processScalars = this.mixedArrayEncryptionEnabled || !traverseContainers; - for (int i = 0; i < arrayNode.size(); i++) { - JsonNode nodeInArray = arrayNode.get(i); - if (traverseContainers && (nodeInArray.isObject() || nodeInArray.isArray())) { - decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, - propertyName); - } else if (processScalars && (!this.mixedArrayEncryptionEnabled || !nodeInArray.isNull())) { - try { - arrayNode.set(i, decryptAndSerializeValue(encryptionSettings, null, nodeInArray, - StringUtils.EMPTY)); - } catch (MicrosoftDataEncryptionException | IOException | IllegalArgumentException ex) { - throw new IllegalStateException("Unable to decrypt array element at index " + i - + " in encrypted property '/" + propertyName + "'. Mixed-type arrays written by previous " - + "SDK versions may contain unencrypted scalar values. If this is legacy data, read the " - + "item using the SDK version that wrote it and rewrite the decrypted item using the " - + "current SDK. Alternatively, temporarily restore legacy reads AND writes by setting " - + "-D" + EncryptionConfigs.MIXED_ARRAYS_ENABLED + "=false or " - + EncryptionConfigs.MIXED_ARRAYS_ENABLED_VARIABLE + "=false before creating clients. " - + "Legacy mode can leave scalar array elements unencrypted and cannot correctly read " - + "mixed arrays written with the fix enabled. Otherwise, check the encryption key and " - + "ciphertext integrity.", ex); - } - } - } + 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 { + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode nodeInArray = arrayNode.get(i); + if (nodeInArray.isObject() || nodeInArray.isArray()) { + decryptAndSerializeProperty(encryptionSettings, null, nodeInArray, propertyName); + } else if (!nodeInArray.isNull()) { + arrayNode.set(i, decryptArrayValue(encryptionSettings, nodeInArray, propertyName, i)); + } + } + } + + private void decryptLegacyArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, + String propertyName) throws MicrosoftDataEncryptionException, IOException { + boolean containerArray = isLegacyContainerArray(arrayNode); + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode nodeInArray = arrayNode.get(i); + if (!containerArray) { + arrayNode.set(i, decryptArrayValue(encryptionSettings, nodeInArray, propertyName, i)); + } else if (nodeInArray.isObject() || nodeInArray.isArray()) { + decryptAndSerializeProperty(encryptionSettings, null, nodeInArray, propertyName); + } + } + } + + 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 + "'. Mixed-type arrays written by previous " + + "SDK versions may contain unencrypted scalar values. If this is legacy data, read the " + + "item using the SDK version that wrote it and rewrite the decrypted item using the " + + "current SDK. Alternatively, temporarily restore legacy reads AND writes by setting " + + "-D" + EncryptionConfigs.MIXED_ARRAYS_ENABLED + "=false or " + + EncryptionConfigs.MIXED_ARRAYS_ENABLED_VARIABLE + "=false before creating clients. " + + "Legacy mode can leave scalar array elements unencrypted and cannot correctly read " + + "mixed arrays written with the fix enabled. Otherwise, check the encryption key and " + + "ciphertext integrity.", ex); + } + } + public JsonNode decryptAndSerializeValue(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException, IOException { byte[] cipherText; From 6664f5f1e68e58e7aff947d3135c97a4adbdae11 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Tue, 24 Nov 2026 10:20:42 -0500 Subject: [PATCH 21/24] Shorten mixed-array decryption error guidance Keep the property/index, migration and opt-out settings, under-encryption warning, and original cause while removing redundant wording. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../implementation/EncryptionProcessor.java | 11 ++++------- .../EncryptionProcessorAndSettingsTest.java | 7 ++++--- 2 files changed, 8 insertions(+), 10 deletions(-) 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 9a713f5c46f1d..0197ec9937b12 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 @@ -635,15 +635,12 @@ private JsonNode decryptArrayValue(EncryptionSettings encryptionSettings, JsonNo 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 + "'. Mixed-type arrays written by previous " - + "SDK versions may contain unencrypted scalar values. If this is legacy data, read the " - + "item using the SDK version that wrote it and rewrite the decrypted item using the " - + "current SDK. Alternatively, temporarily restore legacy reads AND writes by setting " + + " 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. " - + "Legacy mode can leave scalar array elements unencrypted and cannot correctly read " - + "mixed arrays written with the fix enabled. Otherwise, check the encryption key and " - + "ciphertext integrity.", ex); + + "Opt-out restores legacy reads/writes and may leave scalars unencrypted. " + + "Check the cause for key or ciphertext errors.", ex); } } 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 4445229968ac3..ffa21459a90d1 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 @@ -345,8 +345,9 @@ public void decryptLegacyMixedArrayReportsMigration(String arrayJson, .hasCauseInstanceOf(expectedCause) .hasMessageContaining("index 1") .hasMessageContaining("encrypted property '/sensitiveString'") - .hasMessageContaining("SDK version that wrote it") - .hasMessageContaining("rewrite the decrypted item") + .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") @@ -380,7 +381,7 @@ public void decryptArrayPreservesAuthenticationFailure(boolean mixedArraysEnable "sensitiveString")) .isInstanceOf(IllegalStateException.class) .hasCause(authenticationFailure) - .hasMessageContaining("check the encryption key and ciphertext integrity"); + .hasMessageContaining("Check the cause for key or ciphertext errors"); } @DataProvider(name = "legacyArrayWrites") From 33414984733393ff576240e46c1f6960c9f99b66 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Tue, 24 Nov 2026 11:00:58 -0500 Subject: [PATCH 22/24] Keep encryption array traversal close to main Restore main-style legacy iteration and rebuilding, make corrected recursion explicit, and add empty-array and live opt-in/out coverage across GatewayV1, GatewayV2 and Direct. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../implementation/EncryptionProcessor.java | 186 ++++++++++---- .../EncryptionMixedArrayE2ETest.java | 232 ++++++++++++++++++ .../EncryptionProcessorAndSettingsTest.java | 16 ++ 3 files changed, 387 insertions(+), 47 deletions(-) create mode 100644 sdk/cosmos/azure-cosmos-encryption/src/test/java/com/azure/cosmos/encryption/EncryptionMixedArrayE2ETest.java 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 0197ec9937b12..1ddee4de055dd 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 @@ -392,16 +392,12 @@ public void encryptAndSerializeProperty(EncryptionSettings encryptionSettings, J } } } else if (propertyValueHolder.isArray()) { - encryptArray(encryptionSettings, (ArrayNode) propertyValueHolder); + encryptArray(encryptionSettings, (ArrayNode) propertyValueHolder, propertyName); } else { encryptAndSerializeValue(encryptionSettings, (ObjectNode) objectNode, propertyValueHolder, propertyName); } } - private static boolean isLegacyContainerArray(ArrayNode arrayNode) { - return arrayNode.size() > 0 && (arrayNode.get(0).isObject() || arrayNode.get(0).isArray()); - } - private void encryptPatchArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, String propertyName) throws MicrosoftDataEncryptionException, JsonProcessingException { if (this.mixedArrayEncryptionEnabled) { @@ -413,65 +409,126 @@ private void encryptPatchArray(EncryptionSettings encryptionSettings, ArrayNode private void encryptMixedPatchArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, String propertyName) throws MicrosoftDataEncryptionException, JsonProcessingException { - for (int i = 0; i < arrayNode.size(); i++) { - JsonNode nodeInArray = arrayNode.get(i); + ArrayNode encryptedArray = arrayNode.arrayNode(); + for (Iterator arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { + JsonNode nodeInArray = arrayIterator.next(); if (nodeInArray.isObject() || nodeInArray.isArray()) { - arrayNode.set(i, encryptAndSerializePatchProperty(encryptionSettings, nodeInArray, propertyName)); + encryptedArray.add(encryptAndSerializePatchProperty(encryptionSettings, nodeInArray, propertyName)); } else if (!nodeInArray.isNull()) { - arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, - nodeInArray, StringUtils.EMPTY))); + encryptedArray.add(encryptAndSerializeValue(encryptionSettings, null, nodeInArray, StringUtils.EMPTY)); + } else { + encryptedArray.add(nodeInArray); } } + arrayNode.removeAll(); + arrayNode.addAll(encryptedArray); } private void encryptLegacyPatchArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, String propertyName) throws MicrosoftDataEncryptionException, JsonProcessingException { - boolean containerArray = isLegacyContainerArray(arrayNode); - for (int i = 0; i < arrayNode.size(); i++) { - JsonNode nodeInArray = arrayNode.get(i); - if (!containerArray) { - arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, - nodeInArray, StringUtils.EMPTY))); - } else if (nodeInArray.isObject() || nodeInArray.isArray()) { - arrayNode.set(i, encryptAndSerializePatchProperty(encryptionSettings, nodeInArray, propertyName)); + 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); + } + } + 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) throws MicrosoftDataEncryptionException, JsonProcessingException { - boolean containerArray = isLegacyContainerArray(arrayNode); - for (int i = 0; i < arrayNode.size(); i++) { - JsonNode nodeInArray = arrayNode.get(i); - if (!containerArray) { - arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, - nodeInArray, StringUtils.EMPTY))); - } else if (nodeInArray.isObject() || nodeInArray.isArray()) { - encryptAndSerializeProperty(encryptionSettings, null, nodeInArray, StringUtils.EMPTY); + 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 { + 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) throws MicrosoftDataEncryptionException, JsonProcessingException { + private void encryptArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, + String propertyName) throws MicrosoftDataEncryptionException, JsonProcessingException { if (this.mixedArrayEncryptionEnabled) { encryptMixedArray(encryptionSettings, arrayNode); } else { - encryptLegacyArray(encryptionSettings, arrayNode); + encryptLegacyArray(encryptionSettings, arrayNode, propertyName); } } private void encryptMixedArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode) throws MicrosoftDataEncryptionException, JsonProcessingException { - for (int i = 0; i < arrayNode.size(); i++) { - JsonNode nodeInArray = arrayNode.get(i); + ArrayNode encryptedArray = arrayNode.arrayNode(); + for (Iterator arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { + JsonNode nodeInArray = arrayIterator.next(); if (nodeInArray.isObject() || nodeInArray.isArray()) { - encryptAndSerializeProperty(encryptionSettings, null, nodeInArray, StringUtils.EMPTY); + encryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); + encryptedArray.add(nodeInArray); } else if (!nodeInArray.isNull()) { - arrayNode.set(i, BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, - nodeInArray, StringUtils.EMPTY))); + 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 { @@ -606,25 +663,60 @@ private void decryptArray(EncryptionSettings encryptionSettings, ArrayNode array private void decryptMixedArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, String propertyName) throws MicrosoftDataEncryptionException, IOException { - for (int i = 0; i < arrayNode.size(); i++) { - JsonNode nodeInArray = arrayNode.get(i); + 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, null, nodeInArray, propertyName); + decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, propertyName); + decryptedArray.add(nodeInArray); } else if (!nodeInArray.isNull()) { - arrayNode.set(i, decryptArrayValue(encryptionSettings, nodeInArray, propertyName, i)); + decryptedArray.add(decryptArrayValue(encryptionSettings, nodeInArray, propertyName, index)); + } else { + decryptedArray.add(nodeInArray); } } + arrayNode.removeAll(); + for (JsonNode decryptedValue : decryptedArray) { + arrayNode.add(decryptedValue); + } } private void decryptLegacyArray(EncryptionSettings encryptionSettings, ArrayNode arrayNode, String propertyName) throws MicrosoftDataEncryptionException, IOException { - boolean containerArray = isLegacyContainerArray(arrayNode); - for (int i = 0; i < arrayNode.size(); i++) { - JsonNode nodeInArray = arrayNode.get(i); - if (!containerArray) { - arrayNode.set(i, decryptArrayValue(encryptionSettings, nodeInArray, propertyName, i)); - } else if (nodeInArray.isObject() || nodeInArray.isArray()) { - decryptAndSerializeProperty(encryptionSettings, null, nodeInArray, propertyName); + 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<>(); + 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); } } } 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 ffa21459a90d1..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 @@ -366,6 +366,22 @@ 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); From 62d18d89bfcee2ad9c6cab963e384bd8a0540c00 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Tue, 24 Nov 2026 11:10:31 -0500 Subject: [PATCH 23/24] Remove encryption user-agent unit tests and module opening Retain core user-agent and live E2E coverage without the encryption-side reflection tests or extra test JVM flag. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sdk/cosmos/azure-cosmos-encryption/pom.xml | 1 - .../CosmosEncryptionAsyncClientUnitTest.java | 112 ------------------ 2 files changed, 113 deletions(-) diff --git a/sdk/cosmos/azure-cosmos-encryption/pom.xml b/sdk/cosmos/azure-cosmos-encryption/pom.xml index cb630c9b0d5ba..09fa7dec9777e 100644 --- a/sdk/cosmos/azure-cosmos-encryption/pom.xml +++ b/sdk/cosmos/azure-cosmos-encryption/pom.xml @@ -48,7 +48,6 @@ Licensed under the MIT License. --add-opens com.azure.cosmos.encryption/com.azure.cosmos.encryption.keyprovider=ALL-UNNAMED --add-opens com.azure.cosmos.encryption/com.azure.cosmos.encryption.util=ALL-UNNAMED --add-opens com.azure.cosmos.encryption/com.azure.cosmos.encryption.models=ALL-UNNAMED - --add-opens com.azure.cosmos/com.azure.cosmos=ALL-UNNAMED --add-opens com.azure.cosmos/com.azure.cosmos.implementation=ALL-UNNAMED --add-modules java.management --add-reads com.azure.cosmos.encryption=java.management 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 783e127401202..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,31 +8,15 @@ import com.azure.cosmos.CosmosAsyncClientEncryptionKey; import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosAsyncDatabase; -import com.azure.cosmos.encryption.implementation.Constants; -import com.azure.cosmos.encryption.implementation.EncryptionProcessor; -import com.azure.cosmos.encryption.implementation.EncryptionSettings; -import com.azure.cosmos.implementation.AsyncDocumentClient; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.RequestOptions; -import com.azure.cosmos.implementation.RxDocumentClientImpl; -import com.azure.cosmos.implementation.UserAgentContainer; -import com.azure.cosmos.implementation.UserAgentFeatureFlags; import com.azure.cosmos.models.CosmosClientEncryptionKeyProperties; import com.azure.cosmos.models.CosmosClientEncryptionKeyResponse; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.lang3.reflect.FieldUtils; import org.mockito.Mockito; -import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import reactor.core.publisher.Mono; -import java.util.EnumSet; - -import static org.assertj.core.api.Assertions.assertThat; - public class CosmosEncryptionAsyncClientUnitTest { - private static final String MIXED_ARRAYS_ENABLED_PROPERTY = "COSMOS.ENCRYPTION_MIXED_ARRAYS_ENABLED"; private final static ImplementationBridgeHelpers.CosmosAsyncClientEncryptionKeyHelper.CosmosAsyncClientEncryptionKeyAccessor cosmosAsyncClientEncryptionKeyAccessor = ImplementationBridgeHelpers.CosmosAsyncClientEncryptionKeyHelper.getCosmosAsyncClientEncryptionKeyAccessor(); @@ -71,100 +55,4 @@ public void clientEncryptionPropertiesAsync() { Mockito.verify(spyEncryptionAsyncClient, Mockito.times(2)).fetchClientEncryptionKeyPropertiesAsync(Mockito.any(CosmosAsyncContainer.class), Mockito.anyString(), Mockito.any(RequestOptions.class)); } - @DataProvider(name = "mixedArrayUserAgentSettings") - public Object[][] mixedArrayUserAgentSettings() { - return new Object[][] {{null, false}, {"true", false}, {"false", true}}; - } - - @Test(groups = {"unit"}, dataProvider = "mixedArrayUserAgentSettings", timeOut = TestSuiteBase.TIMEOUT) - public void encryptionClientAppendsUserAgentSuffix(String setting, boolean optOutExpected) throws Exception { - CosmosAsyncClient mockAsyncClient = Mockito.mock(CosmosAsyncClient.class); - RxDocumentClientImpl mockDocClient = Mockito.mock(RxDocumentClientImpl.class); - KeyEncryptionKeyResolver mockKeyResolver = Mockito.mock(KeyEncryptionKeyResolver.class); - UserAgentContainer userAgent = new UserAgentContainer(); - userAgent.setSuffix("customer-app"); - userAgent.setFeatureEnabledFlagsAsSuffix(EnumSet.of(UserAgentFeatureFlags.ThinClient)); - FieldUtils.writeField(mockDocClient, "userAgentContainer", userAgent, true); - FieldUtils.writeField(mockAsyncClient, "asyncDocumentClient", mockDocClient, true); - Mockito.doCallRealMethod().when(mockDocClient).appendUserAgentSuffix(Mockito.anyString()); - Mockito.doCallRealMethod().when(mockDocClient) - .addUserAgentFeatureFlag(Mockito.any(UserAgentFeatureFlags.class)); - String previousValue = System.getProperty(MIXED_ARRAYS_ENABLED_PROPERTY); - - try { - if (setting == null) { - System.clearProperty(MIXED_ARRAYS_ENABLED_PROPERTY); - } else { - System.setProperty(MIXED_ARRAYS_ENABLED_PROPERTY, setting); - } - new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); - new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); - - assertThat(userAgent.getUserAgent()) - .contains("customer-app", Constants.USER_AGENT_SUFFIX); - assertThat(userAgent.getSuffix().split("\\s+")) - .containsExactly("customer-app", Constants.USER_AGENT_SUFFIX); - assertThat(userAgent.getUserAgent()).endsWith(optOutExpected ? "|F84" : "|F4"); - } finally { - restoreMixedArraySetting(previousValue); - } - } - - @Test(groups = {"unit"}, timeOut = TestSuiteBase.TIMEOUT) - public void encryptionOptOutSnapshotMatchesUserAgent() throws Exception { - CosmosAsyncClient mockAsyncClient = Mockito.mock(CosmosAsyncClient.class); - AsyncDocumentClient mockDocClient = Mockito.mock(AsyncDocumentClient.class); - FieldUtils.writeField(mockAsyncClient, "asyncDocumentClient", mockDocClient, true); - KeyEncryptionKeyResolver mockKeyResolver = Mockito.mock(KeyEncryptionKeyResolver.class); - String previousValue = System.getProperty(MIXED_ARRAYS_ENABLED_PROPERTY); - try { - System.setProperty(MIXED_ARRAYS_ENABLED_PROPERTY, "false"); - CosmosEncryptionAsyncClient client = - new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); - System.setProperty(MIXED_ARRAYS_ENABLED_PROPERTY, "true"); - - EncryptionProcessor processor = new EncryptionProcessor(Mockito.mock(CosmosAsyncContainer.class), client); - JsonNode array = new ObjectMapper().readTree("[{},42]"); - JsonNode encryptedArray = processor.encryptAndSerializePatchProperty( - Mockito.mock(EncryptionSettings.class), array, "sensitiveString"); - - assertThat(client.isMixedArrayEncryptionEnabled()).isFalse(); - assertThat(encryptedArray.get(1).asInt()).isEqualTo(42); - Mockito.verify(mockDocClient).addUserAgentFeatureFlag(UserAgentFeatureFlags.EncryptionMixedArrayOptOut); - } finally { - restoreMixedArraySetting(previousValue); - } - } - - private void restoreMixedArraySetting(String previousValue) { - if (previousValue == null) { - System.clearProperty(MIXED_ARRAYS_ENABLED_PROPERTY); - } else { - System.setProperty(MIXED_ARRAYS_ENABLED_PROPERTY, previousValue); - } - } - - @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() throws Exception { - CosmosAsyncClient mockAsyncClient = Mockito.mock(CosmosAsyncClient.class); - AsyncDocumentClient mockDocClient = Mockito.mock(AsyncDocumentClient.class); - KeyEncryptionKeyResolver mockKeyResolver = Mockito.mock(KeyEncryptionKeyResolver.class); - FieldUtils.writeField(mockAsyncClient, "asyncDocumentClient", mockDocClient, true); - Mockito.doThrow(new RuntimeException("simulated failure")) - .when(mockDocClient).appendUserAgentSuffix(Constants.USER_AGENT_SUFFIX); - - CosmosEncryptionAsyncClient client = - new CosmosEncryptionAsyncClient(mockAsyncClient, mockKeyResolver, "TEST_KEY_RESOLVER"); - assertThat(client).isNotNull(); - assertThat(client.getCosmosAsyncClient()).isSameAs(mockAsyncClient); - } } From 6be7d2761018dde75ef1c519844c3fdbab66a05d Mon Sep 17 00:00:00 2001 From: Abhijeet Mohanty Date: Tue, 24 Nov 2026 11:17:21 -0500 Subject: [PATCH 24/24] Keep standalone scalar PATCH behavior unchanged Restore the scalar helper fallback from main so the mixed-array fix does not include an unrelated behavior change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../encryption/implementation/EncryptionProcessor.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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 1ddee4de055dd..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 @@ -370,9 +370,8 @@ else if (propertyValueHolder.isArray()) { ArrayNode arrayNode = (ArrayNode) propertyValueHolder; encryptPatchArray(encryptionSettings, arrayNode, propertyName); return arrayNode; - } else if (!propertyValueHolder.isNull()) { - return BinaryNode.valueOf(encryptAndSerializeValue(encryptionSettings, null, propertyValueHolder, - propertyName)); + } else { + encryptAndSerializeValue(encryptionSettings, null, propertyValueHolder, propertyName); } return propertyValueHolder; }