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 e9627d06a515 CAMEL-27917: camel-hashicorp-vault - read the TLS trust 
store and key store again when their files change (#31183)
e9627d06a515 is described below

commit e9627d06a515771f60c440e5b7235aa512b1d89f
Author: Andrea Cosentino <[email protected]>
AuthorDate: Wed Dec 2 11:54:07 2026 +0100

    CAMEL-27917: camel-hashicorp-vault - read the TLS trust store and key store 
again when their files change (#31183)
    
    The trustStore and keyStore of the HashiCorp Vault client were read once, 
so a renewed
    client certificate was used only after a restart. The client now checks the 
files
    before each request and, when one changed, reads both stores again into a 
new TLS
    context, so the next request uses a new connection with the new stores. If 
a store
    cannot be read while it is being written, the previous stores stay in use 
with a
    warning. No new option; the TLS section of the docs describes the reload.
    
    Claude Code on behalf of oscerd.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../catalog/docs/hashicorp-vault-component.adoc    |   7 +-
 .../src/main/docs/hashicorp-vault-component.adoc   |   7 +-
 .../hashicorp/vault/HashicorpVaultClient.java      |  30 +++-
 .../hashicorp/vault/HashicorpVaultTlsStores.java   | 133 ++++++++++++++++
 .../camel/component/hashicorp/vault/FakeVault.java |  16 +-
 .../vault/HashicorpVaultTlsStoresTest.java         | 174 +++++++++++++++++++++
 6 files changed, 352 insertions(+), 15 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hashicorp-vault-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hashicorp-vault-component.adoc
index bc4e16700ebf..a84f1dd10af2 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hashicorp-vault-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hashicorp-vault-component.adoc
@@ -134,8 +134,11 @@ secret refresh task take `trustStore` and `keyStore` only, 
since they can start
 bound.
 
 The trust store and the key store are read when the client is created, when 
the endpoint, the properties function or
-the secret refresh task starts. A certificate replaced in its file, such as a 
client certificate renewed before it
-expires, is used after a restart.
+the secret refresh task starts, and read again when one of their files 
changes. A certificate replaced in its file,
+such as a client certificate renewed before it expires by the Vault agent or 
cert-manager, is used without a restart,
+from the next request to Vault, which goes over a new connection. A store that 
cannot be read when its file changes,
+such as a file being written, leaves the previous stores in use until its file 
changes again. The
+`sslContextParameters` of an endpoint are read once, when the endpoint starts.
 
 For example, the properties function logs in with a client certificate:
 
diff --git 
a/components/camel-hashicorp-vault/src/main/docs/hashicorp-vault-component.adoc 
b/components/camel-hashicorp-vault/src/main/docs/hashicorp-vault-component.adoc
index bc4e16700ebf..a84f1dd10af2 100644
--- 
a/components/camel-hashicorp-vault/src/main/docs/hashicorp-vault-component.adoc
+++ 
b/components/camel-hashicorp-vault/src/main/docs/hashicorp-vault-component.adoc
@@ -134,8 +134,11 @@ secret refresh task take `trustStore` and `keyStore` only, 
since they can start
 bound.
 
 The trust store and the key store are read when the client is created, when 
the endpoint, the properties function or
-the secret refresh task starts. A certificate replaced in its file, such as a 
client certificate renewed before it
-expires, is used after a restart.
+the secret refresh task starts, and read again when one of their files 
changes. A certificate replaced in its file,
+such as a client certificate renewed before it expires by the Vault agent or 
cert-manager, is used without a restart,
+from the next request to Vault, which goes over a new connection. A store that 
cannot be read when its file changes,
+such as a file being written, leaves the previous stores in use until its file 
changes again. The
+`sslContextParameters` of an endpoint are read once, when the endpoint starts.
 
 For example, the properties function logs in with a client certificate:
 
diff --git 
a/components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultClient.java
 
b/components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultClient.java
index fab96d09f7df..a3fd429c21d9 100644
--- 
a/components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultClient.java
+++ 
b/components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultClient.java
@@ -32,7 +32,6 @@ import java.util.function.Consumer;
 import java.util.function.Supplier;
 
 import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLSocketFactory;
 
 import org.apache.camel.CamelContext;
@@ -158,7 +157,7 @@ public final class HashicorpVaultClient implements 
Closeable {
         endpoint.setPort(Integer.parseInt(settings.getPort()));
         endpoint.setScheme(settings.getScheme());
 
-        SimpleClientHttpRequestFactory requestFactory = 
requestFactory(HashicorpVaultTls.sslContext(settings, camelContext));
+        SimpleClientHttpRequestFactory requestFactory = 
requestFactory(socketFactories(settings, camelContext));
         VaultClient client = vaultClient(endpoint, requestFactory, null);
         // on HashiCorp Cloud the login methods are in the namespace, while 
Camel reads the secrets with the namespace in
         // their path: so only the login, and the renewal and revocation of 
its token, are sent to the namespace
@@ -416,24 +415,39 @@ public final class HashicorpVaultClient implements 
Closeable {
         return () -> content.get().trim();
     }
 
+    /**
+     * The TLS socket factories of the settings: of their 
sslContextParameters, created once, or of their trust store
+     * and key store, read again when one of their files changes; null when 
none is set, for the TLS of the JVM
+     */
+    private static Supplier<SSLSocketFactory> socketFactories(
+            HashicorpVaultClientSettings settings, CamelContext camelContext) {
+        if (settings.getSslContextParameters() != null) {
+            SSLSocketFactory socketFactory = 
HashicorpVaultTls.sslContext(settings, camelContext).getSocketFactory();
+            return () -> socketFactory;
+        }
+        return HashicorpVaultTlsStores.of(settings);
+    }
+
     /**
      * The HTTP client that Spring Vault uses for a VaultTemplate of an 
endpoint, with the timeouts it applies by
      * default, so that no request to Vault (such as the revocation of the 
token on stop) waits forever, and with the
-     * TLS context of the trust store and key store when set.
+     * TLS context of sslContextParameters, or of the trust store and key 
store, when set.
+     *
+     * @param socketFactories the TLS socket factories, or null for the TLS of 
the JVM
      */
-    private static SimpleClientHttpRequestFactory requestFactory(SSLContext 
sslContext) {
+    private static SimpleClientHttpRequestFactory 
requestFactory(Supplier<SSLSocketFactory> socketFactories) {
         SimpleClientHttpRequestFactory requestFactory;
-        if (sslContext == null) {
+        if (socketFactories == null) {
             requestFactory = new SimpleClientHttpRequestFactory();
         } else {
-            // one socket factory for all connections, which the JDK then 
keeps alive and reuses
-            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
             requestFactory = new SimpleClientHttpRequestFactory() {
                 @Override
                 protected void prepareConnection(HttpURLConnection connection, 
String httpMethod) throws IOException {
                     super.prepareConnection(connection, httpMethod);
                     if (connection instanceof HttpsURLConnection https) {
-                        https.setSSLSocketFactory(socketFactory);
+                        // the same socket factory for all connections, which 
the JDK keeps alive and reuses, until the
+                        // files of the stores change: the next connection is 
then a new one, with the new stores
+                        https.setSSLSocketFactory(socketFactories.get());
                     }
                 }
             };
diff --git 
a/components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultTlsStores.java
 
b/components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultTlsStores.java
new file mode 100644
index 000000000000..4d3050ce1492
--- /dev/null
+++ 
b/components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultTlsStores.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.hashicorp.vault;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.function.Supplier;
+
+import javax.net.ssl.SSLSocketFactory;
+
+import org.apache.camel.util.ObjectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * The TLS socket factory of the trust store and the key store of HashiCorp 
Vault, which reads the stores again when one
+ * of their files changes, such as a client certificate renewed before it 
expires. The client then makes its next
+ * connection with the new stores, since the JDK keeps connections alive per 
socket factory. A store that cannot be read
+ * when its file changes, such as a file being written, leaves the previous 
stores in use until its file changes again.
+ */
+final class HashicorpVaultTlsStores implements Supplier<SSLSocketFactory> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(HashicorpVaultTlsStores.class);
+
+    // the stores only, so that a change to the settings of the client after 
its creation does not apply
+    private final HashicorpVaultClientSettings stores;
+    private volatile Loaded current;
+    // the files of a reload that failed, which are not read again until they 
change again
+    private StoreFiles failed;
+
+    private HashicorpVaultTlsStores(HashicorpVaultClientSettings stores, 
Loaded current) {
+        this.stores = stores;
+        this.current = current;
+    }
+
+    /**
+     * The socket factory of the trust store and key store of the settings, or 
null when neither is set, so that the
+     * client trusts the server as any other TLS connection of the JVM.
+     *
+     * @throws IllegalArgumentException when a store cannot be read
+     */
+    static HashicorpVaultTlsStores of(HashicorpVaultClientSettings settings) {
+        if (ObjectHelper.isEmpty(settings.getTrustStore()) && 
ObjectHelper.isEmpty(settings.getKeyStore())) {
+            return null;
+        }
+        HashicorpVaultClientSettings stores = new 
HashicorpVaultClientSettings();
+        stores.setTrustStore(settings.getTrustStore());
+        stores.setTrustStorePassword(settings.getTrustStorePassword());
+        stores.setKeyStore(settings.getKeyStore());
+        stores.setKeyStorePassword(settings.getKeyStorePassword());
+        StoreFiles files = StoreFiles.of(stores);
+        return new HashicorpVaultTlsStores(
+                stores, new Loaded(files, HashicorpVaultTls.sslContext(stores, 
null).getSocketFactory()));
+    }
+
+    /**
+     * The socket factory of the stores, read again first when one of their 
files changed
+     */
+    @Override
+    public SSLSocketFactory get() {
+        Loaded loaded = current;
+        StoreFiles files = StoreFiles.of(stores);
+        if (files.equals(loaded.files())) {
+            return loaded.socketFactory();
+        }
+        synchronized (this) {
+            if (!files.equals(current.files()) && !files.equals(failed)) {
+                try {
+                    current = new Loaded(files, 
HashicorpVaultTls.sslContext(stores, null).getSocketFactory());
+                    failed = null;
+                    LOG.info("Read again the TLS trust store and key store of 
HashiCorp Vault, whose files changed");
+                } catch (RuntimeException e) {
+                    // any failure to read a store keeps the previous ones, as 
documented
+                    failed = files;
+                    LOG.warn("Cannot read again the TLS trust store and key 
store of HashiCorp Vault, whose files changed: {}."
+                             + " The previous ones are used until the files 
change again.",
+                            e.getMessage(), e);
+                }
+            }
+            return current.socketFactory();
+        }
+    }
+
+    private record Loaded(StoreFiles files, SSLSocketFactory socketFactory) {
+    }
+
+    /**
+     * The state of the files of the trust store and the key store, to tell 
when one changes
+     */
+    private record StoreFiles(FileState trustStore, FileState keyStore) {
+
+        static StoreFiles of(HashicorpVaultClientSettings stores) {
+            return new StoreFiles(FileState.of(stores.getTrustStore()), 
FileState.of(stores.getKeyStore()));
+        }
+    }
+
+    /**
+     * The modification time, size and identity of a file: a file replaced by 
another one, such as a mounted secret of
+     * Kubernetes, has another identity
+     */
+    private record FileState(FileTime lastModified, long size, Object fileKey) 
{
+
+        static FileState of(String file) {
+            if (ObjectHelper.isEmpty(file)) {
+                return null;
+            }
+            try {
+                BasicFileAttributes attributes = 
Files.readAttributes(Path.of(file), BasicFileAttributes.class);
+                return new FileState(attributes.lastModifiedTime(), 
attributes.size(), attributes.fileKey());
+            } catch (IOException e) {
+                // a file that cannot be read for now, such as one being 
replaced: as a changed file, read once it is back
+                return new FileState(null, -1, null);
+            }
+        }
+    }
+}
diff --git 
a/components/camel-hashicorp-vault/src/test/java/org/apache/camel/component/hashicorp/vault/FakeVault.java
 
b/components/camel-hashicorp-vault/src/test/java/org/apache/camel/component/hashicorp/vault/FakeVault.java
index 09e4796da2bc..5d9ae0b7a0fc 100644
--- 
a/components/camel-hashicorp-vault/src/test/java/org/apache/camel/component/hashicorp/vault/FakeVault.java
+++ 
b/components/camel-hashicorp-vault/src/test/java/org/apache/camel/component/hashicorp/vault/FakeVault.java
@@ -18,14 +18,17 @@ package org.apache.camel.component.hashicorp.vault;
 
 import java.io.File;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.InetSocketAddress;
 import java.net.URISyntaxException;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.nio.file.Path;
 import java.security.GeneralSecurityException;
 import java.security.KeyStore;
 import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import java.util.List;
 import java.util.Map;
@@ -107,14 +110,21 @@ final class FakeVault implements AutoCloseable {
 
     /**
      * A fake Vault over HTTPS, with the certificate of localhost 
(tls/server.p12) signed by the test CA (tls/ca.pem),
-     * which trusts the client certificates of the test CA.
+     * which trusts the client certificates of the test CA, and the 
self-signed client certificates of the given PEM
+     * files of tls/.
      */
-    static FakeVault https() throws IOException, GeneralSecurityException {
+    static FakeVault https(String... trustedClientCertificates) throws 
IOException, GeneralSecurityException {
         char[] password = "changeit".toCharArray();
         KeyManagerFactory keys = 
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
         keys.init(KeyStore.getInstance(new File(tlsFile("server.p12")), 
password), password);
+        KeyStore trusted = KeyStore.getInstance(new 
File(tlsFile("truststore.p12")), password);
+        for (String name : trustedClientCertificates) {
+            try (InputStream pem = 
Files.newInputStream(Path.of(tlsFile(name)))) {
+                trusted.setCertificateEntry(name, 
CertificateFactory.getInstance("X.509").generateCertificate(pem));
+            }
+        }
         TrustManagerFactory trust = 
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
-        trust.init(KeyStore.getInstance(new File(tlsFile("truststore.p12")), 
password));
+        trust.init(trusted);
         SSLContext tls = SSLContext.getInstance("TLS");
         tls.init(keys.getKeyManagers(), trust.getTrustManagers(), null);
         return new FakeVault(tls);
diff --git 
a/components/camel-hashicorp-vault/src/test/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultTlsStoresTest.java
 
b/components/camel-hashicorp-vault/src/test/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultTlsStoresTest.java
new file mode 100644
index 000000000000..75912ddba233
--- /dev/null
+++ 
b/components/camel-hashicorp-vault/src/test/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultTlsStoresTest.java
@@ -0,0 +1,174 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.hashicorp.vault;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.FileTime;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+
+import javax.net.ssl.SSLHandshakeException;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.component.hashicorp.vault.FakeVault.Request;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.vault.support.VaultResponse;
+
+import static org.apache.camel.component.hashicorp.vault.FakeVault.tlsFile;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The client reads its trust store and key store again when their files 
change, against a fake Vault over HTTPS. The
+ * stores are copies of the test material of tls/ (see HashicorpVaultTlsTest), 
replaced while the client runs.
+ */
+class HashicorpVaultTlsStoresTest {
+
+    @TempDir
+    Path dir;
+
+    private FakeVault vault;
+    private CamelContext context;
+    private HashicorpVaultClient client;
+    private int changes;
+
+    @BeforeEach
+    void startContext() {
+        context = new DefaultCamelContext();
+        context.start();
+    }
+
+    @AfterEach
+    void stopVault() {
+        if (client != null) {
+            client.close();
+        }
+        context.stop();
+        vault.close();
+    }
+
+    @Test
+    void readsTheTrustStoreAgainWhenItsFileChanges() throws Exception {
+        startVault();
+        Path trustStore = copy("ca.pem");
+        HashicorpVaultClientSettings settings = token();
+        settings.setTrustStore(trustStore.toString());
+        client = HashicorpVaultClient.create(context, this, settings);
+        assertEquals("pw", readPassword());
+
+        // a trust store without the test CA: the next connection no longer 
trusts Vault
+        replace(trustStore, "client-ec.pem");
+        Exception e = assertThrows(Exception.class, this::readPassword);
+        assertTrue(hasCause(e, SSLHandshakeException.class), "Vault is no 
longer trusted: " + e);
+
+        replace(trustStore, "ca.pem");
+        assertEquals("pw", readPassword());
+    }
+
+    @Test
+    void presentsTheClientCertificateOfTheKeyStoreOnceItsFileChanges() throws 
Exception {
+        startVault("client-ec.pem");
+        vault.on("auth/cert/login", request -> FakeVault.login("cert-token", 
3600));
+        Path keyStore = copy("client.pem");
+        HashicorpVaultClientSettings settings = token();
+        settings.setToken(null);
+        settings.setAuthentication("cert");
+        settings.setTrustStore(tlsFile("ca.pem"));
+        settings.setKeyStore(keyStore.toString());
+        client = HashicorpVaultClient.create(context, this, settings);
+        assertEquals("pw", readPassword());
+        assertEquals("CN=camel-client", 
vault.requests("auth/cert/login").get(0).clientCertificate());
+
+        // the client certificate renewed in its file, such as by the Vault 
agent
+        replace(keyStore, "client-ec.pem");
+        assertEquals("pw", readPassword());
+
+        List<Request> reads = vault.requests("secret/data/api");
+        assertEquals("CN=camel-client-ec", reads.get(reads.size() - 
1).clientCertificate());
+    }
+
+    @Test
+    void keepsTheStoresWhileTheChangedFileCannotBeRead() throws Exception {
+        startVault();
+        Path trustStore = copy("ca.pem");
+        HashicorpVaultClientSettings settings = token();
+        settings.setTrustStore(trustStore.toString());
+        client = HashicorpVaultClient.create(context, this, settings);
+        assertEquals("pw", readPassword());
+
+        // such as a file being written
+        Files.writeString(trustStore, "-----BEGIN CERTIFICATE-----");
+        touch(trustStore);
+        assertEquals("pw", readPassword(), "the previous trust store is kept");
+
+        // once the file changes again it is read again
+        replace(trustStore, "client-ec.pem");
+        assertThrows(Exception.class, this::readPassword);
+    }
+
+    private void startVault(String... trustedClientCertificates) throws 
Exception {
+        vault = FakeVault.https(trustedClientCertificates);
+        vault.on("secret/data/api", request -> FakeVault.secret("pw"));
+        vault.on("auth/token/revoke-self", request -> FakeVault.noContent());
+    }
+
+    private Path copy(String name) throws IOException {
+        return Files.copy(Path.of(tlsFile(name)), dir.resolve(name));
+    }
+
+    private void replace(Path file, String name) throws IOException {
+        Files.copy(Path.of(tlsFile(name)), file, 
StandardCopyOption.REPLACE_EXISTING);
+        touch(file);
+    }
+
+    // a new modification time, also on a file system that stores it to the 
second
+    private void touch(Path file) throws IOException {
+        Files.setLastModifiedTime(file, 
FileTime.from(Instant.now().plusSeconds(10L * ++changes)));
+    }
+
+    private HashicorpVaultClientSettings token() {
+        HashicorpVaultClientSettings settings = new 
HashicorpVaultClientSettings();
+        settings.setHost("localhost");
+        settings.setPort(String.valueOf(vault.port()));
+        settings.setScheme("https");
+        settings.setToken("my-token");
+        return settings;
+    }
+
+    private String readPassword() {
+        VaultResponse response = 
client.getVaultTemplate().read("secret/data/api");
+        return ((Map<?, ?>) 
response.getData().get("data")).get("password").toString();
+    }
+
+    private static boolean hasCause(Throwable e, Class<? extends Throwable> 
type) {
+        for (Throwable cause = e; cause != null; cause = cause.getCause()) {
+            if (type.isInstance(cause)) {
+                return true;
+            }
+        }
+        return false;
+    }
+}

Reply via email to