test(mongo): TLS lane 거절을 첫 handshake 실패로 판정하고 mongod 하나를 없앤다 #79

Merged
donghyeon.kang merged 2 commits from test/mongo-tls-lane-handshake-refusal into main 2026-11-21 08:58:06 +00:00
2 changed files with 207 additions and 43 deletions
@@ -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;
*
* <p>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<Throwable> 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<Throwable> 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.
*
* <p>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<Throwable> 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.
*
* <p>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<Throwable> 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.
*
* <p>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<Optional<Throwable>> decided = new CompletableFuture<>();
private final List<Throwable> 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<Throwable> 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) {
@@ -172,6 +172,27 @@ public final class MongoTlsReplicaSetContainer implements AutoCloseable {
return pem;
}
/**
* An authority that did not sign this server's certificate, in PEM.
*
* <p>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();