fix(elasticache): terminate required TLS at cache proxies (#6227)

This commit is contained in:
jwoa95 authored and GitHub committed 2026-10-24 09:31:10 -04:00
1 parent b4c71b9e25
commit 346a7f4526
25 files changed
+979 -100

No files matched your search

@@ -0,0 +1,67 @@
package io.github.hectorvent.floci.config;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.cert.CertificateExpiredException;
import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ServerCertificateRenewalTest {
@TempDir
Path directory;
@Test
void aLeafLastsAYearAndIsDueAMinuteBeforeItEnds() throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
// after the CA's creation: a CA signs nothing before its own validity starts
Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS);
Clock clock = mock(Clock.class);
when(clock.instant()).thenReturn(now);
ServerCertificateRenewal renewal = new ServerCertificateRenewal(authority, new CertificateGenerator(), clock);
ServerCertificateRenewal.Leaf leaf = renewal.issue(List.of("localhost"));
assertEquals(now.plus(365, ChronoUnit.DAYS), leaf.notAfter());
assertTrue(renewal.due(null));
when(clock.instant()).thenReturn(leaf.notAfter().minusSeconds(61));
assertFalse(renewal.due(leaf));
when(clock.instant()).thenReturn(leaf.notAfter().minusSeconds(60));
assertTrue(renewal.due(leaf));
}
@Test
void aLeafEndsWithTheCaAndIsNotDueAgainUntilTheCaEnds() throws Exception {
CertificateGenerator.GeneratedCertificate ca = new CertificateGenerator().generateCaCertificate(
"Short-lived CA", Instant.now().plus(1, ChronoUnit.DAYS));
Files.writeString(directory.resolve(FlociCertificateAuthority.CA_CERT_NAME), ca.certificatePem());
Files.writeString(directory.resolve(FlociCertificateAuthority.CA_KEY_NAME), ca.privateKeyPem());
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
Instant caNotAfter = authority.certificate().getNotAfter().toInstant();
Clock clock = mock(Clock.class);
when(clock.instant()).thenReturn(Instant.now());
ServerCertificateRenewal renewal = new ServerCertificateRenewal(authority, new CertificateGenerator(), clock);
ServerCertificateRenewal.Leaf leaf = renewal.issue(List.of("localhost"));
assertEquals(caNotAfter, leaf.notAfter());
when(clock.instant()).thenReturn(caNotAfter.minusSeconds(1));
assertFalse(renewal.due(leaf), "a new leaf could end no later, so renewing it would only churn");
when(clock.instant()).thenReturn(caNotAfter);
assertTrue(renewal.due(leaf));
when(clock.instant()).thenReturn(caNotAfter.plusSeconds(1));
assertThrows(CertificateExpiredException.class, () -> renewal.issue(List.of("localhost")));
}
}
@@ -1,9 +1,9 @@
package io.github.hectorvent.floci.config;
import io.github.hectorvent.floci.testing.TlsTrust;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Set;
@@ -14,15 +14,7 @@ final class TlsTestSupport {
private TlsTestSupport() {}
static SSLContext trustOnlyTheCa() throws Exception {
KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());
trust.load(null, null);
trust.setCertificateEntry("floci",
FlociCertificateAuthority.loadOrCreate(Path.of(SelfSignedTlsProfile.TLS_DIR)).certificate());
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(trust);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, factory.getTrustManagers(), null);
return context;
return TlsTrust.trusting(FlociCertificateAuthority.loadOrCreate(Path.of(SelfSignedTlsProfile.TLS_DIR)).certificate());
}
static Set<String> dnsSans(X509Certificate certificate) throws Exception {
@@ -859,7 +859,7 @@ class ElastiCacheIntegrationTest {
}
private static Socket openSocket(int port) throws IOException {
Socket socket = new Socket("localhost", port);
Socket socket = ElastiCacheTestConnections.openSocket("localhost", port);
socket.setSoTimeout(SOCKET_TIMEOUT_MS);
return socket;
}
@@ -275,7 +275,7 @@ class ElastiCachePortSharingIntegrationTest {
* endpoint reaching a different group's proxy produces.
*/
private static String withAuth(int port, String token, String... command) throws IOException {
try (Socket socket = new Socket("localhost", port)) {
try (Socket socket = ElastiCacheTestConnections.openSocket("localhost", port)) {
socket.setSoTimeout(10_000);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
@@ -205,7 +205,7 @@ class ElastiCacheServerlessIntegrationTest {
}
private static Socket socket(ServerlessCache cache) throws IOException {
Socket socket = new Socket(cache.endpoint().address(), cache.endpoint().port());
Socket socket = ElastiCacheTestConnections.openSocket(cache.endpoint().address(), cache.endpoint().port(), !"memcached".equals(cache.engine()));
socket.setSoTimeout(10_000);
return socket;
}
@@ -417,6 +417,21 @@ class ElastiCacheServiceTest {
assertTrue(service.getReplicationGroup("open").getUserGroupIds().isEmpty());
}
@Test
void requiredTransitEncryptionDropsTheUnencryptedConnectionsPreferredTook() {
service.createReplicationGroup("open", "test", AuthMode.NO_AUTH, null, "us-east-1");
service.modifyReplicationGroup("open", null, null,
new ReplicationGroupSettings(null, null, null, null, "preferred", true));
verify(proxyManager, never()).dropUnencryptedConnections(anyString());
service.modifyReplicationGroup("open", null, null,
new ReplicationGroupSettings(null, null, null, null, "required"));
service.modifyReplicationGroup("open", null, null, ReplicationGroupSettings.unchanged());
verify(proxyManager, times(1)).dropUnencryptedConnections("open");
}
@Test
void createReplicationGroupRejectsAnUnknownUserGroupBeforeProvisioning() {
ElastiCacheService.CreateReplicationGroupRequest request = new ElastiCacheService.CreateReplicationGroupRequest(
@@ -0,0 +1,62 @@
package io.github.hectorvent.floci.services.elasticache;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.CacheCluster;
import io.github.hectorvent.floci.services.elasticache.model.ClusterNode;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
import io.github.hectorvent.floci.testing.TlsTrust;
import jakarta.enterprise.inject.spi.CDI;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.net.Socket;
/** Real CA validation for cache data-plane tests; never uses a trust-all manager. */
public final class ElastiCacheTestConnections {
private ElastiCacheTestConnections() {}
static Socket openSocket(String host, int port) throws IOException {
ElastiCacheService service = CDI.current().select(ElastiCacheService.class).get();
for (ReplicationGroup group : service.listReplicationGroups(null)) {
if (!group.isEncryptedInTransit()) {
continue;
}
if (group.getProxyPort() == port) {
return openSocket(host, port, true);
}
for (ClusterNode node : group.getClusterNodes()) {
if (node.getProxyPort() == port) {
return openSocket(host, port, true);
}
}
}
for (CacheCluster cluster : service.findCacheClusters(null)) {
if (cluster.getAuthMode() != AuthMode.NO_AUTH && cluster.getConfigurationEndpoint() != null
&& cluster.getConfigurationEndpoint().port() == port) {
return openSocket(host, port, true);
}
}
return openSocket(host, port, false);
}
static Socket openSocket(String host, int port, boolean encrypted) throws IOException {
if (!encrypted) {
return new Socket(host, port);
}
try {
FlociCertificateAuthority authority = CDI.current().select(FlociCertificateAuthority.class).get();
SSLSocket socket = (SSLSocket) TlsTrust.trusting(authority.certificate()).getSocketFactory()
.createSocket(host, port);
SSLParameters parameters = socket.getSSLParameters();
parameters.setEndpointIdentificationAlgorithm("HTTPS");
socket.setSSLParameters(parameters);
socket.setSoTimeout(10000);
socket.startHandshake();
return socket;
} catch (Exception e) {
throw new IOException("Could not establish a trusted cache TLS connection", e);
}
}
}
@@ -1,6 +1,5 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.testutil.FreePorts;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Test;
@@ -294,7 +293,7 @@ class AbstractRedisAuthProxyHandshakeTest {
private static TestProxy startProxy(ServerSocket backendServer, boolean authRequired,
String username, String password,
int handshakeTimeoutMillis) throws IOException {
int proxyPort = FreePorts.anyInterfacePort();
int proxyPort = 0;
TestProxy proxy = new TestProxy("127.0.0.1", backendServer.getLocalPort(), proxyPort,
authRequired, username, password, handshakeTimeoutMillis);
proxy.start(proxyPort);
@@ -366,7 +365,7 @@ class AbstractRedisAuthProxyHandshakeTest {
}
private int proxyPort() {
return proxyPort;
return localPort();
}
private int authenticationAttempts() {
@@ -0,0 +1,106 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import javax.net.ssl.SSLContext;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ElastiCacheTlsCertificatesTest {
@TempDir
Path directory;
@Test
void concurrentHandshakesRenewAnExpiringLeafOnce() throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
CertificateGenerator generator = spy(new CertificateGenerator());
CertificateGenerator.GeneratedCertificate expiring = new CertificateGenerator().generateIssuedCertificate(
"localhost", List.of("localhost"), KeyAlgorithm.RSA_2048, null, authority.issuer(),
CertificateGenerator.LeafUsage.SERVER, Instant.now().plusSeconds(120));
doReturn(expiring).doCallRealMethod().when(generator)
.generateIssuedCertificate(anyString(), anyList(), eq(KeyAlgorithm.RSA_2048), isNull(),
any(CertificateGenerator.Issuer.class), eq(CertificateGenerator.LeafUsage.SERVER), any(Instant.class));
Clock clock = mock(Clock.class);
when(clock.instant()).thenReturn(expiring.notAfter().minusSeconds(120));
ElastiCacheTlsCertificates certificates = new ElastiCacheTlsCertificates(authority, config(), generator, clock);
SSLContext original = certificates.sslContext();
when(clock.instant()).thenReturn(expiring.notAfter().minusSeconds(61));
assertSame(original, certificates.sslContext());
when(clock.instant()).thenReturn(expiring.notAfter().minusSeconds(60));
List<CompletableFuture<SSLContext>> contexts = IntStream.range(0, 8)
.mapToObj(ignored -> CompletableFuture.supplyAsync(certificates::sslContext)).toList();
SSLContext renewed = contexts.getFirst().get(10, TimeUnit.SECONDS);
assertNotSame(original, renewed);
for (CompletableFuture<SSLContext> context : contexts) {
assertSame(renewed, context.get(10, TimeUnit.SECONDS));
}
assertSame(renewed, certificates.sslContext());
verify(generator, times(2)).generateIssuedCertificate(anyString(), anyList(), eq(KeyAlgorithm.RSA_2048), isNull(),
any(CertificateGenerator.Issuer.class), eq(CertificateGenerator.LeafUsage.SERVER), any(Instant.class));
}
@Test
void failedIssuancePreservesTheCauseAndCanBeRetried() {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
CertificateGenerator generator = spy(new CertificateGenerator());
IllegalStateException failure = new IllegalStateException("certificate setup failed");
doThrow(failure).doCallRealMethod().when(generator)
.generateIssuedCertificate(anyString(), anyList(), eq(KeyAlgorithm.RSA_2048), isNull(),
any(CertificateGenerator.Issuer.class), eq(CertificateGenerator.LeafUsage.SERVER), any(Instant.class));
ElastiCacheTlsCertificates certificates = new ElastiCacheTlsCertificates(authority, config(), generator);
assertSame(failure, assertThrows(IllegalStateException.class, certificates::sslContext).getCause());
assertNotNull(certificates.sslContext());
verify(generator, times(2)).generateIssuedCertificate(anyString(), anyList(), eq(KeyAlgorithm.RSA_2048), isNull(),
any(CertificateGenerator.Issuer.class), eq(CertificateGenerator.LeafUsage.SERVER), any(Instant.class));
}
@Test
void blankConfiguredHostnamesAreSkipped() {
EmulatorConfig config = config();
when(config.hostname()).thenReturn(Optional.of(" "));
when(config.baseUrl()).thenReturn(" ");
when(config.services().elasticache().clusterAnnounceHostname()).thenReturn(Optional.of(" "));
ElastiCacheTlsCertificates certificates = new ElastiCacheTlsCertificates(
FlociCertificateAuthority.loadOrCreate(directory), config, new CertificateGenerator());
assertNotNull(certificates.sslContext());
}
private EmulatorConfig config() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.hostname()).thenReturn(Optional.empty());
when(config.services().elasticache().clusterAnnounceHostname()).thenReturn(Optional.empty());
return config;
}
}
@@ -0,0 +1,280 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.TransitEncryption;
import io.github.hectorvent.floci.testing.TlsTrust;
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.ValueSource;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.ServerSocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ElastiCacheTlsProxyTest {
private static final byte[] AUTH = "*2\r\n$4\r\nAUTH\r\n$18\r\nsynthetic-password\r\n"
.getBytes(StandardCharsets.UTF_8);
private static final byte[] PING = "*1\r\n$4\r\nPING\r\n".getBytes(StandardCharsets.UTF_8);
@TempDir
Path directory;
private ElastiCacheAuthProxy proxy(FlociCertificateAuthority authority, int backendPort) {
return proxy(authority, backendPort, () -> TransitEncryption.REQUIRED);
}
private ElastiCacheAuthProxy proxy(FlociCertificateAuthority authority, int backendPort,
Supplier<TransitEncryption> encryption) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.hostname()).thenReturn(Optional.of("cache.test"));
when(config.baseUrl()).thenReturn("https://base.test:4566");
when(config.services().elasticache().clusterAnnounceHostname()).thenReturn(Optional.of("nodes.test"));
ElastiCacheTlsCertificates certificates = new ElastiCacheTlsCertificates(authority, config, new CertificateGenerator());
return new ElastiCacheAuthProxy("tls-test", AuthMode.PASSWORD, "127.0.0.1", backendPort,
new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return "synthetic-password".equals(password);
}
@Override
public TransitEncryption transitEncryption() {
return encryption.get();
}
}, mock(SigV4Validator.class), certificates::sslContext);
}
@ParameterizedTest
@ValueSource(strings = {"cache.test", "nodes.test", "base.test", "host.docker.internal",
"localhost", "127.0.0.1", "0.0.0.0", "::1", "localhost.floci.io"})
void tlsVerifiesTheSharedCaAndEndpointNameThenAuthenticatesAndRelays(String hostname) throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
try (ServerSocket backend = new ServerSocket(0)) {
CompletableFuture<String> received = CompletableFuture.supplyAsync(() -> {
try (Socket socket = backend.accept()) {
socket.setSoTimeout(5000);
String[] command = new RespReader(socket.getInputStream()).readCommand();
socket.getOutputStream().write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
socket.getOutputStream().flush();
return command[0];
} catch (Exception e) {
throw new IllegalStateException(e);
}
});
ElastiCacheAuthProxy proxy = proxy(authority, backend.getLocalPort());
proxy.start(0);
try (Socket client = tlsClient(authority, proxy.localPort(), hostname)) {
BufferedReader reader = reader(client);
assertEquals("+OK", send(client, reader, AUTH));
assertEquals("+PONG", send(client, reader, PING));
assertEquals("PING", received.get(5, TimeUnit.SECONDS));
} finally {
proxy.stop();
}
}
}
@Test
void encryptedEndpointRejectsPlaintextBeforeBackendAccess() throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
try (ServerSocketChannel backend = idleBackend()) {
ElastiCacheAuthProxy proxy = proxy(authority, backendPort(backend));
proxy.start(0);
try (Socket client = plaintextClient(proxy.localPort())) {
client.getOutputStream().write(PING);
client.getOutputStream().flush();
// A fatal TLS alert or EOF is acceptable; no RESP success can be returned.
int first = client.getInputStream().read();
assertTrue(first == -1 || first == 21);
awaitProxyClose(client);
assertNull(backend.accept(), "a refused client must not reach the backend");
} finally {
proxy.stop();
}
}
}
@Test
void rejectsAnUntrustedCaAndAnIncorrectEndpointName() throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory.resolve("server"));
FlociCertificateAuthority wrong = FlociCertificateAuthority.loadOrCreate(directory.resolve("untrusted"));
try (ServerSocketChannel backend = idleBackend()) {
ElastiCacheAuthProxy proxy = proxy(authority, backendPort(backend));
proxy.start(0);
int port = proxy.localPort();
try {
for (boolean wrongName : new boolean[]{false, true}) {
SSLContext context = TlsTrust.trusting((wrongName ? authority : wrong).certificate());
// autoClose off: tcp stays open after the refusal, so the proxy's close can be seen
try (Socket tcp = plaintextClient(port);
SSLSocket client = (SSLSocket) context.getSocketFactory().createSocket(tcp,
wrongName ? "wrong.test" : "cache.test", port, false)) {
verifyEndpointName(client);
assertThrows(IOException.class, client::startHandshake);
awaitProxyClose(tcp);
}
}
assertNull(backend.accept(), "a refused client must not reach the backend");
} finally {
proxy.stop();
}
}
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void preferredModeTakesEncryptedAndUnencryptedClients(boolean encrypted) throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
try (ServerSocket backend = new ServerSocket(0)) {
answerEveryCommandWithPong(backend);
ElastiCacheAuthProxy proxy = proxy(authority, backend.getLocalPort(), () -> TransitEncryption.PREFERRED);
proxy.start(0);
try (Socket client = encrypted
? tlsClient(authority, proxy.localPort(), "cache.test")
: plaintextClient(proxy.localPort())) {
BufferedReader reader = reader(client);
assertEquals("+OK", send(client, reader, AUTH));
assertEquals("+PONG", send(client, reader, PING));
} finally {
proxy.stop();
}
}
}
@Test
void requiredModeDropsUnencryptedConnectionsAndKeepsEncryptedOnes() throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
AtomicReference<TransitEncryption> mode = new AtomicReference<>(TransitEncryption.PREFERRED);
try (ServerSocket backend = new ServerSocket(0)) {
answerEveryCommandWithPong(backend);
ElastiCacheAuthProxy proxy = proxy(authority, backend.getLocalPort(), mode::get);
proxy.start(0);
try (Socket plaintext = plaintextClient(proxy.localPort());
Socket encrypted = tlsClient(authority, proxy.localPort(), "cache.test")) {
BufferedReader plaintextReader = reader(plaintext);
BufferedReader encryptedReader = reader(encrypted);
assertEquals("+OK", send(plaintext, plaintextReader, AUTH));
assertEquals("+PONG", send(plaintext, plaintextReader, PING));
assertEquals("+OK", send(encrypted, encryptedReader, AUTH));
assertEquals("+PONG", send(encrypted, encryptedReader, PING));
mode.set(TransitEncryption.REQUIRED);
proxy.dropUnencryptedConnections();
assertNull(plaintextReader.readLine(), "the unencrypted connection must be closed");
assertEquals("+PONG", send(encrypted, encryptedReader, PING));
} finally {
proxy.stop();
}
}
}
private static SSLSocket tlsClient(FlociCertificateAuthority authority, int port, String hostname) throws Exception {
Socket tcp = plaintextClient(port);
SSLSocket client = (SSLSocket) TlsTrust.trusting(authority.certificate()).getSocketFactory()
.createSocket(tcp, hostname, port, true);
verifyEndpointName(client);
client.startHandshake();
return client;
}
private static Socket plaintextClient(int port) throws IOException {
Socket client = new Socket("127.0.0.1", port);
client.setSoTimeout(5000);
return client;
}
private static void verifyEndpointName(SSLSocket client) {
SSLParameters parameters = client.getSSLParameters();
parameters.setEndpointIdentificationAlgorithm("HTTPS");
client.setSSLParameters(parameters);
}
private static BufferedReader reader(Socket client) throws IOException {
return new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
}
private static String send(Socket client, BufferedReader reader, byte[] command) throws IOException {
client.getOutputStream().write(command);
client.getOutputStream().flush();
return reader.readLine();
}
/** Returns once the proxy has closed the connection, so it has finished with the client. */
private static void awaitProxyClose(Socket tcp) throws IOException {
InputStream in = tcp.getInputStream();
try {
while (in.read() != -1) {
// drains whatever the proxy sent before closing, a TLS alert for one
}
} catch (SocketException expected) {
// a reset closes the connection as well
}
}
/** A backend that only accepts without blocking, so a check for a connection answers at once. */
private static ServerSocketChannel idleBackend() throws IOException {
ServerSocketChannel backend = ServerSocketChannel.open().bind(new InetSocketAddress("127.0.0.1", 0));
backend.configureBlocking(false);
return backend;
}
private static int backendPort(ServerSocketChannel backend) throws IOException {
return ((InetSocketAddress) backend.getLocalAddress()).getPort();
}
/** Answers every command on every relayed connection with PONG, until the backend is closed. */
private static void answerEveryCommandWithPong(ServerSocket backend) {
Thread.ofVirtual().start(() -> {
while (!backend.isClosed()) {
try {
Socket relayed = backend.accept();
Thread.ofVirtual().start(() -> answerWithPong(relayed));
} catch (IOException expected) {
// the test closed the backend
}
}
});
}
private static void answerWithPong(Socket relayed) {
try (relayed) {
RespReader reader = new RespReader(relayed.getInputStream());
while (true) {
reader.readCommand();
relayed.getOutputStream().write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
relayed.getOutputStream().flush();
}
} catch (IOException expected) {
// the proxy closed the relay, which ends the stream
}
}
}
@@ -0,0 +1,24 @@
package io.github.hectorvent.floci.testing;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
/** A client TLS context that trusts one CA and nothing else, so a test sees real verification. */
public final class TlsTrust {
private TlsTrust() {
}
public static SSLContext trusting(X509Certificate ca) throws Exception {
KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());
trust.load(null, null);
trust.setCertificateEntry("floci", ca);
TrustManagerFactory managers = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
managers.init(trust);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, managers.getTrustManagers(), null);
return context;
}
}