diff --git a/src/adapter/outbound/persistence-mongo/src/mongoIntegrationTest/java/dev/caskeleton/adapter/outbound/mongo/security/MongoTlsLaneTest.java b/src/adapter/outbound/persistence-mongo/src/mongoIntegrationTest/java/dev/caskeleton/adapter/outbound/mongo/security/MongoTlsLaneTest.java index 90fce06a..4cbcc70c 100644 --- a/src/adapter/outbound/persistence-mongo/src/mongoIntegrationTest/java/dev/caskeleton/adapter/outbound/mongo/security/MongoTlsLaneTest.java +++ b/src/adapter/outbound/persistence-mongo/src/mongoIntegrationTest/java/dev/caskeleton/adapter/outbound/mongo/security/MongoTlsLaneTest.java @@ -1,20 +1,37 @@ package dev.caskeleton.adapter.outbound.mongo.security; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.mongodb.ConnectionString; import com.mongodb.MongoClientSettings; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; +import com.mongodb.connection.ServerConnectionState; +import com.mongodb.event.ServerDescriptionChangedEvent; +import com.mongodb.event.ServerHeartbeatFailedEvent; +import com.mongodb.event.ServerListener; +import com.mongodb.event.ServerMonitorListener; import dev.caskeleton.adapter.outbound.mongo.testkit.rs.MongoTlsReplicaSetContainer; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.security.KeyStore; +import java.security.cert.CertPathBuilderException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; +import org.assertj.core.api.InstanceOfAssertFactories; import org.bson.Document; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; @@ -30,12 +47,26 @@ import org.junit.jupiter.api.Test; * *
The three negative cases are the three ways a certificate goes wrong in practice: signed by an
* authority the client does not trust, naming a host other than the one being reached, and past its
- * validity window. Each needs its own server, because each is a property of what the server
- * presents.
+ * validity window. Each runs against its own server. Each is judged by the client's first handshake
+ * and the certificate failure it carries, not by a command that waits out the server-selection
+ * timeout: that wait is the same ten seconds for a refused certificate as for a server that is not
+ * there.
*/
@Tag("mongodb-security-integration")
class MongoTlsLaneTest {
+ /**
+ * The longest a handshake may take to be decided, and the ping client's server-selection timeout:
+ * a bound, not the expected wait.
+ */
+ private static final Duration HANDSHAKE_BOUND = Duration.ofSeconds(10);
+
+ /** How soon the monitor retries an attempt that ended before the certificate was judged. */
+ private static final Duration RETRY_INTERVAL = Duration.ofMillis(500);
+
+ /** How long the expiry poll waits between fresh clients. */
+ private static final Duration EXPIRY_POLL = Duration.ofSeconds(1);
+
@Test
@DisplayName("a client trusting the server's authority connects")
void aTrustedAuthorityConnects() {
@@ -51,41 +82,54 @@ class MongoTlsLaneTest {
}
@Test
- @DisplayName("a client trusting a different authority is refused")
- void anUntrustedAuthorityIsRefused() {
- try (MongoTlsReplicaSetContainer server = MongoTlsReplicaSetContainer.trusted();
- MongoTlsReplicaSetContainer other = MongoTlsReplicaSetContainer.trusted()) {
+ @DisplayName("다른 CA만 믿는 client는 첫 handshake에서 PKIX 경로를 못 만들어 거절된다")
+ void anUntrustedAuthorityIsRefused() throws InterruptedException {
+ try (MongoTlsReplicaSetContainer server = MongoTlsReplicaSetContainer.trusted()) {
+ // given
server.start();
- other.start();
+ // An authority under another name. One under the same name with another key is a different
+ // refusal (the path is built and fails its signature check), and this test does not stage it.
+ String unrelatedAuthority = server.unrelatedAuthorityPem();
- // A real authority, generated by the same script, that simply did not sign this server's
- // certificate — which is what a rotated or swapped CA looks like from the client side.
- try (MongoClient client =
- clientFor(server.connectionString(server.host()), other.certificateAuthorityPem())) {
- assertThatThrownBy(() -> client.getDatabase("tlslane").runCommand(new Document("ping", 1)))
- .isInstanceOf(RuntimeException.class);
- }
+ // when
+ Optional Polled rather than slept through, so the test spends the certificate's lifetime and not a
- * fixed guess at it, and so a failure to expire is reported as a timeout rather than as a pass.
+ * fixed guess at it, and so a failure to expire is reported as a timeout rather than as a pass. A
+ * second apart, because whatever the poll waits past the moment of expiry is added to the test as
+ * it is.
*/
- private static void pingUntilItFails(MongoTlsReplicaSetContainer server, String authority)
+ private static Throwable refusalOnceExpired(MongoTlsReplicaSetContainer server, String authority)
throws InterruptedException {
- long deadline = System.nanoTime() + java.time.Duration.ofMinutes(2).toNanos();
+ long deadline = System.nanoTime() + Duration.ofMinutes(2).toNanos();
while (System.nanoTime() < deadline) {
- try (MongoClient client = clientFor(server.connectionString(server.host()), authority)) {
- client.getDatabase("tlslane").runCommand(new Document("ping", 1));
+ Optional Read from the client's server monitor rather than from a command. A command waits out the
+ * whole server-selection timeout whatever made the server unreachable — the driver's selection
+ * loop stops only for an incompatible server or for the timeout — so a handshake refused in
+ * milliseconds cost the full bound and surfaced as a timeout, which a dead container raises just
+ * as well. An attempt that ended before the certificate was judged (a socket slow to open, a
+ * connection dropped mid-handshake) decides nothing; the monitor retries it. The bound stays,
+ * only as a bound: nothing decided inside it fails the test, and never counts as a refusal.
+ */
+ private static Optional Failures come from the heartbeat events, which fire once per attempt. A server description
+ * changes only when an attempt fails differently from the one before, and the driver tells two
+ * failures apart by the outer exception's class and message alone, which a dropped socket and a
+ * refused certificate can share. Acceptance comes from the description, because the handshake
+ * that opens the monitor's connection is reported as a heartbeat only when it fails (driver-core
+ * 5.6.5, {@code DefaultServerMonitor.ServerMonitor.setupNewConnectionAndGetInitialDescription}).
+ */
+ private static final class HandshakeWatch implements ServerListener, ServerMonitorListener {
+
+ private final CompletableFuture It has a subject of its own, so a client trusting only it holds no anchor that could have
+ * issued this server's certificate and cannot build a path to one: the refusal a client
+ * configured with the wrong authority meets. Generated by one {@code openssl} run inside this
+ * container rather than by a second server, since nothing needs to be served under it.
+ *
+ * @return a CA certificate that a client trusting only it must refuse this server with
+ */
+ public String unrelatedAuthorityPem() {
+ String pem =
+ evaluateShell(
+ "openssl req -x509 -newkey rsa:2048 -nodes -keyout /tmp/unrelated-ca.key -days 3650"
+ + " -subj '/CN=unrelated-ca'");
+ if (!pem.contains("BEGIN CERTIFICATE")) {
+ throw new IllegalStateException("the unrelated certificate authority was not generated");
+ }
+ return pem;
+ }
+
/** The host the mapped port is reachable on. */
public String host() {
return container.getHost();