This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 580ced7a2e7c CAMEL-27663: camel-azure-iothub - the device client pool
key includes the connection string, so clients for different keys are not
shared (#31020)
580ced7a2e7c is described below
commit 580ced7a2e7cbe9fbb34334ac791ab8874c5faf8
Author: Claus Ibsen <[email protected]>
AuthorDate: Fri Nov 27 20:32:02 2026 +0100
CAMEL-27663: camel-azure-iothub - the device client pool key includes the
connection string, so clients for different keys are not shared (#31020)
The pool keyed its device clients by the HostName, DeviceId and ModuleId of
the connection string only, so a connection string of the same device with
another key reused the client opened with the first key. The pool key now
also holds a SHA-256 hash of the whole connection string (never the key
itself), so each connection string gets its own client. Removing a device
closes the clients of all its connection strings.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Claus Ibsen <[email protected]>
---
.../camel/catalog/docs/azure-iothub-component.adoc | 6 +-
.../src/main/docs/azure-iothub-component.adoc | 6 +-
.../azure/iothub/client/DeviceClientPool.java | 158 ++++++++++++---------
.../azure/iothub/IoTHubComponentTest.java | 45 ++++++
.../azure/iothub/client/DeviceClientPoolTest.java | 65 +++++++++
5 files changed, 207 insertions(+), 73 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/azure-iothub-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/azure-iothub-component.adoc
index b86eaa00e74f..1d545f05339f 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/azure-iothub-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/azure-iothub-component.adoc
@@ -17,8 +17,10 @@
The Azure IoT Hub component provides the capability to send device-to-cloud
telemetry and to update device-twin reported properties on
https://azure.microsoft.com/services/iot-hub/[Azure IoT Hub], using the
-Azure IoT device SDK. Device connections are pooled and reused by the
-resolved hub/device/module identity from the connection string.
+Azure IoT device SDK. Device connections are pooled and reused per
+connection string: a message only gets a pooled connection that was opened
+with the same connection string, including its key, so connection strings of
+the same device with different keys get their own connections.
*Prerequisites*
diff --git
a/components/camel-azure/camel-azure-iothub/src/main/docs/azure-iothub-component.adoc
b/components/camel-azure/camel-azure-iothub/src/main/docs/azure-iothub-component.adoc
index b86eaa00e74f..1d545f05339f 100644
---
a/components/camel-azure/camel-azure-iothub/src/main/docs/azure-iothub-component.adoc
+++
b/components/camel-azure/camel-azure-iothub/src/main/docs/azure-iothub-component.adoc
@@ -17,8 +17,10 @@
The Azure IoT Hub component provides the capability to send device-to-cloud
telemetry and to update device-twin reported properties on
https://azure.microsoft.com/services/iot-hub/[Azure IoT Hub], using the
-Azure IoT device SDK. Device connections are pooled and reused by the
-resolved hub/device/module identity from the connection string.
+Azure IoT device SDK. Device connections are pooled and reused per
+connection string: a message only gets a pooled connection that was opened
+with the same connection string, including its key, so connection strings of
+the same device with different keys get their own connections.
*Prerequisites*
diff --git
a/components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java
b/components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java
index 635e1ad502e7..79ea884c088f 100644
---
a/components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java
+++
b/components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java
@@ -16,7 +16,11 @@
*/
package org.apache.camel.component.azure.iothub.client;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
import java.time.Duration;
+import java.util.HexFormat;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@@ -43,7 +47,10 @@ import org.slf4j.LoggerFactory;
/**
* Thread-safe pool of Azure IoT Hub {@link DeviceClient} instances, keyed by
the resolved hub/device/module identity
- * derived from the connection string instead of only the raw device id.
+ * derived from the connection string instead of only the raw device id,
together with a SHA-256 hash of the whole
+ * connection string. A client is only reused for the same connection string,
so a connection string with another key
+ * (or without a key) never gets a client that was opened with a different
credential: it opens its own client, and IoT
+ * Hub checks its credential.
*
* <p>
* Clients are created lazily, reused across messages, and evicted after an
idle timeout. A client is idle only while it
@@ -61,7 +68,7 @@ import org.slf4j.LoggerFactory;
*/
public class DeviceClientPool {
- // the suffix of the pool key of a client over HTTPS; ':' separates the
parts of the identity
+ // the suffix of a client over HTTPS in the log text of its pool key; ':'
separates the parts of the identity
private static final String HTTPS_KEY_SUFFIX = "|HTTPS";
private static final Logger LOG =
LoggerFactory.getLogger(DeviceClientPool.class);
@@ -136,8 +143,8 @@ public class DeviceClientPool {
private final Duration idleTimeout;
private final Duration evictionInterval;
- private final Map<String, PooledClient> pool = new ConcurrentHashMap<>();
- private final Map<String, CompletableFuture<DeviceClient>> creationFutures
= new ConcurrentHashMap<>();
+ private final Map<PoolKey, PooledClient> pool = new ConcurrentHashMap<>();
+ private final Map<PoolKey, CompletableFuture<DeviceClient>>
creationFutures = new ConcurrentHashMap<>();
private final Set<PooledClient> pendingClose =
ConcurrentHashMap.newKeySet();
private final AtomicBoolean shuttingDown = new AtomicBoolean(false);
@@ -202,7 +209,7 @@ public class DeviceClientPool {
throw new IllegalStateException("Skipping client creation due to
shutdown: " + deviceId);
}
- String poolKey = resolvePoolKey(deviceId, connectionString, protocol);
+ PoolKey poolKey = resolvePoolKey(deviceId, connectionString, protocol);
PooledClient existing = pool.get(poolKey);
if (existing != null) {
@@ -281,7 +288,7 @@ public class DeviceClientPool {
throw new IllegalStateException("Skipping client creation due to
shutdown: " + deviceId);
}
- String poolKey = resolvePoolKey(deviceId, connectionString, protocol);
+ PoolKey poolKey = resolvePoolKey(deviceId, connectionString, protocol);
for (;;) {
// read the clock on every attempt: getOrCreate below can block
for a whole open of the client
@@ -300,7 +307,7 @@ public class DeviceClientPool {
return new Lease(this, existing);
}
if (evicted.get() != null) {
- closeQuietly(poolKey, evicted.get().client, "idle eviction");
+ closeQuietly(poolKey.toString(), evicted.get().client, "idle
eviction");
continue;
}
@@ -334,7 +341,7 @@ public class DeviceClientPool {
return acquire(deviceId, connectionString, protocol, subscribeTimeout);
}
- private boolean isCreationInProgress(String poolKey) {
+ private boolean isCreationInProgress(PoolKey poolKey) {
return creationFutures.containsKey(poolKey);
}
@@ -342,8 +349,8 @@ public class DeviceClientPool {
if (deviceId == null || deviceId.isBlank()) {
return false;
}
- for (String poolKey : creationFutures.keySet()) {
- if (matchesDeviceId(poolKey, deviceId)) {
+ for (PoolKey poolKey : creationFutures.keySet()) {
+ if (poolKey.matchesDeviceId(deviceId)) {
return true;
}
}
@@ -351,9 +358,8 @@ public class DeviceClientPool {
}
void remove(String deviceId, String connectionString) {
- String poolKey = resolvePoolKey(deviceId, connectionString);
- removePoolEntry(poolKey);
- removePoolEntry(poolKey + HTTPS_KEY_SUFFIX);
+ removePoolEntry(resolvePoolKey(deviceId, connectionString, false));
+ removePoolEntry(resolvePoolKey(deviceId, connectionString, true));
}
void remove(String deviceId) {
@@ -365,61 +371,68 @@ public class DeviceClientPool {
return;
}
- String directKey = deviceId;
- PooledClient pooled = pool.remove(directKey);
- if (pooled != null) {
- closeQuietly(deviceId, pooled.client, "explicit removal");
- return;
- }
-
- for (Map.Entry<String, PooledClient> entry : pool.entrySet()) {
- String key = entry.getKey();
- if (matchesDeviceId(key, deviceId)) {
- if (pool.remove(key, entry.getValue())) {
- closeQuietly(deviceId, entry.getValue().client, "explicit
removal");
- return;
- }
+ // a device can have several clients, one per connection string (for
example while a key is rotated)
+ for (Map.Entry<PoolKey, PooledClient> entry : pool.entrySet()) {
+ if (entry.getKey().matchesDeviceId(deviceId) &&
pool.remove(entry.getKey(), entry.getValue())) {
+ closeQuietly(deviceId, entry.getValue().client, "explicit
removal");
}
}
}
- private void removePoolEntry(String poolKey) {
- if (poolKey == null || poolKey.isBlank()) {
- return;
- }
+ private void removePoolEntry(PoolKey poolKey) {
if (isCreationInProgress(poolKey)) {
LOG.debug("Skipping removal of in-flight DeviceClient for device
{} while creation is still in progress", poolKey);
return;
}
PooledClient pooled = pool.remove(poolKey);
if (pooled != null) {
- closeQuietly(poolKey, pooled.client, "explicit removal");
+ closeQuietly(poolKey.toString(), pooled.client, "explicit
removal");
}
}
- private static boolean matchesDeviceId(String poolKey, String deviceId) {
- if (poolKey == null) {
- return false;
- }
- if (poolKey.endsWith(HTTPS_KEY_SUFFIX)) {
- poolKey = poolKey.substring(0, poolKey.length() -
HTTPS_KEY_SUFFIX.length());
+ /**
+ * The key of a pooled client: the hub, device and module of the
connection string, whether the client is over
+ * HTTPS, and a SHA-256 hash of the whole connection string, so the
credential (SharedAccessKey,
+ * SharedAccessSignature, ...) is part of the key without the key holding
it. A client over HTTPS is kept apart from
+ * the client over MQTT or AMQPS of the same device, as it cannot do twin
operations. {@link #toString()} leaves the
+ * hash out, as it is used in log messages.
+ */
+ private record PoolKey(String hostName, String deviceId, String moduleId,
boolean https, String connectionStringHash) {
+
+ boolean matchesDeviceId(String id) {
+ return deviceId != null && deviceId.equals(id);
}
- if (poolKey.equals(deviceId)) {
- return true;
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ if (hostName != null) {
+ sb.append(hostName);
+ }
+ if (deviceId != null) {
+ if (!sb.isEmpty()) {
+ sb.append(':');
+ }
+ sb.append(deviceId);
+ }
+ if (moduleId != null) {
+ if (!sb.isEmpty()) {
+ sb.append(':');
+ }
+ sb.append(moduleId);
+ }
+ if (https) {
+ sb.append(HTTPS_KEY_SUFFIX);
+ }
+ return sb.toString();
}
- String[] parts = poolKey.split(":");
- return parts.length >= 2 && parts[1].equals(deviceId);
}
- private static String resolvePoolKey(String deviceId, String
connectionString, IotHubClientProtocol protocol) {
- String poolKey = resolvePoolKey(deviceId, connectionString);
- return protocol == IotHubClientProtocol.HTTPS ? poolKey +
HTTPS_KEY_SUFFIX : poolKey;
+ private static PoolKey resolvePoolKey(String deviceId, String
connectionString, IotHubClientProtocol protocol) {
+ return resolvePoolKey(deviceId, connectionString, protocol ==
IotHubClientProtocol.HTTPS);
}
- private static String resolvePoolKey(String deviceId, String
connectionString) {
- if (deviceId == null || deviceId.isBlank()) {
- return connectionString;
- }
+ private static PoolKey resolvePoolKey(String deviceId, String
connectionString, boolean https) {
String[] items = connectionString == null ? new String[0] :
connectionString.split(";");
String hostName = null;
String csDeviceId = null;
@@ -443,27 +456,34 @@ public class DeviceClientPool {
}
}
}
- if (csDeviceId != null && !csDeviceId.equals(deviceId)) {
+ boolean hasDeviceId = deviceId != null && !deviceId.isBlank();
+ if (hasDeviceId && csDeviceId != null && !csDeviceId.equals(deviceId))
{
throw new IllegalArgumentException(
"Device id '" + deviceId + "' does not match the
connection string's DeviceId '" + csDeviceId + "'");
}
- StringBuilder identity = new StringBuilder();
- if (hostName != null && !hostName.isBlank()) {
- identity.append(hostName);
- }
+ String device;
if (csDeviceId != null && !csDeviceId.isBlank()) {
- if (!identity.isEmpty()) {
- identity.append(':');
- }
- identity.append(csDeviceId);
+ device = csDeviceId;
+ } else {
+ device = hasDeviceId ? deviceId : null;
}
- if (moduleId != null && !moduleId.isBlank()) {
- if (!identity.isEmpty()) {
- identity.append(':');
- }
- identity.append(moduleId);
+ return new PoolKey(
+ hostName != null && !hostName.isBlank() ? hostName : null,
+ device,
+ moduleId != null && !moduleId.isBlank() ? moduleId : null,
+ https,
+ sha256(connectionString));
+ }
+
+ private static String sha256(String value) {
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ byte[] hash = digest.digest((value == null ? "" :
value).getBytes(StandardCharsets.UTF_8));
+ return HexFormat.of().formatHex(hash);
+ } catch (NoSuchAlgorithmException e) {
+ // every Java platform must support SHA-256
+ throw new IllegalStateException("SHA-256 is not available", e);
}
- return !identity.isEmpty() ? identity.toString() : deviceId;
}
private DeviceClient createClient(
@@ -528,7 +548,7 @@ public class DeviceClientPool {
return;
}
- String poolKey = resolvePoolKey(deviceId, connectionString, protocol);
+ PoolKey poolKey = resolvePoolKey(deviceId, connectionString, protocol);
AtomicReference<PooledClient> removed = new AtomicReference<>();
pool.computeIfPresent(poolKey, (key, pooled) -> {
@@ -585,8 +605,8 @@ public class DeviceClientPool {
return;
}
long now = nowMillis();
- for (Map.Entry<String, PooledClient> entry : pool.entrySet()) {
- String key = entry.getKey();
+ for (Map.Entry<PoolKey, PooledClient> entry : pool.entrySet()) {
+ PoolKey key = entry.getKey();
AtomicReference<PooledClient> retired = new AtomicReference<>();
pool.computeIfPresent(key, (k, current) -> {
if (current.isIdle(now, idleTimeout.toMillis())) {
@@ -624,8 +644,8 @@ public class DeviceClientPool {
}
}
creationFutures.clear();
- for (Map.Entry<String, PooledClient> entry : pool.entrySet()) {
- closeQuietly(entry.getKey(), entry.getValue() == null ? null :
entry.getValue().client, "shutdown");
+ for (Map.Entry<PoolKey, PooledClient> entry : pool.entrySet()) {
+ closeQuietly(entry.getKey().toString(), entry.getValue() == null ?
null : entry.getValue().client, "shutdown");
}
pool.clear();
}
diff --git
a/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/IoTHubComponentTest.java
b/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/IoTHubComponentTest.java
index b23d50c36ca1..a77aa265054a 100644
---
a/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/IoTHubComponentTest.java
+++
b/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/IoTHubComponentTest.java
@@ -41,6 +41,7 @@ import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class IoTHubComponentTest extends CamelTestSupport {
@@ -173,6 +174,50 @@ class IoTHubComponentTest extends CamelTestSupport {
verify(client, never()).sendEvent(any(Message.class), anyInt());
}
+ @Test
+ void
testHeaderConnectionStringWithAnotherKeyDoesNotUseClientOfOtherEndpoint()
throws Exception {
+ String good = "HostName=h;DeviceId=myDevice;SharedAccessKey=good";
+ String other = "HostName=h;DeviceId=myDevice;SharedAccessKey=other";
+
+ DeviceClient client = mock(DeviceClient.class);
+ DeviceClientPool pool = new DeviceClientPool(Duration.ofMinutes(5),
Duration.ofSeconds(30));
+ // like IoT Hub, open a client only for the right key
+ pool.setDeviceClientFactory((cs, protocol) -> {
+ if (!cs.equals(good)) {
+ throw new IllegalStateException("Unauthorized");
+ }
+ return client;
+ });
+
+ IoTHubComponent component = new IoTHubComponent();
+ component.setCamelContext(context);
+ setField(component, "clientPool", pool);
+
+ // an endpoint configured with the key of the device opens a client
for it
+ IoTHubConfiguration configured = new IoTHubConfiguration();
+ configured.setDeviceId("myDevice");
+ configured.setConnectionString(good);
+ IoTHubProducer producer = new IoTHubProducer(new
IoTHubEndpoint("azure-iothub:myDevice", component, configured));
+ producer.start();
+ Exchange exchange = new DefaultExchange(context);
+ exchange.getIn().setBody("hello");
+ producer.process(exchange);
+
+ // an endpoint of the same component that takes the device and
connection string from headers
+ IoTHubConfiguration dynamic = new IoTHubConfiguration();
+ dynamic.setDeviceId("placeholder");
+ IoTHubProducer dynamicProducer
+ = new IoTHubProducer(new
IoTHubEndpoint("azure-iothub:placeholder", component, dynamic));
+ dynamicProducer.start();
+ Exchange headerExchange = new DefaultExchange(context);
+ headerExchange.getIn().setHeader(IoTHubConstants.DEVICE_ID,
"myDevice");
+ headerExchange.getIn().setHeader(IoTHubConstants.CONNECTION_STRING,
other);
+ headerExchange.getIn().setBody("hello");
+
+ assertThrows(RuntimeException.class, () ->
dynamicProducer.process(headerExchange));
+ verify(client, times(1)).sendEvent(any(Message.class), anyInt());
+ }
+
private static void setField(Object target, String fieldName, Object
value) throws Exception {
Field field = target.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
diff --git
a/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/client/DeviceClientPoolTest.java
b/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/client/DeviceClientPoolTest.java
index 646218ea866d..12f91ca3587e 100644
---
a/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/client/DeviceClientPoolTest.java
+++
b/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/client/DeviceClientPoolTest.java
@@ -155,6 +155,71 @@ class DeviceClientPoolTest {
assertThrows(IllegalArgumentException.class, () ->
pool.getOrCreate("dev1", CS, IotHubClientProtocol.MQTT));
}
+ @Test
+ void testConnectionStringWithAnotherKeyDoesNotReusePooledClient() {
+ String good = "HostName=h;DeviceId=d;SharedAccessKey=good";
+ String other = "HostName=h;DeviceId=d;SharedAccessKey=other";
+ String noKey = "HostName=h;DeviceId=d";
+ DeviceClient client = mock(DeviceClient.class);
+ List<String> opened = new ArrayList<>();
+ DeviceClientPool pool = new DeviceClientPool(Duration.ofMinutes(5),
Duration.ofSeconds(30));
+ // like IoT Hub, open a client only for the right key
+ pool.setDeviceClientFactory((cs, protocol) -> {
+ opened.add(cs);
+ if (!cs.equals(good)) {
+ throw new IllegalStateException("Unauthorized");
+ }
+ return client;
+ });
+
+ try (DeviceClientPool.Lease lease = pool.lease("d", good,
IotHubClientProtocol.MQTT)) {
+ assertSame(client, lease.getClient());
+ }
+ // the client of the right key is pooled, but another key or no key
must open its own client
+ assertThrows(RuntimeException.class, () -> pool.lease("d", other,
IotHubClientProtocol.MQTT));
+ assertThrows(RuntimeException.class, () -> pool.lease("d", noKey,
IotHubClientProtocol.MQTT));
+
+ assertEquals(List.of(good, other, noKey), opened);
+ assertEquals(1, pool.getActiveClientCount());
+ }
+
+ @Test
+ void testConnectionStringWithWrongKeyIsRejectedOnEmptyPool() {
+ DeviceClientPool pool = new DeviceClientPool(Duration.ofMinutes(5),
Duration.ofSeconds(30));
+ pool.setDeviceClientFactory((cs, protocol) -> {
+ throw new IllegalStateException("Unauthorized");
+ });
+
+ assertThrows(RuntimeException.class, () -> pool.lease("d", CS,
IotHubClientProtocol.MQTT));
+ assertEquals(0, pool.getActiveClientCount());
+ }
+
+ @Test
+ void testTwoKeysOfSameDeviceGetOwnClients() throws Exception {
+ String primary = "HostName=h;DeviceId=d;SharedAccessKey=primary";
+ String secondary = "HostName=h;DeviceId=d;SharedAccessKey=secondary";
+ DeviceClient primaryClient = mock(DeviceClient.class);
+ DeviceClient secondaryClient = mock(DeviceClient.class);
+ DeviceClientPool pool = new DeviceClientPool(Duration.ofMinutes(5),
Duration.ofSeconds(30));
+ pool.setDeviceClientFactory((cs, protocol) -> cs.equals(primary) ?
primaryClient : secondaryClient);
+
+ try (DeviceClientPool.Lease first = pool.lease("d", primary,
IotHubClientProtocol.MQTT);
+ DeviceClientPool.Lease second = pool.lease("d", secondary,
IotHubClientProtocol.MQTT)) {
+ assertSame(primaryClient, first.getClient());
+ assertSame(secondaryClient, second.getClient());
+ }
+ try (DeviceClientPool.Lease again = pool.lease("d", primary,
IotHubClientProtocol.MQTT)) {
+ assertSame(primaryClient, again.getClient());
+ }
+ assertEquals(2, pool.getActiveClientCount());
+
+ // removing the device closes the clients of all its connection strings
+ pool.remove("d");
+ assertEquals(0, pool.getActiveClientCount());
+ verify(primaryClient, times(1)).close();
+ verify(secondaryClient, times(1)).close();
+ }
+
@Test
void testRemoveClosesClient() throws Exception {
DeviceClient client = mock(DeviceClient.class);