mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(rds): match proxy TLS cert SAN to the advertised endpoint (#2603)
Persists a shared self-signed CA whose SAN list grows to cover every advertised RDS host, enabling sslmode=verify-full / VERIFY_IDENTITY for both Postgres and MySQL proxy connections. Reissuing the CA for a new host now reuses its existing key pair instead of minting a new one, so a client that already trusts a prior copy keeps validating connections as the SAN list grows. The MySQL TLS upgrade path also renumbers every packet through the rest of the connection phase (not just the first), since the backend's sequence counter stays one behind the client's for as long as that phase lasts. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
1 parent
e0bf1929e1
commit
b1d7286444
13 files changed
+1308
-152
No files matched your search
@@ -936,7 +936,7 @@ class RdsServiceTest {
|
||||
assertEquals("DBSubnetGroupNotFoundFault", exception.getErrorCode());
|
||||
verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1001,7 +1001,7 @@ class RdsServiceTest {
|
||||
assertNull(cluster.getContainerId());
|
||||
verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1234,7 +1234,7 @@ class RdsServiceTest {
|
||||
assertNull(instance.getDockerVolumeName());
|
||||
verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1300,7 +1300,7 @@ class RdsServiceTest {
|
||||
verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(containerManager, never()).stop(any());
|
||||
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1957,7 +1957,7 @@ class RdsServiceTest {
|
||||
eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app"));
|
||||
verify(restoredProxyManager).startProxy(
|
||||
eq("rds-resource:" + restored.getDbInstanceArn()), eq(DatabaseEngine.POSTGRES),
|
||||
eq(false), eq(persistedProxyPort), eq("127.0.0.1"), eq(15432),
|
||||
eq(false), eq(persistedProxyPort), eq("127.0.0.1"), eq(15432), any(),
|
||||
eq("admin"), eq("secret"), eq("app"), any());
|
||||
|
||||
restoredService.deleteDbInstance("mydb");
|
||||
@@ -2010,11 +2010,11 @@ class RdsServiceTest {
|
||||
eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app"));
|
||||
verify(restoredProxyManager).startProxy(
|
||||
eq("rds-resource:" + restoredCluster.getDbClusterArn()), eq(DatabaseEngine.POSTGRES),
|
||||
eq(false), eq(cluster.getProxyPort()), eq("127.0.0.1"), eq(15432),
|
||||
eq(false), eq(cluster.getProxyPort()), eq("127.0.0.1"), eq(15432), any(),
|
||||
eq("admin"), eq("secret"), eq("app"), any());
|
||||
verify(restoredProxyManager).startProxy(
|
||||
eq("rds-resource:" + restoredMember.getDbInstanceArn()), eq(DatabaseEngine.POSTGRES),
|
||||
eq(false), eq(member.getProxyPort()), eq("127.0.0.1"), eq(15432),
|
||||
eq(false), eq(member.getProxyPort()), eq("127.0.0.1"), eq(15432), any(),
|
||||
eq("admin"), eq("secret"), eq("app"), any());
|
||||
}
|
||||
|
||||
@@ -2038,7 +2038,7 @@ class RdsServiceTest {
|
||||
.doNothing()
|
||||
.when(restoredProxyManager).startProxy(
|
||||
any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any());
|
||||
org.mockito.Mockito.doThrow(new IllegalStateException("cleanup failed"))
|
||||
.doNothing()
|
||||
.doNothing()
|
||||
@@ -2163,7 +2163,7 @@ class RdsServiceTest {
|
||||
.doNothing()
|
||||
.when(restoredProxyManager).startProxy(
|
||||
any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any());
|
||||
org.mockito.Mockito.doThrow(new IllegalStateException("restore container cleanup failed"))
|
||||
.doThrow(new IllegalStateException("delete container cleanup failed"))
|
||||
.doNothing()
|
||||
@@ -2661,7 +2661,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
RdsService service = proxyStoreService(
|
||||
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
|
||||
DbProxyAuth requiredAuth = new DbProxyAuth(
|
||||
@@ -2715,7 +2715,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
RdsService service = proxyStoreService(
|
||||
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
|
||||
DbProxyAuth requiredAuth = new DbProxyAuth(
|
||||
@@ -2981,7 +2981,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
RdsService service = proxyStoreService(
|
||||
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
|
||||
|
||||
@@ -3098,7 +3098,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
RdsService service = proxyStoreService(
|
||||
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
|
||||
|
||||
@@ -3167,7 +3167,7 @@ class RdsServiceTest {
|
||||
.getTargets().isEmpty());
|
||||
verify(proxyManager).startProxy(
|
||||
eq("db-proxy:" + proxy.getDbProxyArn()), eq(DatabaseEngine.MYSQL),
|
||||
anyBoolean(), eq(3306), eq("localhost"), eq(3306),
|
||||
anyBoolean(), eq(3306), eq("localhost"), eq(3306), any(),
|
||||
eq("admin"), eq("secret"), eq("app"), any());
|
||||
verify(proxyManager).stopProxy("db-proxy:" + proxy.getDbProxyArn());
|
||||
}
|
||||
@@ -3197,7 +3197,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
throw startupFailure;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
doAnswer(invocation -> {
|
||||
relayRunning.set(false);
|
||||
return null;
|
||||
@@ -3664,7 +3664,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
IllegalStateException deleteFailure =
|
||||
new IllegalStateException("simulated post-mutation target-group delete failure");
|
||||
doAnswer(invocation -> {
|
||||
@@ -3729,7 +3729,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
IllegalStateException deleteFailure =
|
||||
new IllegalStateException("simulated post-mutation proxy delete failure");
|
||||
doAnswer(invocation -> {
|
||||
@@ -3892,9 +3892,9 @@ class RdsServiceTest {
|
||||
String relayKeyB = "rds-resource:" + instanceB.getDbInstanceArn();
|
||||
|
||||
verify(proxyManager).startProxy(eq(relayKeyA), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
verify(proxyManager).startProxy(eq(relayKeyB), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
|
||||
org.mockito.Mockito.clearInvocations(proxyManager);
|
||||
serviceA.deleteDbInstance("shared-db");
|
||||
@@ -4009,7 +4009,7 @@ class RdsServiceTest {
|
||||
assertTrue(rawClusters.get("cluster1").isPresent());
|
||||
assertTrue(rawClusters.get(currentAccount + "/cluster1").isEmpty());
|
||||
verify(proxyManager, never()).startProxy(
|
||||
any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any());
|
||||
any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -4115,7 +4115,7 @@ class RdsServiceTest {
|
||||
assertEquals("insufficient-resource-limits", failed.getStatus());
|
||||
verify(proxyManager, never()).startProxy(
|
||||
eq("db-proxy:" + proxy.getDbProxyArn()), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
|
||||
DbProxy another = service.createDbProxy(
|
||||
"another-proxy", "MYSQL", true, false, "NONE", PROXY_ROLE_ARN,
|
||||
@@ -4135,7 +4135,7 @@ class RdsServiceTest {
|
||||
verify(proxyManager).startProxy(
|
||||
eq("db-proxy:" + proxy.getDbProxyArn()), eq(DatabaseEngine.MYSQL),
|
||||
anyBoolean(), eq(failed.getProxyPort()), any(), anyInt(),
|
||||
any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -4161,7 +4161,7 @@ class RdsServiceTest {
|
||||
service.getDbProxy("app-proxy", "us-east-1").getStatus());
|
||||
verify(proxyManager, never()).startProxy(
|
||||
eq("db-proxy:" + proxy.getDbProxyArn()), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -4225,7 +4225,7 @@ class RdsServiceTest {
|
||||
assertEquals("app-proxy", restored.getDbProxyName());
|
||||
verify(restoredProxyManager).startProxy(eq("db-proxy:" + restored.getDbProxyArn()),
|
||||
eq(DatabaseEngine.POSTGRES),
|
||||
eq(false), anyInt(), eq("127.0.0.1"), eq(15432),
|
||||
eq(false), anyInt(), eq("127.0.0.1"), eq(15432), any(),
|
||||
eq("admin"), eq("secret"), eq("app"), any());
|
||||
}
|
||||
|
||||
@@ -4297,7 +4297,7 @@ class RdsServiceTest {
|
||||
ArgumentCaptor.forClass(RdsAuthProxy.PasswordValidator.class);
|
||||
verify(restoredProxyManager).startProxy(eq("db-proxy:" + proxy.getDbProxyArn()),
|
||||
eq(DatabaseEngine.POSTGRES),
|
||||
eq(false), eq(5432), eq("127.0.0.1"), eq(15432), eq("admin"),
|
||||
eq(false), eq(5432), eq("127.0.0.1"), eq(15432), any(), eq("admin"),
|
||||
eq("target-secret"), eq("app"), validator.capture());
|
||||
assertTrue(validator.getValue().validate("admin", "target-secret"));
|
||||
assertFalse(validator.getValue().validate("admin", "default-secret"));
|
||||
|
||||
+467
@@ -0,0 +1,467 @@
|
||||
package io.github.hectorvent.floci.services.rds.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class MySqlProtocolHandlerTest {
|
||||
|
||||
private static final int CLIENT_PROTOCOL_41 = 0x0200;
|
||||
private static final int CLIENT_SECURE_CONNECTION = 0x8000;
|
||||
private static final int CLIENT_SSL = 0x0800;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void forwardsPlaintextHandshakeResponseUnmodifiedWhenClientDoesNotRequestTls() throws Exception {
|
||||
byte[] nonce = fixedNonce();
|
||||
AtomicReference<Byte> backendResponseSeq = new AtomicReference<>();
|
||||
AtomicReference<byte[]> backendResponsePayload = new AtomicReference<>();
|
||||
|
||||
try (ServerSocket backendServer = new ServerSocket(0);
|
||||
ServerSocket clientServer = new ServerSocket(0)) {
|
||||
|
||||
Thread backendThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
mockMySqlBackend(backendServer, nonce, backendResponseSeq, backendResponsePayload);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
|
||||
Socket proxyClient = clientServer.accept();
|
||||
Socket backend = new Socket("localhost", backendServer.getLocalPort());
|
||||
|
||||
Thread authThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
MySqlProtocolHandler.handleAuth(
|
||||
proxyClient, backend, "admin", "secret",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
(user, pass) -> true);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
InputStream clientIn = ourClient.getInputStream();
|
||||
OutputStream clientOut = ourClient.getOutputStream();
|
||||
|
||||
byte[] serverHandshake = readMysqlPacketRaw(clientIn);
|
||||
assertNotNull(serverHandshake);
|
||||
// The proxy forces CLIENT_SSL even though the mock backend didn't advertise it.
|
||||
assertTrue((capabilityFlagsLower(serverHandshake) & CLIENT_SSL) != 0);
|
||||
|
||||
byte[] scramble = scrambleNativePassword("secret", nonce);
|
||||
byte[] response = buildHandshakeResponse41("admin", scramble, (byte) 1);
|
||||
clientOut.write(response);
|
||||
clientOut.flush();
|
||||
|
||||
// Wait for the backend's OK packet to come back through the bridge before tearing
|
||||
// down sockets, so we don't race the proxy mid-relay.
|
||||
assertNotNull(readMysqlPacketRaw(clientIn));
|
||||
|
||||
ourClient.close();
|
||||
proxyClient.close();
|
||||
authThread.join(5_000);
|
||||
backendThread.join(5_000);
|
||||
assertEquals(false, authThread.isAlive(), "authThread did not terminate");
|
||||
assertEquals(false, backendThread.isAlive(), "backendThread did not terminate");
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals((byte) 1, backendResponseSeq.get(), "sequence must be unchanged when no TLS upgrade occurs");
|
||||
assertEquals("admin", extractUsername(backendResponsePayload.get()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void upgradesToTlsOnSslRequestAndRenumbersSequenceBeforeForwardingToBackend() throws Exception {
|
||||
byte[] nonce = fixedNonce();
|
||||
AtomicReference<Byte> backendResponseSeq = new AtomicReference<>();
|
||||
AtomicReference<byte[]> backendResponsePayload = new AtomicReference<>();
|
||||
RdsProxyTlsCertificates tlsCertificates = testTlsCertificates();
|
||||
tlsCertificates.ensureHost("172.17.0.6");
|
||||
|
||||
try (ServerSocket backendServer = new ServerSocket(0);
|
||||
ServerSocket clientServer = new ServerSocket(0)) {
|
||||
|
||||
Thread backendThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
mockMySqlBackend(backendServer, nonce, backendResponseSeq, backendResponsePayload);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
|
||||
Socket proxyClient = clientServer.accept();
|
||||
Socket backend = new Socket("localhost", backendServer.getLocalPort());
|
||||
|
||||
Thread authThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
MySqlProtocolHandler.handleAuth(
|
||||
proxyClient, backend, "admin", "secret",
|
||||
false, testSigV4Validator(), tlsCertificates,
|
||||
(user, pass) -> true);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
InputStream clientIn = ourClient.getInputStream();
|
||||
OutputStream clientOut = ourClient.getOutputStream();
|
||||
|
||||
byte[] serverHandshake = readMysqlPacketRaw(clientIn);
|
||||
assertNotNull(serverHandshake);
|
||||
assertTrue((capabilityFlagsLower(serverHandshake) & CLIENT_SSL) != 0);
|
||||
|
||||
// SSLRequest: 32-byte payload, CLIENT_SSL set, sequence 1 (right after the server's
|
||||
// handshake at sequence 0).
|
||||
clientOut.write(buildSslRequest());
|
||||
clientOut.flush();
|
||||
|
||||
SSLSocket sslClient = trustedClientSocket(ourClient);
|
||||
sslClient.startHandshake();
|
||||
InputStream tlsIn = sslClient.getInputStream();
|
||||
OutputStream tlsOut = sslClient.getOutputStream();
|
||||
|
||||
byte[] scramble = scrambleNativePassword("secret", nonce);
|
||||
// Real clients send this at sequence 2 after the TLS upgrade — the proxy must
|
||||
// rewrite it to 1 before forwarding to the (plaintext-only) backend.
|
||||
byte[] response = buildHandshakeResponse41("admin", scramble, (byte) 2);
|
||||
tlsOut.write(response);
|
||||
tlsOut.flush();
|
||||
|
||||
// The mock backend replies with sequence 2 (its own view of the shared counter);
|
||||
// the client, having sent its SSLRequest at sequence 1, expects that reply at 3.
|
||||
byte[] okPacket = readMysqlPacketRaw(tlsIn);
|
||||
assertNotNull(okPacket);
|
||||
assertEquals((byte) 3, okPacket[3],
|
||||
"client sent SSLRequest(1) then response(2), so it expects the backend's "
|
||||
+ "reply at sequence 3, not the backend's own sequence 2");
|
||||
|
||||
ourClient.close();
|
||||
proxyClient.close();
|
||||
authThread.join(5_000);
|
||||
backendThread.join(5_000);
|
||||
assertEquals(false, authThread.isAlive(), "authThread did not terminate");
|
||||
assertEquals(false, backendThread.isAlive(), "backendThread did not terminate");
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals((byte) 1, backendResponseSeq.get(),
|
||||
"backend never saw the SSLRequest, so it must receive the real response at sequence 1");
|
||||
assertEquals("admin", extractUsername(backendResponsePayload.get()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fastAuthSuccessDoesNotBlockWaitingForAClientReply() throws Exception {
|
||||
byte[] nonce = fixedNonce();
|
||||
RdsProxyTlsCertificates tlsCertificates = testTlsCertificates();
|
||||
tlsCertificates.ensureHost("172.17.0.7");
|
||||
|
||||
try (ServerSocket backendServer = new ServerSocket(0);
|
||||
ServerSocket clientServer = new ServerSocket(0)) {
|
||||
|
||||
Thread backendThread = Thread.ofVirtual().start(() -> {
|
||||
try (Socket socket = backendServer.accept()) {
|
||||
OutputStream out = socket.getOutputStream();
|
||||
InputStream in = socket.getInputStream();
|
||||
|
||||
out.write(buildHandshakeV10(nonce));
|
||||
out.flush();
|
||||
|
||||
readMysqlPacketRaw(in); // the real HandshakeResponse41, forwarded at sequence 1
|
||||
|
||||
// caching_sha2_password fast-auth success: AuthMoreData(0x03) immediately
|
||||
// followed by the terminal OK — the client sends nothing back in between.
|
||||
writeMysqlPacket(out, 2, new byte[]{0x01, 0x03});
|
||||
writeMysqlPacket(out, 3, new byte[]{0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00});
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
|
||||
Socket proxyClient = clientServer.accept();
|
||||
Socket backend = new Socket("localhost", backendServer.getLocalPort());
|
||||
|
||||
Thread authThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
MySqlProtocolHandler.handleAuth(
|
||||
proxyClient, backend, "admin", "secret",
|
||||
false, testSigV4Validator(), tlsCertificates,
|
||||
(user, pass) -> true);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
InputStream clientIn = ourClient.getInputStream();
|
||||
OutputStream clientOut = ourClient.getOutputStream();
|
||||
|
||||
assertNotNull(readMysqlPacketRaw(clientIn));
|
||||
|
||||
clientOut.write(buildSslRequest());
|
||||
clientOut.flush();
|
||||
|
||||
SSLSocket sslClient = trustedClientSocket(ourClient);
|
||||
sslClient.startHandshake();
|
||||
InputStream tlsIn = sslClient.getInputStream();
|
||||
OutputStream tlsOut = sslClient.getOutputStream();
|
||||
|
||||
byte[] scramble = scrambleNativePassword("secret", nonce);
|
||||
byte[] response = buildHandshakeResponse41("admin", scramble, (byte) 2);
|
||||
tlsOut.write(response);
|
||||
tlsOut.flush();
|
||||
|
||||
// Neither packet should require anything further from the client — if the proxy
|
||||
// wrongly waits for a client reply after AuthMoreData(0x03), this blocks until the
|
||||
// join timeout below fails the test.
|
||||
byte[] authMoreData = readMysqlPacketRaw(tlsIn);
|
||||
assertNotNull(authMoreData);
|
||||
assertEquals((byte) 0x01, authMoreData[4], "expected AuthMoreData");
|
||||
|
||||
byte[] okPacket = readMysqlPacketRaw(tlsIn);
|
||||
assertNotNull(okPacket);
|
||||
assertEquals((byte) 0x00, okPacket[4], "expected the terminal OK packet");
|
||||
|
||||
ourClient.close();
|
||||
proxyClient.close();
|
||||
authThread.join(5_000);
|
||||
backendThread.join(5_000);
|
||||
assertEquals(false, authThread.isAlive(), "authThread did not terminate");
|
||||
assertEquals(false, backendThread.isAlive(), "backendThread did not terminate");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private RdsProxyTlsCertificates testTlsCertificates() {
|
||||
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
|
||||
when(storage.persistentPath()).thenReturn(tempDir.toString());
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.storage()).thenReturn(storage);
|
||||
return new RdsProxyTlsCertificates(config, new CertificateGenerator());
|
||||
}
|
||||
|
||||
private static RdsSigV4Validator testSigV4Validator() {
|
||||
return new RdsSigV4Validator(IamServiceTestHelper.iamServiceWithAccessKey("AKIATEST", "secret"));
|
||||
}
|
||||
|
||||
private static SSLSocket trustedClientSocket(Socket socket) throws Exception {
|
||||
SSLContext context = SSLContext.getInstance("TLS");
|
||||
context.init(null, new TrustManager[]{new X509TrustManager() {
|
||||
@Override
|
||||
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
|
||||
|
||||
@Override
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return new X509Certificate[0];
|
||||
}
|
||||
}}, null);
|
||||
SSLSocket sslSocket = (SSLSocket) context.getSocketFactory()
|
||||
.createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
|
||||
sslSocket.setUseClientMode(true);
|
||||
return sslSocket;
|
||||
}
|
||||
|
||||
private static void mockMySqlBackend(ServerSocket server, byte[] nonce,
|
||||
AtomicReference<Byte> responseSeq,
|
||||
AtomicReference<byte[]> responsePayload) throws IOException {
|
||||
try (Socket socket = server.accept()) {
|
||||
OutputStream out = socket.getOutputStream();
|
||||
InputStream in = socket.getInputStream();
|
||||
|
||||
out.write(buildHandshakeV10(nonce));
|
||||
out.flush();
|
||||
|
||||
byte[] responseRaw = readMysqlPacketRaw(in);
|
||||
responseSeq.set(responseRaw[3]);
|
||||
byte[] payload = new byte[responseRaw.length - 4];
|
||||
System.arraycopy(responseRaw, 4, payload, 0, payload.length);
|
||||
responsePayload.set(payload);
|
||||
|
||||
writeMysqlPacket(out, 2, new byte[]{0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00}); // OK packet
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
|
||||
// ── MySQL Handshake V10 (server -> client) ──────────────────────────────
|
||||
|
||||
private static byte[] buildHandshakeV10(byte[] nonce) throws IOException {
|
||||
ByteArrayOutputStream payload = new ByteArrayOutputStream();
|
||||
payload.write(10); // protocol version
|
||||
payload.write("8.0.34".getBytes(StandardCharsets.UTF_8));
|
||||
payload.write(0);
|
||||
writeInt32LE(payload, 1); // connection id
|
||||
payload.write(nonce, 0, 8); // auth-plugin-data part 1
|
||||
payload.write(0); // filler
|
||||
int capsLower = (CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION) & 0xFFFF; // no CLIENT_SSL
|
||||
writeInt16LE(payload, capsLower);
|
||||
payload.write(0x21); // charset
|
||||
writeInt16LE(payload, 0x0002); // status flags
|
||||
writeInt16LE(payload, 0); // capability flags upper
|
||||
payload.write(0); // auth-plugin-data length (not advertised)
|
||||
payload.write(new byte[10]); // reserved
|
||||
payload.write(nonce, 8, 12); // auth-plugin-data part 2 (12 bytes)
|
||||
payload.write(0); // null terminator
|
||||
|
||||
return wrapPacket(0, payload.toByteArray());
|
||||
}
|
||||
|
||||
// ── MySQL SSLRequest / HandshakeResponse41 (client -> server) ───────────
|
||||
|
||||
private static byte[] buildSslRequest() throws IOException {
|
||||
ByteArrayOutputStream payload = new ByteArrayOutputStream();
|
||||
writeInt32LE(payload, CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION | CLIENT_SSL);
|
||||
writeInt32LE(payload, 0); // max packet size
|
||||
payload.write(0x21); // charset
|
||||
payload.write(new byte[23]); // reserved
|
||||
return wrapPacket(1, payload.toByteArray());
|
||||
}
|
||||
|
||||
private static byte[] buildHandshakeResponse41(String username, byte[] scramble, byte sequence)
|
||||
throws IOException {
|
||||
ByteArrayOutputStream payload = new ByteArrayOutputStream();
|
||||
writeInt32LE(payload, CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION);
|
||||
writeInt32LE(payload, 0); // max packet size
|
||||
payload.write(0x21); // charset
|
||||
payload.write(new byte[23]); // reserved
|
||||
payload.write(username.getBytes(StandardCharsets.UTF_8));
|
||||
payload.write(0);
|
||||
payload.write(scramble.length); // CLIENT_SECURE_CONNECTION: 1-byte length prefix
|
||||
payload.write(scramble);
|
||||
|
||||
return wrapPacket(sequence, payload.toByteArray());
|
||||
}
|
||||
|
||||
private static String extractUsername(byte[] payload) {
|
||||
int i = 4 + 4 + 1 + 23; // caps + max-packet-size + charset + reserved
|
||||
int start = i;
|
||||
while (i < payload.length && payload[i] != 0) {
|
||||
i++;
|
||||
}
|
||||
return new String(payload, start, i - start, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static int capabilityFlagsLower(byte[] handshakeRaw) {
|
||||
int i = 4 + 1; // header + protocol version
|
||||
while (i < handshakeRaw.length && handshakeRaw[i] != 0) {
|
||||
i++;
|
||||
}
|
||||
i++; // null terminator
|
||||
i += 4; // connection id
|
||||
i += 8; // auth-plugin-data part 1
|
||||
i++; // filler
|
||||
return (handshakeRaw[i] & 0xFF) | ((handshakeRaw[i + 1] & 0xFF) << 8);
|
||||
}
|
||||
|
||||
private static byte[] fixedNonce() {
|
||||
byte[] nonce = new byte[20];
|
||||
for (int i = 0; i < nonce.length; i++) {
|
||||
nonce[i] = (byte) (i + 1);
|
||||
}
|
||||
return nonce;
|
||||
}
|
||||
|
||||
private static byte[] scrambleNativePassword(String password, byte[] nonce) throws Exception {
|
||||
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
|
||||
byte[] hash1 = sha1.digest(password.getBytes(StandardCharsets.UTF_8));
|
||||
sha1.reset();
|
||||
byte[] hash2 = sha1.digest(hash1);
|
||||
sha1.reset();
|
||||
sha1.update(nonce);
|
||||
sha1.update(hash2);
|
||||
byte[] hash3 = sha1.digest();
|
||||
|
||||
byte[] result = new byte[20];
|
||||
for (int i = 0; i < 20; i++) {
|
||||
result[i] = (byte) (hash1[i] ^ hash3[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── Raw packet helpers ───────────────────────────────────────────────────
|
||||
|
||||
private static byte[] wrapPacket(int sequence, byte[] payload) {
|
||||
byte[] raw = new byte[4 + payload.length];
|
||||
int len = payload.length;
|
||||
raw[0] = (byte) (len & 0xFF);
|
||||
raw[1] = (byte) ((len >> 8) & 0xFF);
|
||||
raw[2] = (byte) ((len >> 16) & 0xFF);
|
||||
raw[3] = (byte) sequence;
|
||||
System.arraycopy(payload, 0, raw, 4, payload.length);
|
||||
return raw;
|
||||
}
|
||||
|
||||
private static void writeMysqlPacket(OutputStream out, int sequence, byte[] payload) throws IOException {
|
||||
out.write(wrapPacket(sequence, payload));
|
||||
}
|
||||
|
||||
private static byte[] readMysqlPacketRaw(InputStream in) throws IOException {
|
||||
int b0 = in.read();
|
||||
int b1 = in.read();
|
||||
int b2 = in.read();
|
||||
int seq = in.read();
|
||||
if ((b0 | b1 | b2 | seq) < 0) {
|
||||
return null;
|
||||
}
|
||||
int length = b0 | (b1 << 8) | (b2 << 16);
|
||||
byte[] raw = new byte[4 + length];
|
||||
raw[0] = (byte) b0;
|
||||
raw[1] = (byte) b1;
|
||||
raw[2] = (byte) b2;
|
||||
raw[3] = (byte) seq;
|
||||
int offset = 4;
|
||||
while (offset < raw.length) {
|
||||
int n = in.read(raw, offset, raw.length - offset);
|
||||
if (n < 0) {
|
||||
throw new EOFException("Connection closed while reading MySQL packet");
|
||||
}
|
||||
offset += n;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
private static void writeInt32LE(ByteArrayOutputStream out, int value) {
|
||||
out.write(value & 0xFF);
|
||||
out.write((value >> 8) & 0xFF);
|
||||
out.write((value >> 16) & 0xFF);
|
||||
out.write((value >> 24) & 0xFF);
|
||||
}
|
||||
|
||||
private static void writeInt16LE(ByteArrayOutputStream out, int value) {
|
||||
out.write(value & 0xFF);
|
||||
out.write((value >> 8) & 0xFF);
|
||||
}
|
||||
}
|
||||
+158
-4
@@ -1,7 +1,10 @@
|
||||
package io.github.hectorvent.floci.services.rds.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
@@ -12,23 +15,36 @@ import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.KeyStore;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
import javax.net.ssl.SSLParameters;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class PostgresProtocolHandlerTest {
|
||||
|
||||
private static final int SSL_REQUEST_CODE = 80877103;
|
||||
private static final int STARTUP_PROTOCOL_VERSION = 196608;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"auth_db, postgres, auth_db",
|
||||
@@ -68,7 +84,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.handleAuth(
|
||||
proxyClient, backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(),
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
(user, pass) -> true);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -122,7 +138,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.handleAuth(
|
||||
proxyClient, backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(),
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
(user, pass) -> true);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -176,7 +192,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.handleAuth(
|
||||
proxyClient, backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(),
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
(user, pass) -> true);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -212,6 +228,106 @@ class PostgresProtocolHandlerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void hostnameVerificationSucceedsForRegisteredAdvertisedHost() throws Exception {
|
||||
try (ServerSocket backendServer = new ServerSocket(0);
|
||||
ServerSocket clientServer = new ServerSocket(0)) {
|
||||
|
||||
RdsProxyTlsCertificates tlsCertificates = testTlsCertificates();
|
||||
String advertisedHost = "172.17.0.5";
|
||||
tlsCertificates.ensureHost(advertisedHost);
|
||||
|
||||
int backendPort = backendServer.getLocalPort();
|
||||
Thread backendThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
mockBackendStartup(backendServer, new AtomicReference<>(), false);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
|
||||
Socket proxyClient = clientServer.accept();
|
||||
Socket backend = new Socket("localhost", backendPort);
|
||||
|
||||
Thread authThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
PostgresProtocolHandler.handleAuth(
|
||||
proxyClient, backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), tlsCertificates,
|
||||
(user, pass) -> true);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
|
||||
DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
|
||||
|
||||
writeSslRequest(clientOut);
|
||||
assertEquals('S', clientIn.readUnsignedByte());
|
||||
|
||||
Path caCertFile = tempDir.resolve("tls").resolve("rds-ca.crt");
|
||||
SSLSocket sslClient = verifyingClientSocket(ourClient, caCertFile, advertisedHost);
|
||||
sslClient.startHandshake(); // must not throw — advertisedHost is in the cert's SAN
|
||||
|
||||
proxyClient.close();
|
||||
authThread.join(5_000);
|
||||
backendThread.join(5_000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void hostnameVerificationFailsForUnregisteredAdvertisedHost() throws Exception {
|
||||
try (ServerSocket backendServer = new ServerSocket(0);
|
||||
ServerSocket clientServer = new ServerSocket(0)) {
|
||||
|
||||
RdsProxyTlsCertificates tlsCertificates = testTlsCertificates();
|
||||
tlsCertificates.ensureHost("172.17.0.5");
|
||||
|
||||
int backendPort = backendServer.getLocalPort();
|
||||
Thread backendThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
mockBackendStartup(backendServer, new AtomicReference<>(), false);
|
||||
} catch (IOException e) {
|
||||
// Backend connection is torn down before completing startup — expected here.
|
||||
}
|
||||
});
|
||||
|
||||
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
|
||||
Socket proxyClient = clientServer.accept();
|
||||
Socket backend = new Socket("localhost", backendPort);
|
||||
|
||||
Thread authThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
PostgresProtocolHandler.handleAuth(
|
||||
proxyClient, backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), tlsCertificates,
|
||||
(user, pass) -> true);
|
||||
} catch (IOException ignored) {
|
||||
// Client aborts the handshake below — the handler observing that is expected.
|
||||
}
|
||||
});
|
||||
|
||||
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
|
||||
DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
|
||||
|
||||
writeSslRequest(clientOut);
|
||||
assertEquals('S', clientIn.readUnsignedByte());
|
||||
|
||||
Path caCertFile = tempDir.resolve("tls").resolve("rds-ca.crt");
|
||||
SSLSocket sslClient = verifyingClientSocket(ourClient, caCertFile, "never-registered.example.com");
|
||||
assertThrows(SSLHandshakeException.class, sslClient::startHandshake);
|
||||
|
||||
proxyClient.close();
|
||||
authThread.join(5_000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void closesClientWhenBackendClosesDuringBridge() throws Exception {
|
||||
try (ServerSocket backendServer = new ServerSocket(0);
|
||||
@@ -235,7 +351,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.handleAuth(
|
||||
proxyClient, backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(),
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
(user, pass) -> true);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -266,6 +382,44 @@ class PostgresProtocolHandlerTest {
|
||||
return new RdsSigV4Validator(IamServiceTestHelper.iamServiceWithAccessKey("AKIATEST", "secret"));
|
||||
}
|
||||
|
||||
private RdsProxyTlsCertificates testTlsCertificates() {
|
||||
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
|
||||
when(storage.persistentPath()).thenReturn(tempDir.toString());
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.storage()).thenReturn(storage);
|
||||
return new RdsProxyTlsCertificates(config, new CertificateGenerator());
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps {@code socket} in a client-side {@link SSLSocket} that trusts only {@code caCertFile}
|
||||
* and enforces standard HTTPS-style hostname verification against {@code advertisedHost} —
|
||||
* the same SAN-matching behavior libpq performs for {@code sslmode=verify-full}.
|
||||
*/
|
||||
private static SSLSocket verifyingClientSocket(Socket socket, Path caCertFile, String advertisedHost)
|
||||
throws Exception {
|
||||
X509Certificate ca;
|
||||
try (var in = Files.newInputStream(caCertFile)) {
|
||||
ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(in);
|
||||
}
|
||||
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||
trustStore.load(null, null);
|
||||
trustStore.setCertificateEntry("rds-ca", ca);
|
||||
|
||||
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
tmf.init(trustStore);
|
||||
|
||||
SSLContext context = SSLContext.getInstance("TLS");
|
||||
context.init(null, tmf.getTrustManagers(), null);
|
||||
|
||||
SSLSocket sslSocket = (SSLSocket) context.getSocketFactory()
|
||||
.createSocket(socket, advertisedHost, socket.getPort(), true);
|
||||
sslSocket.setUseClientMode(true);
|
||||
SSLParameters params = sslSocket.getSSLParameters();
|
||||
params.setEndpointIdentificationAlgorithm("HTTPS");
|
||||
sslSocket.setSSLParameters(params);
|
||||
return sslSocket;
|
||||
}
|
||||
|
||||
private static void mockBackendStartup(ServerSocket server, AtomicReference<String> backendDatabase,
|
||||
boolean failWithError) throws IOException {
|
||||
try (Socket socket = server.accept()) {
|
||||
|
||||
+16
-9
@@ -22,7 +22,8 @@ class RdsProxyManagerTest {
|
||||
|
||||
@Test
|
||||
void replacingProxyStopsPreviousListenerAndKeepsReplacementOwned() throws IOException {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
RdsProxyManager manager = new RdsProxyManager(
|
||||
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
|
||||
int firstPort = availablePort();
|
||||
try {
|
||||
start(manager, "proxy", firstPort);
|
||||
@@ -41,7 +42,8 @@ class RdsProxyManagerTest {
|
||||
|
||||
@Test
|
||||
void registrationFailureAfterBindReleasesCandidateListener() throws IOException {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
RdsProxyManager manager = new RdsProxyManager(
|
||||
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
|
||||
int proxyPort = availablePort();
|
||||
try {
|
||||
assertThrows(RuntimeException.class, () -> start(manager, null, proxyPort));
|
||||
@@ -54,7 +56,8 @@ class RdsProxyManagerTest {
|
||||
|
||||
@Test
|
||||
void failedReplacementPreservesOriginalRegistryEntry() throws IOException {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
RdsProxyManager manager = new RdsProxyManager(
|
||||
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
|
||||
int originalPort = availablePort();
|
||||
try {
|
||||
start(manager, "proxy", originalPort);
|
||||
@@ -73,7 +76,8 @@ class RdsProxyManagerTest {
|
||||
|
||||
@Test
|
||||
void stopAllReleasesEveryListenerAndIsIdempotent() throws IOException {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
RdsProxyManager manager = new RdsProxyManager(
|
||||
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
|
||||
int firstPort = availablePort();
|
||||
start(manager, "first", firstPort);
|
||||
int secondPort = availablePort();
|
||||
@@ -88,7 +92,8 @@ class RdsProxyManagerTest {
|
||||
|
||||
@Test
|
||||
void closeFailurePropagatesAndManagerRetainsOwnership() throws Exception {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
RdsProxyManager manager = new RdsProxyManager(
|
||||
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
|
||||
RdsAuthProxy proxy = authProxy("proxy");
|
||||
ServerSocket serverSocket = mock(ServerSocket.class);
|
||||
IOException closeFailure = new IOException("simulated close failure");
|
||||
@@ -107,7 +112,8 @@ class RdsProxyManagerTest {
|
||||
|
||||
@Test
|
||||
void failedPreviousStopRestoresMappingAndReleasesCandidate() throws Exception {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
RdsProxyManager manager = new RdsProxyManager(
|
||||
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
|
||||
RdsAuthProxy previous = mock(RdsAuthProxy.class);
|
||||
doThrow(new IllegalStateException("simulated previous stop failure"))
|
||||
.when(previous).stop();
|
||||
@@ -124,7 +130,8 @@ class RdsProxyManagerTest {
|
||||
|
||||
@Test
|
||||
void stopAllContinuesAndRetainsOnlyFailedListenerOwnership() throws Exception {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
RdsProxyManager manager = new RdsProxyManager(
|
||||
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
|
||||
int successfulPort = availablePort();
|
||||
start(manager, "successful", successfulPort);
|
||||
RdsAuthProxy failed = mock(RdsAuthProxy.class);
|
||||
@@ -143,13 +150,13 @@ class RdsProxyManagerTest {
|
||||
|
||||
private static void start(RdsProxyManager manager, String key, int proxyPort) {
|
||||
manager.startProxy(key, DatabaseEngine.POSTGRES, false, proxyPort,
|
||||
"localhost", 1, "admin", "secret", "app", (user, password) -> true);
|
||||
"localhost", 1, "localhost", "admin", "secret", "app", (user, password) -> true);
|
||||
}
|
||||
|
||||
private static RdsAuthProxy authProxy(String key) {
|
||||
return new RdsAuthProxy(key, "localhost", 1, DatabaseEngine.POSTGRES, false,
|
||||
"admin", "secret", "app", mock(RdsSigV4Validator.class),
|
||||
(user, password) -> true);
|
||||
mock(RdsProxyTlsCertificates.class), (user, password) -> true);
|
||||
}
|
||||
|
||||
private static void setServerSocket(RdsAuthProxy proxy, ServerSocket socket) throws Exception {
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package io.github.hectorvent.floci.services.rds.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFileAttributeView;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RdsProxyTlsCertificatesTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void ensureHostIsIdempotentWhenHostAlreadyCovered() {
|
||||
RdsProxyTlsCertificates certs = newCertificates();
|
||||
certs.ensureHost("172.17.0.5");
|
||||
SSLContext firstContext = certs.sslContext();
|
||||
|
||||
certs.ensureHost("172.17.0.5");
|
||||
|
||||
assertSame(firstContext, certs.sslContext(), "no regeneration for an already-covered host");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureHostRegeneratesWhenHostIsNew() {
|
||||
RdsProxyTlsCertificates certs = newCertificates();
|
||||
certs.ensureHost("172.17.0.5");
|
||||
SSLContext firstContext = certs.sslContext();
|
||||
|
||||
certs.ensureHost("host.docker.internal");
|
||||
|
||||
assertNotSame(firstContext, certs.sslContext(), "a genuinely new host must trigger regeneration");
|
||||
}
|
||||
|
||||
@Test
|
||||
void persistsAndReloadsSansAcrossInstances() throws Exception {
|
||||
RdsProxyTlsCertificates first = newCertificates();
|
||||
first.ensureHost("172.17.0.5");
|
||||
first.ensureHost("host.docker.internal");
|
||||
|
||||
Path certFile = tempDir.resolve("tls").resolve("rds-ca.crt");
|
||||
Path keyFile = tempDir.resolve("tls").resolve("rds-ca.key");
|
||||
Path metadataFile = tempDir.resolve("tls").resolve("rds-ca.metadata.json");
|
||||
assertTrue(Files.exists(certFile));
|
||||
assertTrue(Files.exists(keyFile));
|
||||
assertTrue(Files.exists(metadataFile));
|
||||
String persistedCertPem = Files.readString(certFile);
|
||||
|
||||
// A fresh instance (simulating a restart) backed by the same persistent path must reuse
|
||||
// the same cert rather than regenerating — otherwise a user's trusted sslrootcert goes stale
|
||||
// on every restart even when no new host has appeared.
|
||||
RdsProxyTlsCertificates reloaded = newCertificates();
|
||||
reloaded.ensureHost("172.17.0.5");
|
||||
reloaded.ensureHost("host.docker.internal");
|
||||
|
||||
assertEquals(persistedCertPem, Files.readString(certFile));
|
||||
}
|
||||
|
||||
@Test
|
||||
void growingSansReusesTheSameKeyPairSoOlderCertCopiesStillValidateNewOnes() throws Exception {
|
||||
RdsProxyTlsCertificates certs = newCertificates();
|
||||
certs.ensureHost("172.17.0.5");
|
||||
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
var firstCertificate = generator.parseCertificate(
|
||||
Files.readString(tempDir.resolve("tls").resolve("rds-ca.crt")));
|
||||
|
||||
certs.ensureHost("host.docker.internal");
|
||||
|
||||
var secondCertificate = generator.parseCertificate(
|
||||
Files.readString(tempDir.resolve("tls").resolve("rds-ca.crt")));
|
||||
|
||||
assertEquals(firstCertificate.getPublicKey(), secondCertificate.getPublicKey(),
|
||||
"growing the SAN list must reuse the existing key pair, not mint a new one, "
|
||||
+ "or a client that already trusts a prior copy of the CA loses trust");
|
||||
assertDoesNotThrow(() -> secondCertificate.verify(firstCertificate.getPublicKey()),
|
||||
"the old cert's public key must still validate the reissued cert's signature");
|
||||
}
|
||||
|
||||
@Test
|
||||
void privateKeyAndTlsDirAreRestrictedToOwnerOnly() throws Exception {
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
assumeTrue(Files.getFileStore(tempDir).supportsFileAttributeView(PosixFileAttributeView.class),
|
||||
"POSIX permissions are not supported on this filesystem");
|
||||
|
||||
RdsProxyTlsCertificates certs = newCertificates();
|
||||
certs.ensureHost("172.17.0.5");
|
||||
|
||||
Path keyFile = tlsDir.resolve("rds-ca.key");
|
||||
assertEquals(Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE),
|
||||
Files.getPosixFilePermissions(keyFile),
|
||||
"the CA private key must not be readable by anyone but the owner");
|
||||
assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(tlsDir),
|
||||
"the tls directory must not be traversable by anyone but the owner");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedCertificateIsAGenuineTrustAnchor() throws Exception {
|
||||
RdsProxyTlsCertificates certs = newCertificates();
|
||||
certs.ensureHost("172.17.0.5");
|
||||
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
var certificate = generator.parseCertificate(
|
||||
Files.readString(tempDir.resolve("tls").resolve("rds-ca.crt")));
|
||||
|
||||
assertEquals(certificate.getIssuerX500Principal(), certificate.getSubjectX500Principal());
|
||||
}
|
||||
|
||||
private RdsProxyTlsCertificates newCertificates() {
|
||||
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
|
||||
when(storage.persistentPath()).thenReturn(tempDir.toString());
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.storage()).thenReturn(storage);
|
||||
return new RdsProxyTlsCertificates(config, new CertificateGenerator());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user