From 74187f383576801ae09d8d3fb196d04ebcabaeca Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 21 Nov 2026 15:22:55 +0900 Subject: [PATCH] =?UTF-8?q?test(mongo):=20TLS=20lane=20=EA=B1=B0=EC=A0=88?= =?UTF-8?q?=EC=9D=84=20=EC=B2=AB=20handshake=20=EC=8B=A4=ED=8C=A8=EB=A1=9C?= =?UTF-8?q?=20=ED=8C=90=EC=A0=95=ED=95=98=EA=B3=A0=20mongod=20=ED=95=98?= =?UTF-8?q?=EB=82=98=EB=A5=BC=20=EC=97=86=EC=95=A4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MongoTlsLaneTest가 lane(mongoSecurityIntegrationTest) 시간의 절반 넘게 기다림에 쓴다. 거절 셋(믿지 않는 CA, 이름 불일치, 만료)은 handshake가 ms 안에 실패해도 command가 서버 선택 timeout 10 s를 다 기다린 뒤에야 던지고(driver 5.6.5 BaseCluster.selectServer는 비호환과 timeout에서만 끝난다), 만료 poll은 5 s 간격이고, 「다른 CA」 PEM 하나를 얻으려고 mongod를 하나 더 띄워 rs.initiate까지 한다. 단언도 isInstanceOf(RuntimeException)이라 컨테이너가 죽어도 통과한다. 거절 판정을 client의 server monitor에서 받는다. cause 사슬에 CertificateException이 있는 첫 heartbeat 실패가 거절이고, CONNECTED description이 수락이다. 인증서를 판정하지 않은 실패(소켓 지연·끊김)는 기록만 하고 500 ms heartbeat로 다시 시도한다. 10 s는 상한으로만 남고, 그 안에 판정이 없으면 거절로 세지 않고 AssertionError로 실패한다. 거절 셋은 원인별 root cause를 단언한다: 경로 빌드 실패, 접속 host를 담은 이름 불일치, CertificateExpiredException. 거절은 description 변화가 아니라 heartbeat 이벤트에서 받는다. driver는 바깥 예외의 class와 message만으로 같은 실패를 가려 description 이벤트를 다시 내지 않아, 소켓 끊김 뒤의 인증서 거절이 묻힐 수 있다(driver-core 5.6.5 EventHelper). 「다른 CA」는 server 컨테이너 안 openssl 한 번 (MongoTlsReplicaSetContainer.unrelatedAuthorityPem, subject /CN=unrelated-ca)으로 만들고 두 번째 mongod를 지운다. subject가 같은 CA는 JDK가 경로 빌드 대신 서명 검사로 가서 다른 거절이 된다. 만료 poll은 1 s로 줄인다. 45 s 창, MongoSecurityIntegrationLaneTest, lane 설정, 운영 client 설정은 그대로다. 버린 안: 거절 client만 서버 선택 timeout을 줄이기(부하에서 「믿는데도 timeout」이 거절로 셈해진다), 검증 날짜를 미래로 돌린 TrustManager(실제 시계·운영 설정과 멀어진다). 위험·한계: 같은 이름·다른 키 CA(교체된 CA)의 서명 검사 실패 경로는 어느 시험도 세우지 않는다. 컨테이너를 하나 더 띄워야 해서 넣지 않았다. 단언이 Sun provider 문구와 JDK 예외 사슬 모양에 기대어, 바뀌면 RED로 닫힌다. 두 거절 시험 각 5 s 미만은 new 3회 중 untrusted 6.3/3.0/7.0 s, mismatch 5.4/4.3/5.9 s라 그대로는 못 채웠다. 넘친 몫은 컨테이너 준비(시작 + rs.initiate)이고 판정은 0.02 s 이하다. 검증(desktop, runner job 없을 때): lane --rerun 번갈아 3+3회 중앙값 벽시계 108.9 → 77.9 s, XML 94.5 → 63.1 s. Mongo 컨테이너 6 → 5. 변이 둘(untrusted가 server 자신의 CA, mismatch가 닿는 SAN) 모두 「no handshake failure came」로 RED. 이 lane은 integrationCheck(main·nightly) 에서만 돌아 PR run이 돌리지 않는다. Refs: REV-BE-0043 --- .../mongo/security/MongoTlsLaneTest.java | 229 ++++++++++++++---- .../rs/MongoTlsReplicaSetContainer.java | 21 ++ 2 files changed, 207 insertions(+), 43 deletions(-) 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 refusal = firstHandshake(server, unrelatedAuthority); + + // then + assertThat(refusal) + .as("no handshake failure came: the first handshake was accepted") + .get(InstanceOfAssertFactories.THROWABLE) + .rootCause() + .as("refused, but not because no path led to a trusted authority") + .isInstanceOf(CertPathBuilderException.class) + .hasMessage("unable to find valid certification path to requested target"); } } @Test - @DisplayName("a certificate naming another host is refused") - void aHostnameMismatchIsRefused() { + @DisplayName("믿는 CA가 서명했어도 접속한 host를 이름에 담지 않은 인증서는 첫 handshake에서 거절된다") + void aHostnameMismatchIsRefused() throws InterruptedException { try (MongoTlsReplicaSetContainer server = MongoTlsReplicaSetContainer.withMismatchedHostname()) { + // given server.start(); + String authority = server.certificateAuthorityPem(); - try (MongoClient client = - clientFor(server.connectionString(server.host()), server.certificateAuthorityPem())) { - assertThatThrownBy(() -> client.getDatabase("tlslane").runCommand(new Document("ping", 1))) - .as("a trusted authority is not the same question as the right server") - .isInstanceOf(RuntimeException.class); - } + // when + Optional refusal = firstHandshake(server, authority); + + // then + assertThat(refusal) + .as("no handshake failure came: the first handshake was accepted") + .get(InstanceOfAssertFactories.THROWABLE) + .rootCause() + .as("a trusted authority is not the same question as the right server") + .isExactlyInstanceOf(CertificateException.class) + .hasMessageContaining(server.host()); } } @Test - @DisplayName("a certificate that expires while the server runs stops being accepted") + @DisplayName("서버가 도는 동안 유효 기간이 끝난 인증서는 그 뒤 새 client의 handshake에서 만료로 거절된다") void anExpiredCertificateIsRefused() throws InterruptedException { // Expiry is staged under a running server rather than before it starts: mongod validates its // own certificate at startup and refuses to serve with one that has already expired, so the @@ -94,9 +138,9 @@ class MongoTlsLaneTest { // connections that were working stop working. try (MongoTlsReplicaSetContainer server = MongoTlsReplicaSetContainer.withCertificateExpiringIn(45)) { + // given server.start(); String authority = server.certificateAuthorityPem(); - try (MongoClient beforeExpiry = clientFor(server.connectionString(server.host()), authority)) { assertThatCode( @@ -105,41 +149,140 @@ class MongoTlsLaneTest { .doesNotThrowAnyException(); } - assertThatThrownBy(() -> pingUntilItFails(server, authority)) + // when + Throwable refusal = refusalOnceExpired(server, authority); + + // then + assertThat(refusal) .as("a certificate outside its validity window is not a certificate") - .isInstanceOf(RuntimeException.class); + .rootCause() + .isInstanceOf(CertificateExpiredException.class) + .hasMessageStartingWith("NotAfter:"); } } /** - * Opens a fresh connection until one is refused, or until the window should long since have - * closed. + * Opens a fresh client a second apart until its first handshake is refused, or until the window + * should long since have closed. * *

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 refusal = firstHandshake(server, authority); + if (refusal.isPresent()) { + return refusal.get(); } - Thread.sleep(java.time.Duration.ofSeconds(5)); + Thread.sleep(EXPIRY_POLL); } throw new AssertionError("the certificate never stopped being accepted"); } + /** + * The first handshake a fresh client decides with this server: empty when it was accepted, the + * failure when the certificate was judged and refused. + * + *

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 firstHandshake( + MongoTlsReplicaSetContainer server, String authorityPem) throws InterruptedException { + HandshakeWatch watch = new HandshakeWatch(); + MongoClientSettings settings = + settings(server.connectionString(server.host()), authorityPem) + .applyToServerSettings( + monitor -> + monitor + .addServerListener(watch) + .addServerMonitorListener(watch) + .heartbeatFrequency(RETRY_INTERVAL.toMillis(), TimeUnit.MILLISECONDS)) + .build(); + // The client exists for its server monitor, which starts with it; nothing is sent through it. + try (MongoClient ignored = MongoClients.create(settings)) { + return watch.await(); + } + } + + /** + * What a client's server monitor reports about its handshakes with one server. + * + *

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> decided = new CompletableFuture<>(); + + private final List undecided = new CopyOnWriteArrayList<>(); + + @Override + public void serverDescriptionChanged(ServerDescriptionChangedEvent event) { + if (event.getNewDescription().getState() == ServerConnectionState.CONNECTED) { + decided.complete(Optional.empty()); + } + } + + @Override + public void serverHeartbeatFailed(ServerHeartbeatFailedEvent event) { + Throwable failure = event.getThrowable(); + if (judgedTheCertificate(failure)) { + decided.complete(Optional.of(failure)); + } else { + undecided.add(failure); + } + } + + Optional await() throws InterruptedException { + try { + return decided.get(HANDSHAKE_BOUND.toMillis(), TimeUnit.MILLISECONDS); + } catch (TimeoutException undecidedInTime) { + throw new AssertionError( + "no handshake was decided within " + + HANDSHAKE_BOUND + + "; attempts that judged no certificate: " + + undecided); + } catch (ExecutionException unreachable) { + throw new IllegalStateException("the watch is never completed exceptionally", unreachable); + } + } + + private static boolean judgedTheCertificate(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof CertificateException) { + return true; + } + } + return false; + } + } + /** A client that trusts exactly one authority and nothing else. */ private static MongoClient clientFor(String connectionString, String authorityPem) { - return MongoClients.create( - MongoClientSettings.builder() - .applyConnectionString(new ConnectionString(connectionString)) - .applyToSslSettings(ssl -> ssl.enabled(true).context(trustOnly(authorityPem))) - .applyToClusterSettings( - cluster -> - cluster.serverSelectionTimeout(10, java.util.concurrent.TimeUnit.SECONDS)) - .build()); + return MongoClients.create(settings(connectionString, authorityPem).build()); + } + + private static MongoClientSettings.Builder settings( + String connectionString, String authorityPem) { + return MongoClientSettings.builder() + .applyConnectionString(new ConnectionString(connectionString)) + .applyToSslSettings(ssl -> ssl.enabled(true).context(trustOnly(authorityPem))) + .applyToClusterSettings( + cluster -> + cluster.serverSelectionTimeout(HANDSHAKE_BOUND.toMillis(), TimeUnit.MILLISECONDS)); } private static SSLContext trustOnly(String authorityPem) { diff --git a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoTlsReplicaSetContainer.java b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoTlsReplicaSetContainer.java index 37e99983..4337699d 100644 --- a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoTlsReplicaSetContainer.java +++ b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoTlsReplicaSetContainer.java @@ -172,6 +172,27 @@ public final class MongoTlsReplicaSetContainer implements AutoCloseable { return pem; } + /** + * An authority that did not sign this server's certificate, in PEM. + * + *

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(); -- 2.54.0