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 f6c0ae1f338e CAMEL-26835: Test SPIFFE rotation, trust updates and 
recovery (#29829)
f6c0ae1f338e is described below

commit f6c0ae1f338ed8d0edfd7176086c982fe4983b1d
Author: Andrea Cosentino <[email protected]>
AuthorDate: Mon Nov 16 22:54:38 2026 +0100

    CAMEL-26835: Test SPIFFE rotation, trust updates and recovery (#29829)
    
    Co-Authored-By: Claude Fable 5.1 <[email protected]>
    Co-authored-by: Codex <[email protected]>
---
 components/camel-spiffe/src/test/README.adoc       |  53 +++++++
 .../spiffe/integration/SpiffeMutualTlsIT.java      |   9 +-
 .../spiffe/integration/SpiffeRotationIT.java       | 167 +++++++++++++++++++++
 test-infra/camel-test-infra-spiffe/pom.xml         |   5 +
 .../services/SpiffeLocalContainerInfraService.java | 121 ++++++++++-----
 .../services/SpiffeRotationConfigurationTest.java  |  54 +++++++
 6 files changed, 368 insertions(+), 41 deletions(-)

diff --git a/components/camel-spiffe/src/test/README.adoc 
b/components/camel-spiffe/src/test/README.adoc
new file mode 100644
index 000000000000..42ac050b4636
--- /dev/null
+++ b/components/camel-spiffe/src/test/README.adoc
@@ -0,0 +1,53 @@
+////
+
+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.
+////
+
+= SPIFFE lifecycle integration tests
+
+The `SpiffeRotationIT` test needs a Linux Docker or Podman engine sharing the 
host kernel and PID namespace with the test JVM.
+Docker Desktop on macOS or Windows does not meet these requirements.
+The fixture retains the rootless UID translation and Workload API registration 
readiness checks used by the other SPIFFE integration tests.
+
+After building the required test-infra modules, run:
+
+[source,shell]
+----
+mvn -f components/camel-spiffe/pom.xml verify -DskipITs=false 
-Dit.test=SpiffeRotationIT
+----
+
+The test uses dedicated containers instead of the singleton service, so 
interrupting its agent cannot affect other tests.
+It requests 20-second workload SVIDs and a 120-second CA lifetime.
+SPIRE schedules CA rotation every ten seconds and guarantees an SVID lifetime 
of at most one sixth of the CA lifetime.
+The custom fixture persists the agent node key to allow the same agent process 
to restart with its existing attestation.
+The default shared fixture retains its one-hour SVID, 24-hour CA and in-memory 
key manager.
+
+The test performs fresh mutual TLS handshakes through the same client and 
server `SSLContext` objects.
+Every probe uses a new listening port and invalidates both TLS sessions to 
avoid session resumption masking certificate changes.
+It checks changed leaf serials, continued use of cached valid credentials 
during a short agent interruption,
+watcher recovery, and adoption of a newly published signing authority.
+The trust-bundle assertion requires a successful handshake whose peer leaf 
verifies against an added authority
+and against none of the original authorities; leaf rotation alone does not 
satisfy it.
+Delegating wrappers around real SDK sources verify that Camel stops both 
sources, then the test checks distinct
+SSLContexts and subsequent rotation after CamelContext restart.
+These wrappers preserve the real SDK callback state and perform no synthetic 
Workload API updates.
+
+Allow several minutes for this test.
+Leaf rotation, recovery and rotation after restart each have a 90-second 
Awaitility deadline;
+the trust-authority transition has a 180-second deadline.
+Each handshake has bounded socket and server-task timeouts.
+The test does not claim that an established TLS session revalidates after 
rotation,
+or exercise a prolonged outage beyond cached credential expiry or CA removal.
diff --git 
a/components/camel-spiffe/src/test/java/org/apache/camel/component/spiffe/integration/SpiffeMutualTlsIT.java
 
b/components/camel-spiffe/src/test/java/org/apache/camel/component/spiffe/integration/SpiffeMutualTlsIT.java
index 2fd11c24197e..a60873f773b8 100644
--- 
a/components/camel-spiffe/src/test/java/org/apache/camel/component/spiffe/integration/SpiffeMutualTlsIT.java
+++ 
b/components/camel-spiffe/src/test/java/org/apache/camel/component/spiffe/integration/SpiffeMutualTlsIT.java
@@ -20,6 +20,7 @@ import java.net.ConnectException;
 import java.net.InetAddress;
 import java.net.SocketException;
 import java.net.SocketTimeoutException;
+import java.security.cert.X509Certificate;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
@@ -106,7 +107,8 @@ class SpiffeMutualTlsIT extends CamelTestSupport {
      * present their SVID. Returns normally when the handshake and a one-byte 
exchange complete, and throws when either
      * side rejects the peer.
      */
-    private void handshake(SSLContext serverContext, SSLContext clientContext) 
throws Exception {
+    static X509Certificate handshake(SSLContext serverContext, SSLContext 
clientContext) throws Exception {
+        X509Certificate peerCertificate;
         ExecutorService executor = Executors.newSingleThreadExecutor();
         try (SSLServerSocket serverSocket = (SSLServerSocket) 
serverContext.getServerSocketFactory()
                 .createServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
@@ -120,6 +122,7 @@ class SpiffeMutualTlsIT extends CamelTestSupport {
                     accepted.setSoTimeout(15000);
                     accepted.startHandshake();
                     accepted.getInputStream().read();
+                    accepted.getSession().invalidate();
                 }
                 return null;
             });
@@ -129,6 +132,9 @@ class SpiffeMutualTlsIT extends CamelTestSupport {
                     .createSocket(InetAddress.getLoopbackAddress(), port)) {
                 clientSocket.setSoTimeout(15000);
                 clientSocket.startHandshake();
+                peerCertificate = (X509Certificate) 
clientSocket.getSession().getPeerCertificates()[0];
+                // A new port and invalidated sessions force a full handshake 
on every rotation probe.
+                clientSocket.getSession().invalidate();
                 clientSocket.getOutputStream().write(42);
                 clientSocket.getOutputStream().flush();
             }
@@ -142,6 +148,7 @@ class SpiffeMutualTlsIT extends CamelTestSupport {
                 }
                 throw e;
             }
+            return peerCertificate;
         } finally {
             executor.shutdownNow();
         }
diff --git 
a/components/camel-spiffe/src/test/java/org/apache/camel/component/spiffe/integration/SpiffeRotationIT.java
 
b/components/camel-spiffe/src/test/java/org/apache/camel/component/spiffe/integration/SpiffeRotationIT.java
new file mode 100644
index 000000000000..cd607604cb3c
--- /dev/null
+++ 
b/components/camel-spiffe/src/test/java/org/apache/camel/component/spiffe/integration/SpiffeRotationIT.java
@@ -0,0 +1,167 @@
+/*
+ * 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.spiffe.integration;
+
+import java.security.GeneralSecurityException;
+import java.security.cert.X509Certificate;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.net.ssl.SSLContext;
+
+import io.spiffe.spiffeid.TrustDomain;
+import io.spiffe.workloadapi.DefaultX509Source;
+import io.spiffe.workloadapi.DefaultX509Source.X509SourceOptions;
+import io.spiffe.workloadapi.X509Source;
+import org.apache.camel.component.spiffe.SpiffeSSLContextParameters;
+import org.apache.camel.support.jsse.ClientAuthentication;
+import org.apache.camel.support.jsse.SSLContextServerParameters;
+import 
org.apache.camel.test.infra.spiffe.services.SpiffeLocalContainerInfraService;
+import org.apache.camel.test.infra.spiffe.services.SpiffeService;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledOnOs;
+import org.junit.jupiter.api.condition.OS;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.mockito.MockedStatic;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+import static org.mockito.AdditionalAnswers.delegatesTo;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.CALLS_REAL_METHODS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.verify;
+
+/** Dedicated containers: short TTLs and agent interruption must never affect 
the shared Workload API fixture. */
+@EnabledOnOs(OS.LINUX)
+class SpiffeRotationIT extends CamelTestSupport {
+
+    @RegisterExtension
+    static RotationService service = new RotationService();
+
+    static class RotationService extends SpiffeLocalContainerInfraService 
implements SpiffeService {
+        RotationService() {
+            // SPIRE guarantees SVID lifetime only up to CA TTL / 6. Its CA 
rotator ticks every ten seconds.
+            super(Duration.ofSeconds(20), Duration.ofSeconds(120));
+        }
+    }
+
+    @Test
+    void rotatesRecoversAndRecreatesSources() throws Exception {
+        List<DefaultX509Source> sources = new ArrayList<>();
+        try (MockedStatic<DefaultX509Source> factory = 
mockStatic(DefaultX509Source.class, CALLS_REAL_METHODS)) {
+            factory.when(() -> 
DefaultX509Source.newSource(any(X509SourceOptions.class))).thenAnswer(invocation
 -> {
+                DefaultX509Source realSource = (DefaultX509Source) 
invocation.callRealMethod();
+                // Delegate rather than spy: SDK callbacks update the original 
source snapshot asynchronously.
+                DefaultX509Source source = mock(DefaultX509Source.class, 
delegatesTo(realSource));
+                sources.add(source);
+                return source;
+            });
+            SpiffeSSLContextParameters serverParameters = parameters(true);
+            SpiffeSSLContextParameters clientParameters = parameters(false);
+            SSLContext server = serverParameters.createSSLContext(context);
+            SSLContext client = clientParameters.createSSLContext(context);
+            try (X509Source observer = 
DefaultX509Source.newSource(X509SourceOptions.builder()
+                    
.spiffeSocketPath(service.getWorkloadApiSocketPath()).initTimeout(Duration.ofSeconds(20)).build()))
 {
+                Set<X509Certificate> originalAuthorities = 
authorities(observer);
+                X509Certificate first = SpiffeMutualTlsIT.handshake(server, 
client);
+
+                await().alias("leaf rotation on existing 
SSLContexts").atMost(Duration.ofSeconds(90))
+                        .pollInterval(Duration.ofSeconds(1)).untilAsserted(() 
-> {
+                            X509Certificate rotated = 
SpiffeMutualTlsIT.handshake(server, client);
+                            
assertThat(rotated.getSerialNumber()).isNotEqualTo(first.getSerialNumber());
+                        });
+
+                // Stop/start the process, preserving its node key and data. 
Cached, still-valid credentials can complete
+                // fresh handshakes during disconnection; this does not assert 
that an already-open TLS session revalidates.
+                service.stopAgent();
+                try {
+                    assertThat(SpiffeMutualTlsIT.handshake(server, 
client)).isNotNull();
+                } finally {
+                    service.startAgent();
+                }
+                X509Certificate beforeRecovery = 
SpiffeMutualTlsIT.handshake(server, client);
+                await().alias("watcher reconnect and fresh SVID after agent 
restart").atMost(Duration.ofSeconds(90))
+                        .pollInterval(Duration.ofSeconds(1)).untilAsserted(() 
-> {
+                            assertThat(SpiffeMutualTlsIT.handshake(server, 
client).getSerialNumber())
+                                    
.isNotEqualTo(beforeRecovery.getSerialNumber());
+                        });
+
+                // A changed CA certificate alone is insufficient: the peer 
leaf must verify with a newly published CA
+                // and fail verification against every original CA, while the 
original SSLContext still trusts it.
+                await().alias("new trust authority published and used in fresh 
TLS handshakes")
+                        
.atMost(Duration.ofSeconds(180)).pollInterval(Duration.ofSeconds(1)).untilAsserted(()
 -> {
+                            Set<X509Certificate> added = authorities(observer);
+                            added.removeAll(originalAuthorities);
+                            assertThat(added).isNotEmpty();
+                            X509Certificate peer = 
SpiffeMutualTlsIT.handshake(server, client);
+                            assertThat(added.stream().anyMatch(authority -> 
signedBy(peer, authority))).isTrue();
+                            
assertThat(originalAuthorities.stream().noneMatch(authority -> signedBy(peer, 
authority))).isTrue();
+                        });
+
+                context.stop();
+                verify(sources.get(0)).close();
+                verify(sources.get(1)).close();
+                context.start();
+                SSLContext restartedServer = 
serverParameters.createSSLContext(context);
+                SSLContext restartedClient = 
clientParameters.createSSLContext(context);
+                assertThat(restartedServer).isNotSameAs(server);
+                assertThat(restartedClient).isNotSameAs(client);
+                assertThat(sources).hasSize(5);
+                assertThat(SpiffeMutualTlsIT.handshake(restartedServer, 
restartedClient)).isNotNull();
+                X509Certificate restartedLeaf = 
SpiffeMutualTlsIT.handshake(restartedServer, restartedClient);
+                await().alias("recreated source continues observing 
rotation").atMost(Duration.ofSeconds(90))
+                        .pollInterval(Duration.ofSeconds(1)).untilAsserted(() 
-> {
+                            
assertThat(SpiffeMutualTlsIT.handshake(restartedServer, 
restartedClient).getSerialNumber())
+                                    
.isNotEqualTo(restartedLeaf.getSerialNumber());
+                        });
+            }
+        }
+    }
+
+    private static Set<X509Certificate> authorities(X509Source source) throws 
Exception {
+        return new HashSet<>(
+                
source.getBundleForTrustDomain(TrustDomain.parse(service.getTrustDomain()))
+                        .getX509Authorities());
+    }
+
+    private static boolean signedBy(X509Certificate leaf, X509Certificate 
authority) {
+        try {
+            leaf.verify(authority.getPublicKey());
+            return true;
+        } catch (GeneralSecurityException e) {
+            return false;
+        }
+    }
+
+    private static SpiffeSSLContextParameters parameters(boolean server) {
+        SpiffeSSLContextParameters parameters = new 
SpiffeSSLContextParameters();
+        parameters.setSpiffeSocketPath(service.getWorkloadApiSocketPath());
+        parameters.setAcceptedSpiffeIds(service.getWorkloadSpiffeId());
+        if (server) {
+            SSLContextServerParameters configuration = new 
SSLContextServerParameters();
+            
configuration.setClientAuthentication(ClientAuthentication.REQUIRE.name());
+            parameters.setServerParameters(configuration);
+        }
+        return parameters;
+    }
+}
diff --git a/test-infra/camel-test-infra-spiffe/pom.xml 
b/test-infra/camel-test-infra-spiffe/pom.xml
index 0c7c28a24b5b..7d7968567d32 100644
--- a/test-infra/camel-test-infra-spiffe/pom.xml
+++ b/test-infra/camel-test-infra-spiffe/pom.xml
@@ -31,6 +31,11 @@
     <name>Camel :: Test Infra :: SPIFFE</name>
 
     <dependencies>
+        <dependency>
+            <groupId>org.awaitility</groupId>
+            <artifactId>awaitility</artifactId>
+            <version>${awaitility-version}</version>
+        </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-test-infra-common</artifactId>
diff --git 
a/test-infra/camel-test-infra-spiffe/src/main/java/org/apache/camel/test/infra/spiffe/services/SpiffeLocalContainerInfraService.java
 
b/test-infra/camel-test-infra-spiffe/src/main/java/org/apache/camel/test/infra/spiffe/services/SpiffeLocalContainerInfraService.java
index 1e277f2ee554..317d214c4a45 100644
--- 
a/test-infra/camel-test-infra-spiffe/src/main/java/org/apache/camel/test/infra/spiffe/services/SpiffeLocalContainerInfraService.java
+++ 
b/test-infra/camel-test-infra-spiffe/src/main/java/org/apache/camel/test/infra/spiffe/services/SpiffeLocalContainerInfraService.java
@@ -17,6 +17,7 @@
 package org.apache.camel.test.infra.spiffe.services;
 
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.time.Duration;
@@ -38,7 +39,9 @@ import org.testcontainers.containers.Network;
 import org.testcontainers.containers.SelinuxContext;
 import 
org.testcontainers.containers.startupcheck.IsRunningStartupCheckStrategy;
 import org.testcontainers.containers.wait.strategy.Wait;
-import org.testcontainers.utility.MountableFile;
+import org.testcontainers.images.builder.Transferable;
+
+import static org.awaitility.Awaitility.await;
 
 /**
  * Runs a SPIRE server and agent so a test can fetch SVIDs from a real 
Workload API.
@@ -78,9 +81,14 @@ public class SpiffeLocalContainerInfraService implements 
SpiffeInfraService, Con
     private static final String SOCKET_FILE = "api.sock";
     private static final String SERVER_CONF_RESOURCE = 
"org/apache/camel/test/infra/spiffe/services/spire-server.conf";
     private static final String AGENT_CONF_RESOURCE = 
"org/apache/camel/test/infra/spiffe/services/spire-agent.conf";
+    /** The lifetimes of the stock SPIRE configuration, which keeps the 
in-memory KeyManager. */
+    static final Duration DEFAULT_WORKLOAD_SVID_TTL = Duration.ofHours(1);
+    static final Duration DEFAULT_CA_TTL = Duration.ofHours(24);
 
     private final String serverImage;
     private final String agentImage;
+    private final Duration workloadSvidTtl;
+    private final Duration caTtl;
 
     private Network network;
     private GenericContainer<?> server;
@@ -89,13 +97,31 @@ public class SpiffeLocalContainerInfraService implements 
SpiffeInfraService, Con
     private String socketPath;
 
     public SpiffeLocalContainerInfraService() {
+        this(DEFAULT_WORKLOAD_SVID_TTL, DEFAULT_CA_TTL);
+    }
+
+    /** Uses a shorter registration TTL for rotation tests without changing 
the shared fixture defaults. */
+    public SpiffeLocalContainerInfraService(Duration workloadSvidTtl, Duration 
caTtl) {
         
this(LocalPropertyResolver.getProperty(SpiffeLocalContainerInfraService.class,
                 SpiffeProperties.SPIFFE_SERVER_CONTAINER),
              
LocalPropertyResolver.getProperty(SpiffeLocalContainerInfraService.class,
-                     SpiffeProperties.SPIFFE_AGENT_CONTAINER));
+                     SpiffeProperties.SPIFFE_AGENT_CONTAINER),
+             workloadSvidTtl, caTtl);
     }
 
     public SpiffeLocalContainerInfraService(String serverImage, String 
agentImage) {
+        this(serverImage, agentImage, DEFAULT_WORKLOAD_SVID_TTL, 
DEFAULT_CA_TTL);
+    }
+
+    public SpiffeLocalContainerInfraService(String serverImage, String 
agentImage, Duration workloadSvidTtl, Duration caTtl) {
+        if (workloadSvidTtl == null || workloadSvidTtl.getSeconds() < 1) {
+            throw new IllegalArgumentException("Workload SVID TTL must be at 
least one second");
+        }
+        if (caTtl == null || caTtl.compareTo(workloadSvidTtl.multipliedBy(6)) 
< 0) {
+            throw new IllegalArgumentException("CA TTL must be at least six 
times the workload SVID TTL");
+        }
+        this.caTtl = caTtl;
+        this.workloadSvidTtl = workloadSvidTtl;
         this.serverImage = serverImage;
         this.agentImage = agentImage;
     }
@@ -122,7 +148,7 @@ public class SpiffeLocalContainerInfraService implements 
SpiffeInfraService, Con
         server = new GenericContainer<>(serverImage)
                 .withNetwork(network)
                 .withNetworkAliases(SERVER_ALIAS)
-                
.withCopyFileToContainer(MountableFile.forClasspathResource(SERVER_CONF_RESOURCE),
 SERVER_CONF)
+                .withCopyToContainer(Transferable.of(serverConfiguration()), 
SERVER_CONF)
                 .withExposedPorts(SERVER_PORT)
                 .withCommand("-config", SERVER_CONF)
                 .waitingFor(Wait.forListeningPort());
@@ -136,7 +162,7 @@ public class SpiffeLocalContainerInfraService implements 
SpiffeInfraService, Con
         // the socket directory bind-mounted (SELinux-shared) so the host can 
reach the Workload API socket it creates
         agent = new GenericContainer<>(agentImage)
                 .withNetwork(network)
-                
.withCopyFileToContainer(MountableFile.forClasspathResource(AGENT_CONF_RESOURCE),
 AGENT_CONF)
+                .withCopyToContainer(Transferable.of(agentConfiguration()), 
AGENT_CONF)
                 .withCreateContainerCmdModifier(cmd -> 
cmd.getHostConfig().withPidMode("host"))
                 .withStartupCheckStrategy(new IsRunningStartupCheckStrategy())
                 .withCommand("-config", AGENT_CONF, "-joinToken", joinToken);
@@ -155,6 +181,51 @@ public class SpiffeLocalContainerInfraService implements 
SpiffeInfraService, Con
         LOG.info("SPIRE Workload API available at {}", socketPath);
     }
 
+    String agentConfiguration() {
+        try (var input = 
getClass().getClassLoader().getResourceAsStream(AGENT_CONF_RESOURCE)) {
+            if (input == null) {
+                throw new IllegalStateException("Missing SPIRE agent 
configuration");
+            }
+            // Restarting a process must retain its node key, rather than try 
to reuse a consumed join token.
+            String configuration = new String(input.readAllBytes(), 
StandardCharsets.UTF_8);
+            if (workloadSvidTtl.equals(DEFAULT_WORKLOAD_SVID_TTL) && 
caTtl.equals(DEFAULT_CA_TTL)) {
+                return configuration;
+            }
+            return configuration
+                    .replace("KeyManager \"memory\" {\n        plugin_data {}",
+                            "KeyManager \"disk\" {\n        plugin_data { 
directory = \"/tmp/spire-agent/keys\" }");
+        } catch (IOException e) {
+            throw new RuntimeException("Could not read SPIRE agent 
configuration", e);
+        }
+    }
+
+    String serverConfiguration() {
+        try (var input = 
getClass().getClassLoader().getResourceAsStream(SERVER_CONF_RESOURCE)) {
+            if (input == null) {
+                throw new IllegalStateException("Missing SPIRE server 
configuration");
+            }
+            return new String(input.readAllBytes(), StandardCharsets.UTF_8)
+                    .replace("ca_ttl = \"24h\"", "ca_ttl = \"" + 
caTtl.getSeconds() + "s\"")
+                    .replace("default_x509_svid_ttl = \"1h\"",
+                            "default_x509_svid_ttl = \"" + 
workloadSvidTtl.getSeconds() + "s\"");
+        } catch (IOException e) {
+            throw new RuntimeException("Could not read SPIRE server 
configuration", e);
+        }
+    }
+
+    /**
+     * Stops the existing container without removing its data. Use the 
custom-TTL fixture, which persists the node key,
+     * when restarting: the default in-memory key manager cannot recover a 
consumed join token.
+     */
+    public void stopAgent() {
+        
agent.getDockerClient().stopContainerCmd(agent.getContainerId()).withTimeout(10).exec();
+    }
+
+    /** Restarts the same agent, retaining its node attestation and Workload 
API socket location. */
+    public void startAgent() {
+        
agent.getDockerClient().startContainerCmd(agent.getContainerId()).exec();
+    }
+
     private void createHostSocketDir() {
         try {
             // keep the socket path short (AF_UNIX sun_path is limited to ~108 
bytes); /tmp keeps it well within that
@@ -171,24 +242,9 @@ public class SpiffeLocalContainerInfraService implements 
SpiffeInfraService, Con
     }
 
     private void waitForServerHealthy() {
-        long deadline = System.currentTimeMillis() + 
Duration.ofSeconds(30).toMillis();
-        RuntimeException last = null;
-        while (System.currentTimeMillis() < deadline) {
-            try {
-                Container.ExecResult result = 
server.execInContainer(SERVER_BIN, "healthcheck");
-                if (result.getExitCode() == 0) {
-                    return;
-                }
-                last = new RuntimeException("healthcheck exit " + 
result.getExitCode() + ": " + result.getStderr());
-            } catch (IOException e) {
-                last = new RuntimeException(e);
-            } catch (InterruptedException e) {
-                Thread.currentThread().interrupt();
-                throw new RuntimeException(e);
-            }
-            sleep(500);
-        }
-        throw new RuntimeException("SPIRE server did not become healthy in 
time", last);
+        await().alias("SPIRE server 
healthcheck").atMost(Duration.ofSeconds(30))
+                
.pollInterval(Duration.ofMillis(500)).ignoreException(IOException.class)
+                .until(() -> server.execInContainer(SERVER_BIN, 
"healthcheck").getExitCode() == 0);
     }
 
     private String generateJoinToken() {
@@ -205,7 +261,7 @@ public class SpiffeLocalContainerInfraService implements 
SpiffeInfraService, Con
     private void createWorkloadEntry(long uid) {
         LOG.info("Registering {} for the selector unix:uid:{}", 
WORKLOAD_SPIFFE_ID, uid);
         exec(server, SERVER_BIN, "entry", "create", "-parentID", 
AGENT_SPIFFE_ID, "-spiffeID", WORKLOAD_SPIFFE_ID,
-                "-selector", "unix:uid:" + uid);
+                "-selector", "unix:uid:" + uid, "-x509SVIDTTL", 
Long.toString(workloadSvidTtl.getSeconds()));
     }
 
     /**
@@ -266,14 +322,8 @@ public class SpiffeLocalContainerInfraService implements 
SpiffeInfraService, Con
 
     private void waitForSocket() {
         Path socket = hostSocketDir.resolve(SOCKET_FILE);
-        long deadline = System.currentTimeMillis() + 
Duration.ofSeconds(60).toMillis();
-        while (System.currentTimeMillis() < deadline) {
-            if (Files.exists(socket)) {
-                return;
-            }
-            sleep(250);
-        }
-        throw new RuntimeException("The SPIRE agent did not create the 
Workload API socket at " + socket);
+        await().alias("SPIRE Workload API socket " + 
socket).atMost(Duration.ofSeconds(60))
+                .pollInterval(Duration.ofMillis(250)).until(() -> 
Files.exists(socket));
     }
 
     private Container.ExecResult exec(GenericContainer<?> container, String... 
command) {
@@ -293,15 +343,6 @@ public class SpiffeLocalContainerInfraService implements 
SpiffeInfraService, Con
         }
     }
 
-    private static void sleep(long millis) {
-        try {
-            Thread.sleep(millis);
-        } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            throw new RuntimeException(e);
-        }
-    }
-
     @Override
     public void registerProperties() {
         System.setProperty(SpiffeProperties.SPIFFE_SOCKET_PATH, socketPath);
diff --git 
a/test-infra/camel-test-infra-spiffe/src/test/java/org/apache/camel/test/infra/spiffe/services/SpiffeRotationConfigurationTest.java
 
b/test-infra/camel-test-infra-spiffe/src/test/java/org/apache/camel/test/infra/spiffe/services/SpiffeRotationConfigurationTest.java
new file mode 100644
index 000000000000..542e4da506be
--- /dev/null
+++ 
b/test-infra/camel-test-infra-spiffe/src/test/java/org/apache/camel/test/infra/spiffe/services/SpiffeRotationConfigurationTest.java
@@ -0,0 +1,54 @@
+/*
+ * 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.test.infra.spiffe.services;
+
+import java.time.Duration;
+
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static 
org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+
+class SpiffeRotationConfigurationTest {
+
+    @Test
+    void retainsDefaultLifetimesAndKeyManager() {
+        var service = new SpiffeLocalContainerInfraService("server", "agent");
+        assertThat(service.serverConfiguration()).contains("ca_ttl = 
\"86400s\"",
+                "default_x509_svid_ttl = \"3600s\"");
+        assertThat(service.agentConfiguration()).contains("KeyManager 
\"memory\"").doesNotContain("KeyManager \"disk\"");
+    }
+
+    @Test
+    void configuresRotationAndPersistentAgentKey() {
+        var service = new SpiffeLocalContainerInfraService("server", "agent", 
Duration.ofSeconds(20), Duration.ofSeconds(120));
+        assertThat(service.serverConfiguration()).contains("ca_ttl = \"120s\"",
+                "default_x509_svid_ttl = \"20s\"");
+        assertThat(service.agentConfiguration()).contains("KeyManager 
\"disk\"",
+                "directory = 
\"/tmp/spire-agent/keys\"").doesNotContain("KeyManager \"memory\"");
+    }
+
+    @Test
+    void rejectsLifetimesThatCannotBeGuaranteed() {
+        assertThatIllegalArgumentException().isThrownBy(() -> new 
SpiffeLocalContainerInfraService(
+                "server", "agent",
+                Duration.ofSeconds(20), Duration.ofSeconds(119)));
+        assertThatIllegalArgumentException().isThrownBy(() -> new 
SpiffeLocalContainerInfraService(
+                "server", "agent",
+                Duration.ZERO, Duration.ofSeconds(120)));
+    }
+}

Reply via email to