Skip to content

Commit f7ec207

Browse files
jeet1995Copilot
andauthored
[Cosmos Encryption] Encrypt each array element independently for mixed-type arrays (#51247)
* Fix mixed-array client-side encryption Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * 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> * 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> * 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> * 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> * 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 be7befe) * 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 9b2ee77) * 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 234ba13) * 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 43e221c) * 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 04364a7) * 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 aedf49c) * 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 44fe92a) * 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 c7fa98e) * 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 b8b6c8f) * 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 5d8cf1c) * 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 c655610) * 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> * 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> * 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> * 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> * 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> * 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> * 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> * 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> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent d3cff40 commit f7ec207

21 files changed

Lines changed: 1115 additions & 221 deletions

‎sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
#### Features Added
66

77
#### Breaking Changes
8+
* 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)
89

910
#### Bugs Fixed
11+
* 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)
1012

1113
#### Other Changes
1214

‎sdk/cosmos/azure-cosmos-encryption/README.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,52 @@ However, because Azure Cosmos DB is accessed via network calls there are client-
151151

152152
- [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.
153153

154+
### Legacy mixed-type arrays
155+
156+
Earlier SDK versions could leave scalar array elements unencrypted inside an encrypted property when the first
157+
array element was an object or another array. For example, with `/sensitive` included in the encryption policy,
158+
writing `[{"label":"secret"},42]` encrypted `"secret"` but left `42` in plaintext. This can occur in nested arrays
159+
as well. The old reader skipped the same scalar elements, so reads could succeed despite the missing encryption.
160+
161+
The corrected reader decrypts every non-null scalar array element. If an element cannot be decrypted, it throws
162+
`IllegalStateException` with the encrypted property name, the array-local index, migration guidance, and the original
163+
exception as its cause. It does not silently return the value as plaintext. This failure can also indicate incorrect
164+
keys or damaged ciphertext; it is not proof that the item was written by an older SDK.
165+
166+
#### Temporary compatibility opt-out
167+
168+
The fix is enabled by default. To temporarily restore legacy array traversal for **both reads and writes**
169+
(including PATCH), set either of the following before creating encryption clients:
170+
171+
- JVM system property: `-DCOSMOS.ENCRYPTION_MIXED_ARRAYS_ENABLED=false`
172+
- Environment variable: `COSMOS_ENCRYPTION_MIXED_ARRAYS_ENABLED=false`
173+
174+
A non-empty JVM property takes precedence over the environment variable. Values are case-insensitive `true` or
175+
`false`; invalid values are rejected rather than silently disabling encryption. Each encryption client
176+
captures the setting when it is created and shares it with its container processors; restart the application
177+
to change modes consistently.
178+
The setting is implemented in the encryption package and does not require a new `azure-cosmos` config getter.
179+
180+
**Warning:** legacy mode restores the first-element-based behavior, including the bug that leaves scalar elements
181+
unencrypted after an object or array. It logs a warning once per JVM and is a migration bridge, not a long-term fix.
182+
It also retains legacy failures for unsupported scalar-first mixed arrays. Legacy readers skip scalar elements
183+
after a leading container, so they cannot correctly read mixed arrays already written with the fix enabled.
184+
Do not use the two modes interchangeably on the same data or switch to legacy mode after writing corrected data.
185+
Opt-out is an explicit traversal choice, not a fallback for decoding or authentication failures.
186+
187+
If you confirm that an item contains legacy mixed-type arrays:
188+
189+
1. Coordinate a migration so old clients do not read rewritten items or write more legacy items during the cutover.
190+
2. Read the affected items with the SDK version that wrote them, or with the compatibility opt-out in a separate
191+
migration reader process, to recover their decrypted values.
192+
3. Pass the decrypted items to a separate encryption-enabled writer process with the fix enabled and rewrite the
193+
complete items. Use ETags to prevent overwriting concurrent changes; do not first read the legacy items through
194+
the corrected reader. Do not copy raw encrypted values into the writer.
195+
4. Resume normal access with the fix enabled after the affected items have been migrated.
196+
197+
These items are partially encrypted, not wholly unencrypted: existing encrypted fields still require decryption.
198+
Do not treat authentication failures as plaintext or assume that raw stored items can be rewritten without decryption.
199+
154200
### Enable Client Logging
155201
Azure Cosmos DB Java SDK v4 uses SLF4j as the logging facade that supports logging into popular logging frameworks such as log4j and logback.
156202

‎sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/CosmosEncryptionAsyncClient.java‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,17 @@
1010
import com.azure.cosmos.CosmosAsyncClientEncryptionKey;
1111
import com.azure.cosmos.CosmosAsyncContainer;
1212
import com.azure.cosmos.CosmosAsyncDatabase;
13-
import com.azure.cosmos.CosmosBridgeInternal;
1413
import com.azure.cosmos.CosmosException;
1514
import com.azure.cosmos.CosmosItemSerializer;
1615
import com.azure.cosmos.encryption.implementation.Constants;
16+
import com.azure.cosmos.encryption.implementation.EncryptionConfigs;
1717
import com.azure.cosmos.encryption.implementation.EncryptionImplementationBridgeHelpers;
1818
import com.azure.cosmos.encryption.implementation.keyprovider.EncryptionKeyStoreProviderImpl;
1919
import com.azure.cosmos.implementation.HttpConstants;
2020
import com.azure.cosmos.implementation.ImplementationBridgeHelpers;
2121
import com.azure.cosmos.implementation.RequestOptions;
2222
import com.azure.cosmos.implementation.Utils;
23+
import com.azure.cosmos.implementation.UserAgentFeatureFlags;
2324
import com.azure.cosmos.implementation.apachecommons.lang.StringUtils;
2425
import com.azure.cosmos.implementation.caches.AsyncCache;
2526
import com.azure.cosmos.models.CosmosClientEncryptionKeyProperties;
@@ -46,6 +47,7 @@ public final class CosmosEncryptionAsyncClient implements Closeable {
4647
private final KeyEncryptionKeyResolver keyEncryptionKeyResolver;
4748
private final String keyEncryptionKeyResolverName;
4849
private final EncryptionKeyStoreProviderImpl encryptionKeyStoreProviderImpl;
50+
private final boolean mixedArrayEncryptionEnabled;
4951
private final static ImplementationBridgeHelpers.CosmosAsyncClientEncryptionKeyHelper.CosmosAsyncClientEncryptionKeyAccessor cosmosAsyncClientEncryptionKeyAccessor = ImplementationBridgeHelpers.CosmosAsyncClientEncryptionKeyHelper.getCosmosAsyncClientEncryptionKeyAccessor();
5052

5153
private final static ImplementationBridgeHelpers.CosmosAsyncClientHelper.CosmosAsyncClientAccessor cosmosAsyncClientAccessor = ImplementationBridgeHelpers.CosmosAsyncClientHelper.getCosmosAsyncClientAccessor();
@@ -62,6 +64,7 @@ public final class CosmosEncryptionAsyncClient implements Closeable {
6264
if (StringUtils.isEmpty(keyEncryptionKeyResolverName)) {
6365
throw new IllegalArgumentException("keyEncryptionKeyResolverName is null");
6466
}
67+
this.mixedArrayEncryptionEnabled = EncryptionConfigs.isMixedArrayEncryptionEnabled();
6568
this.cosmosAsyncClient = cosmosAsyncClient;
6669
this.keyEncryptionKeyResolver = keyEncryptionKeyResolver;
6770
this.clientEncryptionKeyPropertiesCacheByKeyId = new AsyncCache<>();
@@ -93,6 +96,10 @@ EncryptionKeyStoreProviderImpl getEncryptionKeyStoreProviderImpl() {
9396
return encryptionKeyStoreProviderImpl;
9497
}
9598

99+
boolean isMixedArrayEncryptionEnabled() {
100+
return this.mixedArrayEncryptionEnabled;
101+
}
102+
96103
Mono<CosmosContainerProperties> getContainerPropertiesAsync(
97104
CosmosAsyncContainer container,
98105
boolean shouldForceRefresh) {
@@ -195,9 +202,11 @@ public CosmosAsyncClient getCosmosAsyncClient() {
195202

196203
private void appendEncryptionUserAgentSuffix() {
197204
try {
198-
CosmosBridgeInternal
199-
.getAsyncDocumentClient(this.cosmosAsyncClient)
200-
.appendUserAgentSuffix(Constants.USER_AGENT_SUFFIX);
205+
cosmosAsyncClientAccessor.appendUserAgentSuffix(this.cosmosAsyncClient, Constants.USER_AGENT_SUFFIX);
206+
if (!this.mixedArrayEncryptionEnabled) {
207+
cosmosAsyncClientAccessor.addUserAgentFeatureFlag(this.cosmosAsyncClient,
208+
UserAgentFeatureFlags.EncryptionMixedArrayOptOut);
209+
}
201210
} catch (Exception e) {
202211
LOGGER.warn("Failed to append encryption SDK user agent suffix", e);
203212
}
@@ -273,6 +282,11 @@ public Mono<CosmosContainerProperties> getContainerPropertiesAsync(CosmosEncrypt
273282
public EncryptionKeyStoreProviderImpl getEncryptionKeyStoreProviderImpl(CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient) {
274283
return cosmosEncryptionAsyncClient.getEncryptionKeyStoreProviderImpl();
275284
}
285+
286+
@Override
287+
public boolean isMixedArrayEncryptionEnabled(CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient) {
288+
return cosmosEncryptionAsyncClient.isMixedArrayEncryptionEnabled();
289+
}
276290
});
277291
}
278292
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
package com.azure.cosmos.encryption.implementation;
5+
6+
import org.slf4j.Logger;
7+
import org.slf4j.LoggerFactory;
8+
9+
import java.util.concurrent.atomic.AtomicBoolean;
10+
11+
/**
12+
* Internal configuration for the encryption SDK.
13+
*/
14+
public final class EncryptionConfigs {
15+
static final String MIXED_ARRAYS_ENABLED = "COSMOS.ENCRYPTION_MIXED_ARRAYS_ENABLED";
16+
static final String MIXED_ARRAYS_ENABLED_VARIABLE = "COSMOS_ENCRYPTION_MIXED_ARRAYS_ENABLED";
17+
private static final Logger LOGGER = LoggerFactory.getLogger(EncryptionConfigs.class);
18+
private static final AtomicBoolean LEGACY_MODE_WARNING_LOGGED = new AtomicBoolean(false);
19+
20+
private EncryptionConfigs() {
21+
}
22+
23+
/**
24+
* Resolves the mixed-array encryption setting, giving the JVM property precedence over the environment variable.
25+
*
26+
* @return whether corrected mixed-array traversal is enabled
27+
*/
28+
public static boolean isMixedArrayEncryptionEnabled() {
29+
return isMixedArrayEncryptionEnabled(System.getProperty(MIXED_ARRAYS_ENABLED),
30+
System.getenv(MIXED_ARRAYS_ENABLED_VARIABLE));
31+
}
32+
33+
static boolean isMixedArrayEncryptionEnabled(String systemPropertyValue, String environmentVariableValue) {
34+
String value = systemPropertyValue == null || systemPropertyValue.isEmpty()
35+
? environmentVariableValue : systemPropertyValue;
36+
if (value == null || value.isEmpty() || "true".equalsIgnoreCase(value)) {
37+
return true;
38+
}
39+
if ("false".equalsIgnoreCase(value)) {
40+
if (LEGACY_MODE_WARNING_LOGGED.compareAndSet(false, true)) {
41+
LOGGER.warn("Mixed-array encryption is disabled through {} or {}. Legacy traversal can leave "
42+
+ "scalar array elements unencrypted and cannot correctly read mixed arrays written with "
43+
+ "the fix enabled. Use this temporary compatibility mode only until legacy data is migrated.",
44+
MIXED_ARRAYS_ENABLED, MIXED_ARRAYS_ENABLED_VARIABLE);
45+
}
46+
return false;
47+
}
48+
throw new IllegalArgumentException("Invalid " + MIXED_ARRAYS_ENABLED + " or "
49+
+ MIXED_ARRAYS_ENABLED_VARIABLE + " setting. Only 'true' or 'false' are supported.");
50+
}
51+
}

‎sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/EncryptionImplementationBridgeHelpers.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ Mono<CosmosContainerProperties> getContainerPropertiesAsync(
104104
boolean shouldForceRefresh);
105105

106106
EncryptionKeyStoreProviderImpl getEncryptionKeyStoreProviderImpl(CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient);
107+
108+
boolean isMixedArrayEncryptionEnabled(CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient);
107109
}
108110
}
109111

0 commit comments

Comments
 (0)