fix(elbv2): route shared HTTPS to ALBs by server name (#9767)

With TLS on, Floci's TLS proxy holds floci.tls.aws-https-port (443 by
default) for AWS API calls and cfn-response callbacks, so an ALB HTTPS
listener on that port could not bind it and received no traffic, where
AWS serves it.

- an HTTPS listener on the proxy's port is served on loopback, and the
  proxy reads the ClientHello's SNI without terminating TLS and hands the
  connection to the listener that claims the name; Floci's own endpoint
  names, no SNI and unclaimed names stay with Floci
- the proxy waits for a whole ClientHello only while such a listener is
  served behind it, from one deadline armed by the first bytes, and sends
  anything else to Floci on its first bytes as before
- each proxied connection is pinned to the listener its ClientHello
  selected, and carries the client the proxy accepted it from, so targets
  see the client in X-Forwarded-For and X-Forwarded-Port names the
  listener's port
- the proxy and the embedded DNS server share one list of Floci's DNS
  suffixes
- a failing route lookup is logged at warn, and the connection goes to
  Floci

Refs #8613

Co-authored-by: Jonathan Morley <jonathanmorley@users.noreply.github.com>
This commit is contained in:
Priamo GermosenandJonathan Morley authored and GitHub committed 2026-11-29 15:12:09 -04:00
1 parent 4328882f67
commit 3a0cce0188
14 files changed
+1353 -75

No files matched your search

+3
View File
@@ -134,6 +134,9 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on
bind resets the delay. Deleting the last listener or stopping Floci cancels its retry.
An external process holding the port must still release it before Floci can serve traffic.
- HTTPS listeners terminate TLS using the configured ACM or IAM server certificates, with SNI certificate selection. When several load balancers share one local HTTPS port, clients must send SNI to identify the certificate they need; a connection without SNI cannot identify a particular load balancer before the TLS handshake.
- With TLS enabled, Floci's TLS proxy holds `floci.tls.aws-https-port` (443 by default) for AWS API calls and CloudFormation `cfn-response` callbacks. While an HTTPS listener is on that port, the proxy reads the ClientHello's SNI without terminating TLS; otherwise it hands each connection to Floci on its first bytes. Floci's own endpoint names, including `localhost.floci.io` and configured API and callback hosts, take precedence over ALB claims. This includes the exact hostname in `floci.services.iot.endpoint-address` regardless of its configured port or DNS suffix. Under Floci's endpoint DNS suffixes, the proxy routes to an ALB only for its generated DNS name. For other names it also accepts an ALB certificate hostname or a hostname declared by a `host-header` rule. Connections without SNI and unclaimed names go to Floci.
- The proxy can assemble the first TLS record across TCP segments. A ClientHello split across multiple TLS records goes to Floci. A proxied connection stays with the listener selected from its ClientHello, even if that listener loses the SNI claim or the TLS session exposes no requested SNI after resumption. Requests on the connection return `502` if the selected listener is removed and the connection remains open. A resumed handshake whose ClientHello omits SNI goes to Floci at the proxy.
- Targets behind an ALB on the AWS-HTTPS port see the client's address in `X-Forwarded-For`, not the proxy's. HTTP and TCP listeners on that port serve no traffic. Set `floci.tls.aws-https-port=0` to give them the port.
- ACM certificates must be issued before attaching them. Reimporting an attached ACM certificate refreshes subsequent full TLS handshakes; existing connections keep their negotiated certificate. Reload does not invalidate TLS session caches: a resumed session can retain its previously authenticated certificate after replacement or removal until the session expires or is invalidated. ACM deletion and revocation are refused while a listener still references the certificate.
- Certificate replacement keeps the previous key material available to new handshakes while the replacement loads. A failed reload leaves the previous certificate active.
- Unusable saved listeners are retained for correction and logged individually so other saved listeners can start.
@@ -0,0 +1,102 @@
package io.floci.aws.config;
import io.vertx.core.buffer.Buffer;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
/**
* Reads the SNI server name from a TLS ClientHello without terminating TLS.
*
* <p>Only the first TLS record is read. A client may split its ClientHello across several records
* at any size; when the server name extension is not in the first one, or the first record is
* cut short, there is no name and the connection keeps its default route.
*/
final class TlsClientHello {
private static final int RECORD_HEADER = 5;
private static final int MAX_RECORD = 16384;
private static final int HANDSHAKE_CLIENT_HELLO = 1;
private static final int EXTENSION_SERVER_NAME = 0;
private static final int NAME_TYPE_HOST = 0;
private TlsClientHello() {
}
/** Whether {@code data} starts a handshake record that has not fully arrived yet. */
static boolean needsMore(Buffer data) {
if (data.length() == 0 || data.getByte(0) != TlsProxyServer.TLS_HANDSHAKE) {
return false;
}
if (data.length() < RECORD_HEADER) {
return true;
}
int length = data.getUnsignedShort(3);
return length <= MAX_RECORD && data.length() < RECORD_HEADER + length;
}
/** The lower-cased host name the client asked for, or null when absent, incomplete or malformed. */
static String serverName(Buffer data) {
try {
ByteBuffer in = ByteBuffer.wrap(data.getBytes());
if (in.get() != TlsProxyServer.TLS_HANDSHAKE) {
return null;
}
in.getShort();
ByteBuffer record = slice(in, Short.toUnsignedInt(in.getShort()));
if (record.get() != HANDSHAKE_CLIENT_HELLO) {
return null;
}
ByteBuffer hello = slice(record, (Byte.toUnsignedInt(record.get()) << 16) | Short.toUnsignedInt(record.getShort()));
skip(hello, 2 + 32);
skip(hello, Byte.toUnsignedInt(hello.get()));
skip(hello, Short.toUnsignedInt(hello.getShort()));
skip(hello, Byte.toUnsignedInt(hello.get()));
if (!hello.hasRemaining()) {
return null;
}
ByteBuffer extensions = slice(hello, Short.toUnsignedInt(hello.getShort()));
while (extensions.hasRemaining()) {
int type = Short.toUnsignedInt(extensions.getShort());
ByteBuffer extension = slice(extensions, Short.toUnsignedInt(extensions.getShort()));
if (type == EXTENSION_SERVER_NAME) {
return hostName(slice(extension, Short.toUnsignedInt(extension.getShort())));
}
}
return null;
} catch (BufferUnderflowException | IllegalArgumentException malformed) {
return null;
}
}
private static String hostName(ByteBuffer names) {
while (names.hasRemaining()) {
int type = Byte.toUnsignedInt(names.get());
ByteBuffer name = slice(names, Short.toUnsignedInt(names.getShort()));
if (type == NAME_TYPE_HOST) {
String host = StandardCharsets.US_ASCII.decode(name).toString().toLowerCase(Locale.ROOT);
if (host.endsWith(".")) {
host = host.substring(0, host.length() - 1);
}
return !host.isEmpty() && host.chars().allMatch(c -> c == '.' || c == '-'
|| (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) ? host : null;
}
}
return null;
}
private static ByteBuffer slice(ByteBuffer in, int length) {
if (length > in.remaining()) {
throw new BufferUnderflowException();
}
ByteBuffer part = in.slice(in.position(), length);
in.position(in.position() + length);
return part;
}
private static void skip(ByteBuffer in, int length) {
slice(in, length);
}
}
@@ -507,10 +507,8 @@ public class TlsConfigSource implements ConfigSource {
String iotEndpoint = resolveProperty("floci.services.iot.endpoint-address", "").strip();
if (!iotEndpoint.isEmpty()) {
try {
// Anything beyond host[:port] is a typo: java.net.URI would read "https" as the host of a URL.
URI uri = new URI("//" + iotEndpoint);
String host = uri.getHost();
if (host == null || uri.getUserInfo() != null || !iotEndpoint.equals(uri.getRawAuthority())) {
String host = iotEndpointHost(iotEndpoint);
if (host == null) {
LOG.warnv("TLS: floci.services.iot.endpoint-address is not a host or host:port, not added to the certificate: {0}",
iotEndpoint);
} else if (!isDefaultHostname(host)) {
@@ -530,6 +528,13 @@ public class TlsConfigSource implements ConfigSource {
return result;
}
/** Extracts the host from an IoT endpoint address in host[:port] form. */
static String iotEndpointHost(String endpointAddress) throws URISyntaxException {
String authority = endpointAddress.strip();
URI uri = new URI("//" + authority);
return uri.getUserInfo() == null && authority.equals(uri.getRawAuthority()) ? uri.getHost() : null;
}
/**
* Checks if a hostname is a default value that should be filtered out.
*
@@ -1,27 +1,38 @@
package io.floci.aws.config;
import io.floci.aws.core.common.DomainNames;
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
import io.quarkus.runtime.Startup;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;
import io.vertx.core.net.NetSocket;
import io.vertx.core.net.SocketAddress;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.eclipse.microprofile.config.Config;
import org.jboss.logging.Logger;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;
/**
* A TCP proxy server that enables HTTP and HTTPS on the same port (LocalStack parity).
@@ -44,6 +55,10 @@ import java.util.function.IntConsumer;
* so they PUT to 443 regardless of Floci's configured port; binding 443 lets those callbacks
* reach Floci. The extra binding is skipped when the port is {@code 0} or equals the public port.
*
* <p>While a load balancer HTTPS listener is served behind that extra port, a ClientHello there whose SNI
* server name the listener claims goes to it instead, without terminating TLS: see
* {@link #routeServerNames}. Floci's endpoint names, no SNI, and unclaimed names keep the Floci route above.
*
* <p>Both listen on the configured {@code quarkus.http.host}, not the loopback pin
* {@link TlsConfigSource} applies to Quarkus itself, and a non-loopback host needs the same consent
* as without TLS; see {@link NetworkExposureGuard}.
@@ -62,13 +77,17 @@ public class TlsProxyServer {
private static final int HTTP_BACKEND_PORT = TlsConfigSource.HTTP_INTERNAL_PORT;
private static final int HTTPS_BACKEND_PORT = TlsConfigSource.HTTPS_INTERNAL_PORT;
private static final long CLIENT_HELLO_TIMEOUT_MILLIS = 5_000;
private final Vertx vertx;
private final EmulatorConfig config;
private final String host;
private final int httpBackendPort;
private final int httpsBackendPort;
private final Set<String> endpointHosts = new LinkedHashSet<>();
private final Set<String> endpointSuffixes = new LinkedHashSet<>();
private final List<NetServer> proxyServers = new ArrayList<>();
private Future<NetServer> awsHttpsBind;
/**
* Ports whose bind definitively failed. Absent means bound, or not resolved yet: callers
* default to treating the port as the proxy's until the outcome is known, which is what stops
@@ -89,19 +108,87 @@ public class TlsProxyServer {
failedPorts.forEach(handler::accept);
}
private NetClient client;
private volatile ServerNameRouting serverNameRouting;
private final Map<BackendConnection, Pin> pins = new ConcurrentHashMap<>();
private final ClientHelloDeadline clientHelloDeadline;
/** Picks the local port that serves a TLS server name arriving on a proxy port. */
@FunctionalInterface
public interface ServerNameRoute {
/**
* The backend target, or null for none. When {@code allowAliases} is false,
* only a load balancer's own generated DNS name can claim the connection.
*/
ServerNameTarget resolve(int listenPort, String serverName, boolean allowAliases);
}
public record ServerNameTarget(int port, String routeId) {}
/** The route a loopback connection was pinned to from its ClientHello, and the client it was accepted from. */
public record PinnedRoute(String routeId, SocketAddress client) {}
/** Arms the one deadline a partial ClientHello has to complete by, from its first bytes. */
interface ClientHelloDeadline {
long arm(Runnable expired);
void cancel(long id);
static ClientHelloDeadline after(Vertx vertx, long millis) {
return new ClientHelloDeadline() {
@Override
public long arm(Runnable expired) {
return vertx.setTimer(millis, id -> expired.run());
}
@Override
public void cancel(long id) {
vertx.cancelTimer(id);
}
};
}
}
private record ServerNameRouting(IntPredicate claimsServerNames, ServerNameRoute route) {}
private record BackendConnection(int port, SocketAddress peer) {}
private record Pin(NetSocket backSocket, PinnedRoute route) {}
/**
* Sends ClientHellos on the AWS-HTTPS port whose SNI the route claims to the port it names. A connection
* waits for its whole ClientHello only while {@code claimsServerNames} holds for the port; otherwise it is
* dispatched on its first bytes.
*/
public void routeServerNames(IntPredicate claimsServerNames, ServerNameRoute route) {
serverNameRouting = new ServerNameRouting(claimsServerNames, route);
}
/** Returns the route selected from the ClientHello for this loopback connection, or null. */
public PinnedRoute pinnedRoute(int backendPort, SocketAddress peer) {
Pin pin = pins.get(new BackendConnection(backendPort, peer));
return pin == null ? null : pin.route();
}
@Inject
public TlsProxyServer(Vertx vertx, EmulatorConfig config, Config mpConfig) {
this(vertx, config, NetworkExposureGuard.publicHost(mpConfig), HTTP_BACKEND_PORT, HTTPS_BACKEND_PORT);
}
/** Visible for testing — lets tests point the proxy at backends on non-default ports. */
/** Visible for testing: lets tests point the proxy at backends on non-default ports. */
TlsProxyServer(Vertx vertx, EmulatorConfig config, String host, int httpBackendPort, int httpsBackendPort) {
this(vertx, config, host, httpBackendPort, httpsBackendPort,
ClientHelloDeadline.after(vertx, CLIENT_HELLO_TIMEOUT_MILLIS));
}
/** Visible for testing: lets tests fire the ClientHello deadline themselves. */
TlsProxyServer(Vertx vertx, EmulatorConfig config, String host, int httpBackendPort, int httpsBackendPort,
ClientHelloDeadline clientHelloDeadline) {
this.vertx = vertx;
this.config = config;
this.host = host;
this.httpBackendPort = httpBackendPort;
this.httpsBackendPort = httpsBackendPort;
this.clientHelloDeadline = clientHelloDeadline;
startIfTlsEnabled();
}
@@ -112,17 +199,22 @@ public class TlsProxyServer {
NetworkExposureGuard.requireConsent(host, config.security());
if (config.tls().awsHttpsPort() > 0 && config.tls().awsHttpsPort() != config.port()) {
configureEndpointNames();
}
client = vertx.createNetClient();
Handler<NetSocket> connectHandler = buildConnectHandler();
for (int port : listenPorts()) {
NetServerOptions options = new NetServerOptions()
.setHost(host)
.setPort(port);
NetServer server = vertx.createNetServer(options);
server.connectHandler(connectHandler);
server.connectHandler(buildConnectHandler(port));
proxyServers.add(server);
Future<NetServer> bind = server.listen();
if (port != config.port()) {
awsHttpsBind = bind;
}
bind.onComplete(ar -> {
if (ar.succeeded()) {
failedPorts.remove(port);
@@ -155,6 +247,50 @@ public class TlsProxyServer {
}
}
private void configureEndpointNames() {
endpointHosts.addAll(TlsConfigSource.defaultEndpointHostnames());
Set<String> suffixes = new LinkedHashSet<>(EmbeddedDnsServer.emulatorSuffixes(config));
suffixes.add("localhost");
try {
String baseHost = URI.create(config.baseUrl()).getHost();
if (baseHost != null) {
suffixes.add(baseHost);
}
} catch (IllegalArgumentException e) {
LOG.debugv(e, "TLS proxy: cannot read the hostname from floci.base-url");
}
config.services().lambda().dockerHostOverride().map(TlsProxyServer::normalizeHost).ifPresent(endpointHosts::add);
config.services().iot().endpointAddress().filter(address -> !address.isBlank()).ifPresent(address -> {
try {
String iotHost = TlsConfigSource.iotEndpointHost(address);
if (iotHost != null) {
endpointHosts.add(normalizeHost(iotHost));
}
} catch (URISyntaxException e) {
LOG.debugv("TLS proxy: cannot read the hostname from floci.services.iot.endpoint-address: {0}",
e.getReason());
}
});
suffixes.stream().map(TlsProxyServer::normalizeHost).filter(suffix -> !suffix.isEmpty())
.forEach(endpointSuffixes::add);
endpointHosts.addAll(endpointSuffixes);
}
private static String normalizeHost(String host) {
String name = host.strip().toLowerCase(Locale.ROOT);
return name.endsWith(".") ? name.substring(0, name.length() - 1) : name;
}
/** Completes with the actual listening port, or fails with the reason a socket was never bound. */
public Future<Integer> boundAwsHttpsPort() {
if (awsHttpsBind == null) {
return Future.failedFuture("TLS proxy did not attempt a separate AWS-HTTPS bind (tls.enabled="
+ config.tls().enabled() + ", tls.aws-https-port=" + config.tls().awsHttpsPort()
+ ", public port=" + config.port() + ")");
}
return awsHttpsBind.map(NetServer::actualPort);
}
/**
* Whether the proxy holds, or is still expected to hold, {@code port}.
*
@@ -184,48 +320,55 @@ public class TlsProxyServer {
}
/**
* Builds the shared connect handler that peeks the first byte to detect TLS and pipes the
* connection to the matching backend. A single instance is reused across all listen ports.
* Builds the connect handler that peeks the first bytes to detect TLS and pipes the connection
* to the matching backend. On the AWS-HTTPS port, while a load balancer listener is served behind it, it
* buffers a whole ClientHello record first so the listener can claim the connection by its SNI server name.
*/
private Handler<NetSocket> buildConnectHandler() {
private Handler<NetSocket> buildConnectHandler(int listenPort) {
return frontSocket -> {
// Pause incoming data until we've peeked at the first byte
// Pause incoming data until we've peeked at the first bytes
frontSocket.pause();
Buffer buffer = Buffer.buffer();
ServerNameRoute route = serverNameRoute(listenPort);
AtomicBoolean dispatched = new AtomicBoolean();
AtomicLong helloDeadline = new AtomicLong(-1);
Runnable cancelDeadline = () -> {
long id = helloDeadline.get();
if (id != -1) {
clientHelloDeadline.cancel(id);
}
};
frontSocket.closeHandler(ignored -> {
dispatched.set(true);
cancelDeadline.run();
});
frontSocket.handler(buffer -> {
Runnable dispatch = () -> {
if (!dispatched.compareAndSet(false, true)) {
return;
}
cancelDeadline.run();
// Remove handler and keep socket paused to prevent data loss
// while we establish the backend connection.
frontSocket.handler(null);
frontSocket.pause();
boolean tls = buffer.length() > 0 && buffer.getByte(0) == TLS_HANDSHAKE;
ServerNameTarget target = tls ? serverNameTarget(listenPort, route, buffer) : null;
int backendPort = target == null ? (tls ? httpsBackendPort : httpBackendPort) : target.port();
pipeToBackend(frontSocket, buffer, backendPort, target);
};
// Inspect first byte to determine protocol
int backendPort;
if (buffer.length() > 0 && buffer.getByte(0) == TLS_HANDSHAKE) {
backendPort = httpsBackendPort;
} else {
backendPort = httpBackendPort;
}
// Connect to the appropriate backend
client.connect(backendPort, "127.0.0.1").onComplete(ar -> {
if (ar.succeeded()) {
NetSocket backSocket = ar.result();
// Send the initial buffer that we already read
backSocket.write(buffer);
// Bi-directional pipe — pipeTo handles end-of-stream
// propagation and will resume the paused frontSocket.
frontSocket.pipeTo(backSocket).onFailure(err ->
LOG.debugv("TLS proxy: pipe front→back failed: {0}", err.getMessage()));
backSocket.pipeTo(frontSocket).onFailure(err ->
LOG.debugv("TLS proxy: pipe back→front failed: {0}", err.getMessage()));
} else {
LOG.warnv("TLS proxy: failed to connect to backend port {0}: {1}",
String.valueOf(backendPort), ar.cause().getMessage());
frontSocket.close();
frontSocket.handler(chunk -> {
buffer.appendBuffer(chunk);
if (route != null && TlsClientHello.needsMore(buffer)) {
// One deadline from the first partial chunk, never extended: a client that
// stalls or trickles its ClientHello is served by Floci rather than held open.
if (helloDeadline.get() == -1) {
helloDeadline.set(clientHelloDeadline.arm(dispatch));
}
});
return;
}
dispatch.run();
});
// Resume to receive the first buffer
@@ -233,6 +376,59 @@ public class TlsProxyServer {
};
}
/** The route for a connection on {@code listenPort}, or null when no listener there can claim it by name. */
private ServerNameRoute serverNameRoute(int listenPort) {
ServerNameRouting routing = serverNameRouting;
if (listenPort == config.port() || routing == null || !routing.claimsServerNames().test(listenPort)) {
return null;
}
return routing.route();
}
private ServerNameTarget serverNameTarget(int listenPort, ServerNameRoute route, Buffer buffer) {
String serverName = route == null ? null : TlsClientHello.serverName(buffer);
if (serverName == null || endpointHosts.contains(serverName)) {
return null;
}
boolean allowAliases = endpointSuffixes.stream().noneMatch(suffix -> DomainNames.isWithin(serverName, suffix));
try {
return route.resolve(listenPort, serverName, allowAliases);
} catch (RuntimeException failure) {
LOG.warnv(failure, "TLS proxy: routing server name {0} failed; Floci serves it", serverName);
return null;
}
}
private void pipeToBackend(NetSocket frontSocket, Buffer buffer, int port, ServerNameTarget target) {
// Connect to the appropriate backend
client.connect(port, "127.0.0.1").onComplete(ar -> {
if (ar.succeeded()) {
NetSocket backSocket = ar.result();
if (target != null) {
BackendConnection connection = new BackendConnection(port, backSocket.localAddress());
Pin pin = new Pin(backSocket, new PinnedRoute(target.routeId(), frontSocket.remoteAddress()));
// Publish before sending the ClientHello so the backend can read the pin on its first request.
pins.put(connection, pin);
backSocket.closeHandler(ignored -> pins.remove(connection, pin));
}
// Send the initial buffer that we already read
backSocket.write(buffer);
// Bi-directional pipe: pipeTo handles end-of-stream
// propagation and will resume the paused frontSocket.
frontSocket.pipeTo(backSocket).onFailure(err ->
LOG.debugv("TLS proxy: pipe front→back failed: {0}", err.getMessage()));
backSocket.pipeTo(frontSocket).onFailure(err ->
LOG.debugv("TLS proxy: pipe back→front failed: {0}", err.getMessage()));
} else {
LOG.warnv("TLS proxy: failed to connect to backend port {0}: {1}",
String.valueOf(port), ar.cause().getMessage());
frontSocket.close();
}
});
}
@PreDestroy
void stop() {
for (NetServer server : proxyServers) {
@@ -201,18 +201,27 @@ public class EmbeddedDnsServer {
}
}
private void prepare(EmulatorConfig config) {
upstreamDnsServers = composeUpstreams(readResolvConfNameservers(), config.dns().containerFallbackServers());
suffixes.addAll(BUILTIN_SUFFIXES);
/**
* The suffixes Floci resolves to itself: the built-in ones, {@code floci.hostname}, the extra suffixes
* and, with {@code floci.dns.spoof-aws-endpoints}, every AWS endpoint suffix.
*/
public static SequencedSet<String> emulatorSuffixes(EmulatorConfig config) {
SequencedSet<String> suffixes = new LinkedHashSet<>(BUILTIN_SUFFIXES);
config.hostname().ifPresent(suffixes::add);
LocalStackParity.withDnsSuffixes(config.dns().extraSuffixes()).ifPresent(suffixes::addAll);
if (config.dns().spoofAwsEndpoints()) {
suffixes.addAll(TlsConfigSource.awsEndpointSuffixes());
if (shouldWarnSpoofInvisibleToTls(true, TlsConfigSource.tlsEnabledVisibleToTls(),
TlsConfigSource.spoofAwsEndpointsVisibleToTls())) {
LOG.warnv("floci.dns.spoof-aws-endpoints is set in application config but the TLS certificate only reads it from FLOCI_DNS_SPOOF_AWS_ENDPOINTS or -Dfloci.dns.spoof-aws-endpoints; https:// calls to {0} will fail the handshake until it is set there.", TlsConfigSource.awsEndpointSuffixes());
}
}
return suffixes;
}
private void prepare(EmulatorConfig config) {
upstreamDnsServers = composeUpstreams(readResolvConfNameservers(), config.dns().containerFallbackServers());
suffixes.addAll(emulatorSuffixes(config));
if (config.dns().spoofAwsEndpoints() && shouldWarnSpoofInvisibleToTls(true,
TlsConfigSource.tlsEnabledVisibleToTls(), TlsConfigSource.spoofAwsEndpointsVisibleToTls())) {
LOG.warnv("floci.dns.spoof-aws-endpoints is set in application config but the TLS certificate only reads it from FLOCI_DNS_SPOOF_AWS_ENDPOINTS or -Dfloci.dns.spoof-aws-endpoints; https:// calls to {0} will fail the handshake until it is set there.", TlsConfigSource.awsEndpointSuffixes());
}
}
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.TlsProxyServer;
import io.floci.aws.config.TlsProxyServer.PinnedRoute;
import io.floci.aws.config.TlsProxyServer.ServerNameTarget;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.CertificateReferenceResolver;
@@ -47,6 +49,7 @@ import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;
import io.vertx.core.net.NetSocket;
import io.vertx.core.net.PemKeyCertOptions;
import io.vertx.core.net.SocketAddress;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
@@ -162,6 +165,10 @@ public class ElbV2DataPlane {
private long bindRetryTimer = -1;
private long bindRetryDelay = INITIAL_BIND_RETRY_MILLIS;
private ReloadingKeyManager tlsKeyManager;
/** The server listens on loopback behind the TLS proxy, which holds the public port. */
private volatile boolean behindProxy;
/** Its loopback port once listening, which the proxy forwards claimed SNI names to; 0 otherwise. */
private volatile int serverNamePort;
private volatile RoutingView routing = new RoutingView(Map.of(), Map.of());
}
@@ -480,6 +487,8 @@ public class ElbV2DataPlane {
* HTTP and hung every {@code Custom::} resource - and the reverse on a fresh start. Yielding
* here makes the outcome deterministic and keeps the emulator's own control path working. To
* give 443 to load balancers instead, set {@code floci.tls.aws-https-port=0} or disable TLS.
* An HTTPS listener on a port the proxy holds is served on loopback instead, and the proxy
* forwards it the connections whose SNI server name it claims.
*/
// Package-private for ElbV2ReservedPortTest.
boolean isReservedByFloci(int port) {
@@ -548,7 +557,12 @@ public class ElbV2DataPlane {
PortState state = portStates.get(port);
if (state != null) {
onCurrentPort(port, state, () -> {
if (listenersByHostAndPort.containsKey(port)) {
if (!listenersByHostAndPort.containsKey(port)) {
return;
}
if (state.behindProxy && servers.containsKey(port)) {
restartPortServer(port);
} else {
ensurePortServer(port);
}
});
@@ -569,6 +583,7 @@ public class ElbV2DataPlane {
private void ensureReleaseHandlerRegistered() {
if (releaseHandlerRegistered.compareAndSet(false, true)) {
tlsProxyServer.onPortReleased(this::bindListenersWaitingOn);
tlsProxyServer.routeServerNames(this::servesBehindProxy, this::serverNameTarget);
}
}
@@ -581,14 +596,44 @@ public class ElbV2DataPlane {
}
}
/**
* The loopback port and identity of the HTTPS listener behind the TLS proxy that claims {@code serverName}
* on {@code port}, by the same selection as a Host header but without the sole-listener
* fallback. Inside Floci's endpoint suffixes, only a load balancer's generated DNS name
* can claim the connection.
*/
private ServerNameTarget serverNameTarget(int port, String serverName, boolean allowAliases) {
PortState state = portStates.get(port);
int backend = state == null ? 0 : state.serverNamePort;
if (backend <= 0) {
return null;
}
RoutingView routing = state.routing;
if (!allowAliases) {
String arn = routing.hosts().get(serverName);
return arn == null ? null : new ServerNameTarget(backend, arn);
}
RoutedListener listener = resolveListener(routing, serverName, false);
return listener == null ? null : new ServerNameTarget(backend, listener.arn());
}
/** Whether an HTTPS listener on {@code port} is listening on loopback behind the TLS proxy right now. */
private boolean servesBehindProxy(int port) {
PortState state = portStates.get(port);
return state != null && state.serverNamePort > 0;
}
private void startPortServer(int port, PortState state) {
if (isReservedByFloci(port)) {
boolean behindProxy = isReservedByFloci(port) && port != config.port() && portIsSecure(port)
&& servedBindings(port).noneMatch(ListenerBinding::tcp);
if (isReservedByFloci(port) && !behindProxy) {
// Returning null leaves `servers` untouched: computeIfAbsent skips a null mapping.
// The emulator's own port cannot be handed over, so the two cases need different
// advice: freeing floci.tls.aws-https-port is only meaningful for the TLS proxy.
String remedy = port == config.port()
? "This is the emulator's own port, so it cannot be freed; give the listener a different port."
: "Set floci.tls.aws-https-port=0 (or disable TLS) to free it.";
: "Only HTTPS listeners share it, by TLS server name; set floci.tls.aws-https-port=0 "
+ "(or disable TLS) to free it.";
LOG.warnv("ELBv2 listener port {0} is reserved by Floci itself; the listener is "
+ "registered but serves no traffic. {1}", String.valueOf(port), remedy);
return;
@@ -599,8 +644,8 @@ public class ElbV2DataPlane {
}
boolean secure = portIsSecure(port);
HttpServerOptions options = new HttpServerOptions()
.setHost("0.0.0.0")
.setPort(port)
.setHost(behindProxy ? "127.0.0.1" : "0.0.0.0")
.setPort(behindProxy ? 0 : port)
.setMaxHeaderSize(MAX_REQUEST_HEADER_SIZE)
.setMaxInitialLineLength(MAX_REQUEST_LINE_LENGTH);
if (secure) {
@@ -612,10 +657,20 @@ public class ElbV2DataPlane {
HttpServer server = vertx.createHttpServer(options);
long generation = ++state.generation;
servers.put(port, server);
state.behindProxy = behindProxy;
try {
server.requestHandler(req -> handleRequest(req, port));
server.requestHandler(req -> handleRequest(req, port, behindProxy));
server.listen()
.onSuccess(s -> portStarted(port, state, generation, secure ? "HTTPS" : "HTTP"))
.onSuccess(s -> {
if (behindProxy) {
onCurrentPort(port, state, () -> {
if (state.generation == generation) {
state.serverNamePort = s.actualPort();
}
});
}
portStarted(port, state, generation, secure ? "HTTPS" : "HTTP");
})
.onFailure(err -> onCurrentPort(port, state, () -> {
if (state.generation == generation && servers.remove(port, server)) {
scheduleBindRetry(port, state);
@@ -934,6 +989,8 @@ public class ElbV2DataPlane {
private void closeOwnedServer(int port, PortState state, Supplier<Future<Void>> close) {
long generation = ++state.generation;
state.behindProxy = false;
state.serverNamePort = 0;
state.closing++;
Future<Void> closed;
try {
@@ -1044,17 +1101,29 @@ public class ElbV2DataPlane {
state.routing = new RoutingView(Map.copyOf(hosts), Map.copyOf(routes));
}
private void handleRequest(HttpServerRequest req, int port) {
private void handleRequest(HttpServerRequest req, int port, boolean behindProxy) {
PortState state = portStates.get(port);
RoutingView routing = state == null ? null : state.routing;
RoutedListener listener = routing == null ? null : resolveListener(routing, req.host());
RoutedListener listener = null;
SocketAddress client = req.remoteAddress();
if (routing != null) {
if (behindProxy) {
PinnedRoute pin = tlsProxyServer.pinnedRoute(req.localAddress().port(), req.remoteAddress());
if (pin != null) {
listener = routing.listeners().get(pin.routeId());
client = pin.client();
}
} else {
listener = resolveListener(routing, req.host(), true);
}
}
if (listener == null) {
req.response().setStatusCode(502).end("No listener for host");
return;
}
for (CompiledRule compiled : listener.chain()) {
if (compiled.matches(req)) {
executeAction(req, compiled.action, listener.region(), listener.arn());
executeAction(req, client, compiled.action, listener.region(), listener.arn());
return;
}
}
@@ -1062,7 +1131,7 @@ public class ElbV2DataPlane {
}
/** Floci's shared socket first uses load-balancer DNS, then unique rule or certificate hosts. */
private RoutedListener resolveListener(RoutingView routing, String hostHeader) {
private RoutedListener resolveListener(RoutingView routing, String hostHeader, boolean soleListenerFallback) {
String host = normalizeHost(hostHeader);
String direct = routing.hosts().get(host);
if (direct != null) {
@@ -1081,7 +1150,7 @@ public class ElbV2DataPlane {
if (!certificates.isEmpty()) {
return certificates.size() == 1 ? certificates.getFirst() : null;
}
return routing.hosts().size() == 1
return soleListenerFallback && routing.hosts().size() == 1
? routing.listeners().get(routing.hosts().values().iterator().next()) : null;
}
@@ -1105,20 +1174,22 @@ public class ElbV2DataPlane {
return normalized;
}
private void executeAction(HttpServerRequest req, Action action, String region, String listenerArn) {
private void executeAction(HttpServerRequest req, SocketAddress client, Action action, String region,
String listenerArn) {
if (action == null) {
req.response().setStatusCode(502).end("No action");
return;
}
switch (action.getType() != null ? action.getType() : "") {
case "forward" -> executeForward(req, action, region, listenerArn);
case "forward" -> executeForward(req, client, action, region, listenerArn);
case "redirect" -> executeRedirect(req, action);
case "fixed-response" -> executeFixedResponse(req, action);
default -> req.response().setStatusCode(502).end("Unsupported action type");
}
}
private void executeForward(HttpServerRequest req, Action action, String region, String listenerArn) {
private void executeForward(HttpServerRequest req, SocketAddress client, Action action, String region,
String listenerArn) {
ElbV2TraceHeader.update(req.headers());
String tgArn = resolveTgArn(action);
if (tgArn == null) {
@@ -1131,12 +1202,12 @@ public class ElbV2DataPlane {
return;
}
ElbV2ForwardedHeaders forwarded = ElbV2ForwardedHeaders.of(req,
ListenerBinding binding = listenerBindings.get(listenerArn);
int listenerPort = binding != null ? binding.port() : req.localAddress().port();
ElbV2ForwardedHeaders forwarded = ElbV2ForwardedHeaders.of(req, client, listenerPort,
loadBalancerAttribute(listenerArn, region, ElbV2ForwardedHeaders.XFF_MODE_ATTRIBUTE),
Boolean.parseBoolean(
loadBalancerAttribute(listenerArn, region, ElbV2ForwardedHeaders.XFF_CLIENT_PORT_ATTRIBUTE)));
ListenerBinding binding = listenerBindings.get(listenerArn);
int listenerPort = binding != null ? binding.port() : req.localAddress().port();
boolean preserveHost = Boolean.parseBoolean(
loadBalancerAttribute(listenerArn, region, PRESERVE_HOST_HEADER_ATTRIBUTE));
String authority = RequestHost.of(req);
@@ -27,9 +27,10 @@ record ElbV2ForwardedHeaders(SocketAddress client, boolean secure, int listenerP
private static final String FORWARDED_PROTO = "X-Forwarded-Proto";
private static final String FORWARDED_PORT = "X-Forwarded-Port";
static ElbV2ForwardedHeaders of(HttpServerRequest req, String xffMode, boolean xffClientPort) {
return new ElbV2ForwardedHeaders(req.remoteAddress(), req.isSSL(), req.localAddress().port(),
xffMode, xffClientPort);
/** Behind the TLS proxy, {@code client} is the address the proxy accepted the connection from. */
static ElbV2ForwardedHeaders of(HttpServerRequest req, SocketAddress client, int listenerPort, String xffMode,
boolean xffClientPort) {
return new ElbV2ForwardedHeaders(client, req.isSSL(), listenerPort, xffMode, xffClientPort);
}
/** Sets the headers on {@code outbound}, which may already hold a copy of {@code inbound}. */
@@ -4,9 +4,11 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.acm.CertificateGenerator;
import io.floci.aws.services.acm.model.KeyAlgorithm;
import io.floci.aws.testing.SidecarContainersProfile;
import io.floci.aws.testutil.FreePorts;
import io.quarkus.test.junit.QuarkusTestProfile;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
@@ -34,8 +36,13 @@ import java.util.Map;
* <li>{@code floci.tls.*}, the two {@code quarkus.tls.key-store} entries and
* {@code floci.storage.persistent-path} serve that leaf on HTTPS, with the CA it was issued by
* behind {@code GET /_floci/ca.pem}, and keep plain HTTP served beside it. Every class here
* relies on them. {@code aws-https-port=0} keeps the TLS proxy from also binding 443, which an
* unprivileged test JVM cannot do and no class here uses.</li>
* relies on them.</li>
* <li>{@code floci.tls.aws-https-port} set to a free port chosen when the class loads stands in
* for 443, which an unprivileged test JVM cannot bind, and {@code floci.services.elbv2.mock=false}
* runs the real ELBv2 data plane behind it. {@code ElbV2AwsHttpsPortIntegrationTest} relies on
* them, and awaits the proxy's actual bind result before connecting. It uses
* {@code floci.services.iot.endpoint-address} to check shared-port SNI precedence. The other
* classes only see the proxy listening on one more port, and create no load balancer.</li>
* <li>{@code floci.docker.resource-namespace} and
* {@code floci.services.ecr.keep-running-on-shutdown=false} name the ECR registry container in
* this run's {@link SidecarContainersProfile#namespace() sidecar namespace} and stop it at
@@ -65,6 +72,10 @@ public class SelfSignedTlsProfile implements QuarkusTestProfile {
public static final String TLS_DIR = DATA_DIR + "/tls";
public static final String IOT_ENDPOINT_HOST = "iot.example.test";
private static final int AWS_HTTPS_PORT = freePort();
static {
Path tlsDir = Path.of(TLS_DIR);
try {
@@ -97,7 +108,9 @@ public class SelfSignedTlsProfile implements QuarkusTestProfile {
return Map.ofEntries(
Map.entry("floci.tls.enabled", "true"),
Map.entry("floci.tls.self-signed", "true"),
Map.entry("floci.tls.aws-https-port", "0"),
Map.entry("floci.tls.aws-https-port", String.valueOf(AWS_HTTPS_PORT)),
Map.entry("floci.services.elbv2.mock", "false"),
Map.entry("floci.services.iot.endpoint-address", IOT_ENDPOINT_HOST + ":8443"),
Map.entry("floci.storage.persistent-path", Path.of(DATA_DIR).toAbsolutePath().toString()),
Map.entry("quarkus.tls.key-store.pem.0.cert", tlsDir.resolve("floci-server.crt").toString()),
Map.entry("quarkus.tls.key-store.pem.0.key", tlsDir.resolve("floci-server.key").toString()),
@@ -106,4 +119,12 @@ public class SelfSignedTlsProfile implements QuarkusTestProfile {
Map.entry("floci.services.ecr.keep-running-on-shutdown", "false"),
Map.entry("floci.services.ecr.tls-uri", "true"));
}
private static int freePort() {
try {
return FreePorts.anyInterfacePort();
} catch (IOException e) {
throw new UncheckedIOException("No free port for the AWS-HTTPS proxy port", e);
}
}
}
@@ -0,0 +1,102 @@
package io.floci.aws.config;
import io.vertx.core.buffer.Buffer;
import org.junit.jupiter.api.Test;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import java.nio.ByteBuffer;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class TlsClientHelloTest {
@Test
void readsTheServerNameOfARealClientHello() throws Exception {
Buffer hello = clientHello("App-LB-123.elb.localhost.floci.io");
assertFalse(TlsClientHello.needsMore(hello));
assertEquals("app-lb-123.elb.localhost.floci.io", TlsClientHello.serverName(hello));
}
@Test
void absentServerNameIsNull() throws Exception {
Buffer hello = clientHello(null);
assertFalse(TlsClientHello.needsMore(hello));
assertNull(TlsClientHello.serverName(hello));
}
@Test
void aPartialRecordNeedsMoreAndHasNoNameYet() throws Exception {
Buffer hello = clientHello("api.example.test");
Buffer head = hello.getBuffer(0, 3);
Buffer partial = hello.getBuffer(0, hello.length() - 1);
assertTrue(TlsClientHello.needsMore(head));
assertTrue(TlsClientHello.needsMore(partial));
assertNull(TlsClientHello.serverName(partial));
}
@Test
void nonHandshakeOrOversizedRecordsNeverWait() {
assertFalse(TlsClientHello.needsMore(Buffer.buffer("GET / HTTP/1.1\r\n")));
assertFalse(TlsClientHello.needsMore(Buffer.buffer(new byte[]{0x16, 3, 1, (byte) 0xff, (byte) 0xff})));
}
@Test
void malformedHellosAreNull() throws Exception {
assertNull(TlsClientHello.serverName(Buffer.buffer()));
assertNull(TlsClientHello.serverName(Buffer.buffer("GET / HTTP/1.1\r\n")));
Buffer notAClientHello = clientHello("api.example.test");
notAClientHello.setByte(5, (byte) 2);
assertNull(TlsClientHello.serverName(notAClientHello));
Buffer overrunExtensions = handBuiltHello("api.example.test".getBytes());
// Session id length beyond the record shifts every later length out of bounds.
overrunExtensions.setByte(5 + 4 + 2 + 32, (byte) 0xff);
assertNull(TlsClientHello.serverName(overrunExtensions));
Buffer garbage = Buffer.buffer(new byte[]{0x16, 3, 1, 0, 4, 1, 0, 0, 9});
assertNull(TlsClientHello.serverName(garbage));
}
@Test
void aServerNameWithIllegalCharactersIsNull() {
byte[] name = "bad host".getBytes();
assertNull(TlsClientHello.serverName(handBuiltHello(name)));
assertEquals("ok.example.test", TlsClientHello.serverName(handBuiltHello("ok.example.test.".getBytes())));
}
static Buffer clientHello(String serverName) throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
SSLEngine engine = context.createSSLEngine();
engine.setUseClientMode(true);
SSLParameters parameters = engine.getSSLParameters();
parameters.setServerNames(serverName == null ? List.of() : List.of(new SNIHostName(serverName)));
engine.setSSLParameters(parameters);
ByteBuffer out = ByteBuffer.allocate(engine.getSession().getPacketBufferSize());
engine.beginHandshake();
engine.wrap(ByteBuffer.allocate(0), out);
out.flip();
byte[] bytes = new byte[out.remaining()];
out.get(bytes);
return Buffer.buffer(bytes);
}
private static Buffer handBuiltHello(byte[] name) {
Buffer sni = Buffer.buffer().appendShort((short) (name.length + 3)).appendByte((byte) 0)
.appendShort((short) name.length).appendBytes(name);
Buffer extensions = Buffer.buffer().appendShort((short) 0).appendShort((short) sni.length()).appendBuffer(sni);
Buffer body = Buffer.buffer().appendShort((short) 0x0303).appendBytes(new byte[32]).appendByte((byte) 0)
.appendShort((short) 2).appendShort((short) 0x1301).appendByte((byte) 1).appendByte((byte) 0)
.appendShort((short) extensions.length()).appendBuffer(extensions);
Buffer handshake = Buffer.buffer().appendByte((byte) 1).appendByte((byte) 0)
.appendShort((short) body.length()).appendBuffer(body);
return Buffer.buffer().appendByte((byte) 0x16).appendShort((short) 0x0301)
.appendShort((short) handshake.length()).appendBuffer(handshake);
}
}
@@ -15,9 +15,11 @@ import java.util.List;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -35,8 +37,9 @@ class TlsProxyServerReservedPortTest {
when(tls.enabled()).thenReturn(tlsEnabled);
when(tls.awsHttpsPort()).thenReturn(awsHttpsPort);
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.port()).thenReturn(flociPort);
when(config.baseUrl()).thenReturn("http://localhost:4566");
when(config.tls()).thenReturn(tls);
// The listen() future is left uncompleted on purpose: that is the "bind outcome not yet
@@ -71,8 +74,9 @@ class TlsProxyServerReservedPortTest {
EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class);
when(tls.enabled()).thenReturn(tlsEnabled);
when(tls.awsHttpsPort()).thenReturn(awsHttpsPort);
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.port()).thenReturn(flociPort);
when(config.baseUrl()).thenReturn("http://localhost:4566");
when(config.tls()).thenReturn(tls);
NetServer server = mock(NetServer.class);
@@ -93,6 +97,7 @@ class TlsProxyServerReservedPortTest {
TlsProxyServer proxy = proxyWith(4566, true, 443);
assertTrue(proxy.reservesPort(443),
"an unresolved bind must still hold the port, or a listener races the proxy for it");
assertFalse(proxy.boundAwsHttpsPort().isComplete());
}
@Test
@@ -107,25 +112,29 @@ class TlsProxyServerReservedPortTest {
void reservesNothingWhenTlsIsDisabled() {
TlsProxyServer proxy = proxyWith(4566, false, 443);
assertFalse(proxy.reservesPort(443));
assertTrue(proxy.boundAwsHttpsPort().failed());
}
@Test
void doesNotReserveTheAwsHttpsPortWhenItIsDisabled() {
TlsProxyServer proxy = proxyWith(4566, true, 0);
assertFalse(proxy.reservesPort(443));
assertTrue(proxy.boundAwsHttpsPort().failed());
}
@Test
void notifiesHandlersWhenABindFails() {
List<Integer> released = new ArrayList<>();
// listen() resolving to a failure is what happens when the privileged port is refused.
RuntimeException failure = new RuntimeException("permission denied");
TlsProxyServer proxy = proxyWith(4566, true, 443,
Future.failedFuture(new RuntimeException("permission denied")),
Future.failedFuture(failure),
p -> p.onPortReleased(released::add));
assertTrue(released.contains(443),
"a listener that yielded 443 has no other way to learn the bind failed");
assertFalse(proxy.reservesPort(443));
assertSame(failure, proxy.boundAwsHttpsPort().cause());
}
@Test
@@ -1,7 +1,9 @@
package io.floci.aws.config;
import io.floci.aws.config.TlsProxyServer.ServerNameTarget;
import io.floci.aws.testing.ParallelLocks;
import io.floci.aws.testutil.FreePorts;
import io.vertx.core.Context;
import io.vertx.core.Vertx;
import io.vertx.core.net.NetServer;
import org.junit.jupiter.api.AfterEach;
@@ -19,9 +21,12 @@ import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -71,6 +76,12 @@ class TlsProxyServerTest {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class);
when(config.port()).thenReturn(publicPort);
when(config.baseUrl()).thenReturn("http://base.example.test:4566");
when(config.hostname()).thenReturn(Optional.of("api.example.test"));
when(config.dns()).thenReturn(mock(EmulatorConfig.DnsConfig.class));
when(config.services()).thenReturn(mock(EmulatorConfig.ServicesConfig.class));
when(config.services().lambda()).thenReturn(mock(EmulatorConfig.LambdaServiceConfig.class));
when(config.services().iot()).thenReturn(mock(EmulatorConfig.IotServiceConfig.class));
when(config.tls()).thenReturn(tls);
when(tls.enabled()).thenReturn(tlsEnabled);
when(tls.awsHttpsPort()).thenReturn(awsHttpsPort);
@@ -154,6 +165,167 @@ class TlsProxyServerTest {
assertEquals("PLAIN", roundTrip(awsHttpsPort, (byte) 'G'));
}
@Test
@Timeout(20)
void awsHttpsPort_routesAKnownServerNameAndLeavesTheRestToFloci() throws Exception {
httpBackend = startMarkerBackend("PLAIN");
httpsBackend = startMarkerBackend("TLS");
NetServer albBackend = startMarkerBackend("ALB");
try {
int[] ports = FreePorts.anyInterfacePorts(2);
int publicPort = ports[0];
int awsHttpsPort = ports[1];
EmulatorConfig config = configWith(true, publicPort, awsHttpsPort);
when(config.services().iot().endpointAddress()).thenReturn(Optional.of(" MQTT.example.test:8443 "));
proxy = new TlsProxyServer(vertx, config, "127.0.0.1",
httpBackend.actualPort(), httpsBackend.actualPort());
proxy.routeServerNames(port -> true, (port, name, allowAliases) -> port == awsHttpsPort && allowAliases
&& !name.equals("other.example.test") ? new ServerNameTarget(albBackend.actualPort(), "listener") : null);
assertEquals("ALB", roundTrip(awsHttpsPort, TlsClientHelloTest.clientHello("ALB.example.test").getBytes()));
assertEquals("TLS", roundTrip(awsHttpsPort, TlsClientHelloTest.clientHello("other.example.test").getBytes()));
assertEquals("TLS", roundTrip(awsHttpsPort, TlsClientHelloTest.clientHello(null).getBytes()));
for (String endpoint : Set.of("localhost.floci.io", "api.example.test", "base.example.test",
"host.docker.internal", "sqs.us-east-1.localhost.floci.io", "mqtt.example.test")) {
assertEquals("TLS", roundTrip(awsHttpsPort, TlsClientHelloTest.clientHello(endpoint).getBytes()),
endpoint);
}
assertEquals("PLAIN", roundTrip(awsHttpsPort, new byte[]{(byte) 'G'}));
assertEquals("TLS", roundTrip(publicPort, TlsClientHelloTest.clientHello("alb.example.test").getBytes()),
"the public port never routes by server name");
} finally {
closeBackend(albBackend);
}
}
@Test
@Timeout(20)
void awsHttpsPort_waitsForAClientHelloSplitAcrossWrites() throws Exception {
httpsBackend = startMarkerBackend("TLS");
NetServer albBackend = startMarkerBackend("ALB");
try {
int[] ports = FreePorts.anyInterfacePorts(2);
int awsHttpsPort = ports[1];
ManualDeadline deadline = new ManualDeadline();
proxy = new TlsProxyServer(vertx, configWith(true, ports[0], awsHttpsPort), "127.0.0.1",
4510, httpsBackend.actualPort(), deadline);
proxy.routeServerNames(port -> true, (port, name, allowAliases) -> "alb.example.test".equals(name)
? new ServerNameTarget(albBackend.actualPort(), "listener") : null);
byte[] hello = TlsClientHelloTest.clientHello("alb.example.test").getBytes();
awaitListening(awsHttpsPort);
try (Socket sock = new Socket("127.0.0.1", awsHttpsPort)) {
sock.setTcpNoDelay(true);
sock.setSoTimeout(5000);
sock.getOutputStream().write(hello, 0, 3);
sock.getOutputStream().flush();
// Armed means the proxy has read the partial record and is waiting for the rest.
deadline.awaitArmed();
sock.getOutputStream().write(hello, 3, hello.length - 3);
sock.getOutputStream().flush();
byte[] buf = new byte[64];
int n = sock.getInputStream().read(buf);
assertEquals("ALB", new String(buf, 0, n, StandardCharsets.UTF_8));
}
} finally {
closeBackend(albBackend);
}
}
@Test
@Timeout(20)
void awsHttpsPort_aRouteThatThrowsLeavesTheConnectionWithFloci() throws Exception {
httpsBackend = startMarkerBackend("TLS");
int[] ports = FreePorts.anyInterfacePorts(2);
proxy = new TlsProxyServer(vertx, configWith(true, ports[0], ports[1]), "127.0.0.1",
4510, httpsBackend.actualPort());
proxy.routeServerNames(port -> true, (port, name, allowAliases) -> {
throw new IllegalStateException("route failed");
});
assertEquals("TLS", roundTrip(ports[1], TlsClientHelloTest.clientHello("alb.example.test").getBytes()));
}
@Test
@Timeout(20)
void awsHttpsPort_aStalledPartialClientHelloGoesToFlociAtItsDeadline() throws Exception {
httpsBackend = startMarkerBackend("TLS");
int[] ports = FreePorts.anyInterfacePorts(2);
ManualDeadline deadline = new ManualDeadline();
proxy = new TlsProxyServer(vertx, configWith(true, ports[0], ports[1]), "127.0.0.1",
4510, httpsBackend.actualPort(), deadline);
proxy.routeServerNames(port -> true,
(port, name, allowAliases) -> fail("a partial ClientHello has no server name to route"));
byte[] hello = TlsClientHelloTest.clientHello("alb.example.test").getBytes();
awaitListening(ports[1]);
try (Socket sock = new Socket("127.0.0.1", ports[1])) {
sock.setSoTimeout(5000);
sock.getOutputStream().write(hello, 0, 3);
sock.getOutputStream().flush();
deadline.awaitArmed().run();
byte[] buf = new byte[64];
int n = sock.getInputStream().read(buf);
assertEquals("TLS", new String(buf, 0, n, StandardCharsets.UTF_8));
}
}
@Test
@Timeout(20)
void awsHttpsPort_bytesTrickledAfterTheFirstNeverPushTheDeadlineBack() throws Exception {
httpsBackend = startMarkerBackend("TLS");
int[] ports = FreePorts.anyInterfacePorts(2);
ManualDeadline deadline = new ManualDeadline();
proxy = new TlsProxyServer(vertx, configWith(true, ports[0], ports[1]), "127.0.0.1",
4510, httpsBackend.actualPort(), deadline);
proxy.routeServerNames(port -> true,
(port, name, allowAliases) -> fail("the deadline passed before the ClientHello was complete"));
byte[] hello = TlsClientHelloTest.clientHello("alb.example.test").getBytes();
awaitListening(ports[1]);
try (Socket sock = new Socket("127.0.0.1", ports[1])) {
sock.setTcpNoDelay(true);
sock.setSoTimeout(5000);
sock.getOutputStream().write(hello[0]);
sock.getOutputStream().flush();
Runnable expire = deadline.awaitArmed();
for (int i = 1; i < hello.length - 1; i++) {
sock.getOutputStream().write(hello[i]);
sock.getOutputStream().flush();
}
// The deadline armed by the first byte still fires: the later ones neither cancel nor re-arm it.
expire.run();
byte[] buf = new byte[64];
int n = sock.getInputStream().read(buf);
assertEquals("TLS", new String(buf, 0, n, StandardCharsets.UTF_8));
}
assertEquals(1, deadline.armCount());
}
@Test
@Timeout(20)
void awsHttpsPort_withNoListenerClaimingNamesTheFirstBytesGoStraightToFloci() throws Exception {
httpsBackend = startMarkerBackend("TLS");
int[] ports = FreePorts.anyInterfacePorts(2);
ManualDeadline deadline = new ManualDeadline();
proxy = new TlsProxyServer(vertx, configWith(true, ports[0], ports[1]), "127.0.0.1",
4510, httpsBackend.actualPort(), deadline);
proxy.routeServerNames(port -> false,
(port, name, allowAliases) -> fail("no listener claims server names on this port"));
byte[] hello = TlsClientHelloTest.clientHello("alb.example.test").getBytes();
awaitListening(ports[1]);
try (Socket sock = new Socket("127.0.0.1", ports[1])) {
sock.setSoTimeout(5000);
sock.getOutputStream().write(hello, 0, 3);
sock.getOutputStream().flush();
byte[] buf = new byte[64];
int n = sock.getInputStream().read(buf);
assertEquals("TLS", new String(buf, 0, n, StandardCharsets.UTF_8));
}
assertEquals(0, deadline.armCount(), "a port no listener claims names on never waits for a whole ClientHello");
}
@Test
@Timeout(20)
void tlsDisabled_bindsNothing() throws Exception {
@@ -164,6 +336,39 @@ class TlsProxyServerTest {
// ---- helpers ----
/** Records the ClientHello deadline the proxy arms, and fires it on the connection's own context on request. */
private static final class ManualDeadline implements TlsProxyServer.ClientHelloDeadline {
private final CompletableFuture<Runnable> firstArmed = new CompletableFuture<>();
private final AtomicInteger arms = new AtomicInteger();
private final Set<Long> cancelled = ConcurrentHashMap.newKeySet();
@Override
public long arm(Runnable expired) {
long id = arms.incrementAndGet();
Context context = Vertx.currentContext();
firstArmed.complete(() -> context.runOnContext(ignored -> {
if (!cancelled.contains(id)) {
expired.run();
}
}));
return id;
}
@Override
public void cancel(long id) {
cancelled.add(id);
}
/** Waits until the proxy arms its first deadline and returns what fires it. */
Runnable awaitArmed() throws Exception {
return firstArmed.get(5, TimeUnit.SECONDS);
}
int armCount() {
return arms.get();
}
}
private NetServer startMarkerBackend(String marker) throws Exception {
NetServer server = vertx.createNetServer();
server.connectHandler(sock -> sock.write(marker));
@@ -180,9 +385,13 @@ class TlsProxyServerTest {
}
private String roundTrip(int proxyPort, byte firstByte) throws Exception {
return roundTrip(proxyPort, new byte[]{firstByte});
}
private String roundTrip(int proxyPort, byte[] firstBytes) throws Exception {
awaitListening(proxyPort);
try (Socket sock = new Socket("127.0.0.1", proxyPort)) {
sock.getOutputStream().write(new byte[]{firstByte});
sock.getOutputStream().write(firstBytes);
sock.getOutputStream().flush();
byte[] buf = new byte[64];
int n = sock.getInputStream().read(buf);
@@ -0,0 +1,380 @@
package io.floci.aws.services.elbv2;
import com.sun.net.httpserver.HttpServer;
import io.floci.aws.config.SelfSignedTlsProfile;
import io.floci.aws.config.TlsProxyServer;
import io.floci.aws.services.acm.AcmService;
import io.floci.aws.services.acm.CertificateGenerator;
import io.floci.aws.services.acm.model.KeyAlgorithm;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;
import software.amazon.awssdk.services.elasticloadbalancingv2.model.Rule;
import javax.net.ssl.SNIHostName;
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.X509TrustManager;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static io.floci.aws.testing.AlbFixtures.createLoadBalancer;
import static io.floci.aws.testing.AlbFixtures.createTargetGroup;
import static io.floci.aws.testing.AlbFixtures.loadBalancerDnsName;
import static io.floci.aws.testing.AlbFixtures.registerTarget;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* An HTTPS listener on {@code floci.tls.aws-https-port} (443 outside tests), which the TLS proxy
* holds for AWS API calls, receives the connections whose SNI server name it claims, and only those.
*/
@QuarkusTest
@TestProfile(SelfSignedTlsProfile.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ElbV2AwsHttpsPortIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260720/us-east-1/elasticloadbalancing/aws4_request";
private static final String RULE_HOST = "app.example.test";
private static final String CERTIFICATE_HOST = "cert-only.example.org";
private static HttpServer target;
private static String forwardingLoadBalancer;
private static String forwardingTargetGroup;
private static String forwardingDns;
private static String forwardingListener;
private static String fixedDns;
private static String fixedLoadBalancer;
private static String fixedListener;
private static String aliasRule;
@Inject
AcmService acmService;
@Inject
TlsProxyServer proxy;
// Read from the application, not the profile class, which loads again with its own port there.
@ConfigProperty(name = "floci.tls.aws-https-port")
int port;
@BeforeAll
static void startTarget() throws IOException {
RestAssuredJsonUtils.configureAwsContentTypes();
target = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
target.createContext("/", exchange -> {
byte[] body = ("target port=" + exchange.getRequestHeaders().getFirst("X-Forwarded-Port")
+ " for=" + exchange.getRequestHeaders().getFirst("X-Forwarded-For"))
.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(body);
}
});
target.start();
}
@AfterAll
static void stopTarget() {
if (target != null) {
target.stop(0);
}
}
@BeforeEach
void requireTheProxyOnThePort() throws Exception {
assertEquals(port, proxy.boundAwsHttpsPort().toCompletionStage().toCompletableFuture()
.get(10, TimeUnit.SECONDS), "the TLS proxy must bind the configured AWS-HTTPS port");
}
@Test
@Order(1)
void aClaimedServerNameReachesTheListenerWithTheListenerPortForwarded() throws Exception {
forwardingLoadBalancer = createLoadBalancer("sni-forwarding");
forwardingDns = loadBalancerDnsName(forwardingLoadBalancer);
forwardingTargetGroup = createTargetGroup("sni-forwarding-tg", "ip", target.getAddress().getPort());
registerTarget(forwardingTargetGroup, "127.0.0.1", target.getAddress().getPort());
forwardingListener = createHttpsListener(forwardingLoadBalancer, importCertificate(forwardingDns, List.of()),
"DefaultActions.member.1.Type", "forward",
"DefaultActions.member.1.TargetGroupArn", forwardingTargetGroup);
fixedLoadBalancer = createLoadBalancer("sni-fixed");
fixedDns = loadBalancerDnsName(fixedLoadBalancer);
fixedListener = createHttpsListener(fixedLoadBalancer, importCertificate(fixedDns, List.of(CERTIFICATE_HOST)),
"DefaultActions.member.1.Type", "fixed-response",
"DefaultActions.member.1.FixedResponseConfig.StatusCode", "200",
"DefaultActions.member.1.FixedResponseConfig.ContentType", "text/plain",
"DefaultActions.member.1.FixedResponseConfig.MessageBody", "fixed");
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertThat(get(forwardingDns, forwardingDns, "/"), containsString("target port=" + port)));
assertThat(get(fixedDns, fixedDns, "/"), containsString("fixed"));
}
@Test
@Order(2)
void theServerNamePinsTheLoadBalancerWhateverTheHostHeaderSays() throws Exception {
assertThat(get(forwardingDns, fixedDns, "/"), containsString("target port=" + port));
assertThat(get(fixedDns, forwardingDns, "/"), containsString("fixed"));
}
@Test
@Order(3)
void theTargetSeesTheClientTheProxyAcceptedInXForwardedFor() throws Exception {
try (ElasticLoadBalancingV2Client elb = elbClient()) {
elb.modifyLoadBalancerAttributes(request -> request.loadBalancerArn(forwardingLoadBalancer)
.attributes(attribute -> attribute.key(ElbV2ForwardedHeaders.XFF_CLIENT_PORT_ATTRIBUTE).value("true")));
}
try (SSLSocket socket = connect(forwardingDns)) {
assertThat(requestOn(socket, forwardingDns, 200),
containsString("for=127.0.0.1:" + socket.getLocalPort()));
}
}
@Test
@Order(4)
void noOrAnUnclaimedServerNameStaysWithFloci() {
assertGoesToFloci(null);
assertGoesToFloci("unclaimed.example.test");
}
@Test
@Order(5)
void aWildcardRuleCannotClaimFlociServerNames() throws Exception {
try (ElasticLoadBalancingV2Client elb = elbClient()) {
Rule rule = elb.createRule(request -> request.listenerArn(fixedListener).priority(10)
.conditions(condition -> condition.field("host-header")
.hostHeaderConfig(hosts -> hosts.values("*.floci.io", "*.example.test")))
.actions(action -> action.type("fixed-response").fixedResponseConfig(response -> response
.statusCode("200").contentType("text/plain").messageBody("wildcard rule")))).rules().getFirst();
aliasRule = rule.ruleArn();
}
assertThat(get(RULE_HOST, RULE_HOST, "/"), containsString("wildcard rule"));
assertThat(get(forwardingDns, forwardingDns, "/"), containsString("target port=" + port));
assertGoesToFloci("localhost.floci.io");
assertGoesToFloci("sqs.us-east-1.localhost.floci.io");
assertGoesToFloci(SelfSignedTlsProfile.IOT_ENDPOINT_HOST);
}
@Test
@Order(6)
void removingTheHostRuleKeepsTheEstablishedConnectionOnItsListener() throws Exception {
try (SSLSocket socket = connect(RULE_HOST); ElasticLoadBalancingV2Client elb = elbClient()) {
assertEquals("wildcard rule", requestOn(socket, RULE_HOST, 200));
elb.deleteRule(request -> request.ruleArn(aliasRule));
assertGoesToFloci(RULE_HOST);
assertEquals("fixed", requestOn(socket, forwardingDns, 200));
}
}
@Test
@Order(7)
void replacingTheCertificateKeepsTheEstablishedConnectionOnItsListener() throws Exception {
try (SSLSocket socket = connect(CERTIFICATE_HOST); ElasticLoadBalancingV2Client elb = elbClient()) {
assertEquals("fixed", requestOn(socket, CERTIFICATE_HOST, 200));
String replacement = importCertificate(fixedDns, List.of());
elb.modifyListener(request -> request.listenerArn(fixedListener)
.certificates(certificate -> certificate.certificateArn(replacement)));
assertGoesToFloci(CERTIFICATE_HOST);
assertEquals("fixed", requestOn(socket, forwardingDns, 200));
}
}
@Test
@Order(8)
void removingTheLoadBalancerRejectsRequestsInsteadOfSwitchingListeners() throws Exception {
try (SSLSocket socket = connect(fixedDns); ElasticLoadBalancingV2Client elb = elbClient()) {
assertEquals("fixed", requestOn(socket, fixedDns, 200));
elb.deleteLoadBalancer(request -> request.loadBalancerArn(fixedLoadBalancer));
assertThat(get(forwardingDns, forwardingDns, "/"), containsString("target port=" + port));
assertEquals("No listener for host", requestOn(socket, forwardingDns, 502));
}
}
@Test
@Order(9)
void aListenerModifiedAwayFromHttpsNoLongerClaimsItsName() {
given()
.formParam("Action", "ModifyListener")
.formParam("ListenerArn", forwardingListener)
.formParam("Protocol", "HTTP")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.log().ifValidationFails()
.statusCode(200);
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertGoesToFloci(forwardingDns));
}
// The other classes on this profile share the application, so the listener left on the port goes too.
@Test
@Order(10)
void deletingTheLastLoadBalancerLeavesThePortToFloci() {
try (ElasticLoadBalancingV2Client elb = elbClient()) {
elb.deleteLoadBalancer(request -> request.loadBalancerArn(forwardingLoadBalancer));
elb.deleteTargetGroup(request -> request.targetGroupArn(forwardingTargetGroup));
}
assertGoesToFloci(forwardingDns);
}
private static ElasticLoadBalancingV2Client elbClient() {
return AwsTestClients.create(ElasticLoadBalancingV2Client.builder(), "test", Region.US_EAST_1);
}
private String importCertificate(String dnsName, List<String> alternativeNames) {
CertificateGenerator.GeneratedCertificate certificate = new CertificateGenerator()
.generateSelfSignedCertificate(dnsName, alternativeNames, KeyAlgorithm.RSA_2048);
return acmService.importCertificate(certificate.certificatePem(),
certificate.privateKeyPem(), null, null, Map.of(), "us-east-1").getArn();
}
private String createHttpsListener(String loadBalancerArn, String certificateArn, String... action) {
RequestSpecification request = given()
.formParam("Action", "CreateListener")
.formParam("LoadBalancerArn", loadBalancerArn)
.formParam("Protocol", "HTTPS")
.formParam("Port", String.valueOf(port))
.formParam("Certificates.member.1.CertificateArn", certificateArn)
.header("Authorization", AUTH);
for (int i = 0; i < action.length; i += 2) {
request.formParam(action[i], action[i + 1]);
}
return request
.when()
.post("/")
.then()
.statusCode(200)
.extract()
.path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn");
}
/**
* Under {@code @QuarkusTest} Floci serves HTTPS on its test port, not the internal port the proxy
* hands Floci's connections to, so a connection the proxy leaves with Floci fails its handshake
* here instead of reaching a load balancer, which would complete it.
*/
private void assertGoesToFloci(String serverName) {
assertThrows(SSLHandshakeException.class, () -> get(serverName, "localhost", "/"));
}
/** One HTTP/1.1 request over TLS to the AWS-HTTPS port, sending {@code serverName} as SNI when set. */
private String get(String serverName, String host, String path) throws Exception {
try (SSLSocket socket = connect(serverName)) {
sendRequest(socket, host, path, "close");
return new String(socket.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
}
}
private SSLSocket connect(String serverName) throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{new TrustAll()}, null);
Socket transport = new Socket();
try {
transport.connect(new InetSocketAddress("127.0.0.1", port), 2000);
SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket(transport, "127.0.0.1", port, true);
socket.setSoTimeout(5000);
SSLParameters parameters = socket.getSSLParameters();
parameters.setServerNames(serverName == null ? List.of() : List.of(new SNIHostName(serverName)));
socket.setSSLParameters(parameters);
socket.startHandshake();
return socket;
} catch (IOException | RuntimeException exception) {
try {
transport.close();
} catch (IOException closeFailure) {
exception.addSuppressed(closeFailure);
}
throw exception;
}
}
private static void sendRequest(SSLSocket socket, String host, String path, String connection) throws IOException {
OutputStream out = socket.getOutputStream();
out.write(("GET " + path + " HTTP/1.1\r\nHost: " + host + "\r\nConnection: " + connection + "\r\n\r\n")
.getBytes(StandardCharsets.US_ASCII));
out.flush();
}
private static String requestOn(SSLSocket socket, String host, int expectedStatus) throws IOException {
sendRequest(socket, host, "/", "keep-alive");
InputStream in = socket.getInputStream();
String status = readLine(in);
assertEquals(expectedStatus, Integer.parseInt(status.split(" ", 3)[1]), status);
int length = -1;
for (String header = readLine(in); !header.isEmpty(); header = readLine(in)) {
if (header.toLowerCase(Locale.ROOT).startsWith("content-length:")) {
length = Integer.parseInt(header.substring("content-length:".length()).trim());
}
}
if (length < 0) {
throw new IOException("Expected a Content-Length header");
}
return new String(in.readNBytes(length), StandardCharsets.UTF_8);
}
private static String readLine(InputStream in) throws IOException {
StringBuilder line = new StringBuilder();
for (int next = in.read(); next != '\n'; next = in.read()) {
if (next < 0) {
throw new EOFException("Connection closed before the HTTP response ended");
}
if (next != '\r') {
line.append((char) next);
}
}
return line.toString();
}
private static final class TrustAll implements 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];
}
}
}
@@ -179,4 +179,20 @@ class ElbV2ForwardedHeadersTest {
assertEquals(List.of("client.example.test", "second.example.test:8443"),
((Map<String, List<String>>) event.get("multiValueHeaders")).get("host"));
}
@Test
void behindTheProxyTheHeadersNameTheProxiedClientAndTheListenersPort() {
HttpServerRequest request = mock(HttpServerRequest.class);
when(request.remoteAddress()).thenReturn(SocketAddress.inetSocketAddress(61000, "127.0.0.1"));
when(request.isSSL()).thenReturn(true);
when(request.localAddress()).thenReturn(SocketAddress.inetSocketAddress(50443, "127.0.0.1"));
MultiMap outbound = MultiMap.caseInsensitiveMultiMap();
ElbV2ForwardedHeaders.of(request, CLIENT_V4, 443, "append", true)
.applyTo(MultiMap.caseInsensitiveMultiMap(), outbound);
assertEquals(List.of("12.34.56.78:8080"), outbound.getAll("X-Forwarded-For"));
assertEquals(List.of("443"), outbound.getAll("X-Forwarded-Port"));
assertEquals(List.of("https"), outbound.getAll("X-Forwarded-Proto"));
}
}
@@ -2,6 +2,7 @@ package io.floci.aws.services.elbv2;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.TlsProxyServer;
import io.floci.aws.config.TlsProxyServer.ServerNameTarget;
import io.floci.aws.core.common.CertificateReferenceResolver;
import io.floci.aws.core.common.CertificateReferenceResolver.CertificateMaterial;
import io.floci.aws.core.common.Pem;
@@ -11,8 +12,10 @@ import io.floci.aws.services.elbv2.model.Action;
import io.floci.aws.services.elbv2.model.Listener;
import io.floci.aws.services.elbv2.model.LoadBalancer;
import io.floci.aws.services.elbv2.model.Rule;
import io.floci.aws.services.elbv2.model.RuleCondition;
import io.floci.aws.testing.InlineMocks;
import io.floci.aws.testing.ParallelLocks;
import io.floci.aws.testutil.LogCapture;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
@@ -21,6 +24,7 @@ import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.net.NetServerOptions;
import io.vertx.core.net.SSLOptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.ResourceAccessMode;
@@ -30,8 +34,11 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;
import java.util.logging.LogRecord;
import static io.floci.aws.services.elbv2.ElbV2PublicationTestSupport.publishRuntime;
import static io.floci.aws.services.elbv2.ElbV2PublicationTestSupport.removeRuntime;
@@ -39,6 +46,7 @@ import static io.floci.aws.services.elbv2.ElbV2PublicationTestSupport.servedCert
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -160,6 +168,152 @@ class ElbV2ReservedPortTest {
verify(vertx, times(1)).createHttpServer(any(HttpServerOptions.class));
}
/** A data plane whose TLS proxy holds 443, with one HTTPS listener ready to publish there. */
private static final class ProxiedPort {
final AtomicBoolean proxyHolds443 = new AtomicBoolean(true);
final TlsProxyServer proxy = mock(TlsProxyServer.class);
final HttpServer local = mock(HttpServer.class);
final HttpServer public443 = mock(HttpServer.class);
final Vertx vertx = mock(Vertx.class);
final ElbV2DataPlane dataPlane = new ElbV2DataPlane();
final Listener listener = new Listener();
final Rule hostRule = fixedRule("api");
ProxiedPort() {
EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class);
when(tls.enabled()).thenReturn(true);
when(tls.awsHttpsPort()).thenReturn(443);
EmulatorConfig.ElbV2ServiceConfig elbv2 = mock(EmulatorConfig.ElbV2ServiceConfig.class);
when(elbv2.mock()).thenReturn(false);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
when(services.elbv2()).thenReturn(elbv2);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.port()).thenReturn(4566);
when(config.tls()).thenReturn(tls);
when(config.services()).thenReturn(services);
when(proxy.reservesPort(anyInt())).thenAnswer(inv -> proxyHolds443.get() && (int) inv.getArgument(0) == 443);
for (HttpServer server : List.of(local, public443)) {
when(server.requestHandler(any())).thenReturn(server);
when(server.listen()).thenReturn(Future.succeededFuture(server));
when(server.close()).thenReturn(Future.succeededFuture());
}
when(local.actualPort()).thenReturn(50443);
when(vertx.createHttpServer(any(HttpServerOptions.class))).thenReturn(local, public443);
dataPlane.config = config;
dataPlane.tlsProxyServer = proxy;
dataPlane.vertx = vertx;
dataPlane.elbV2Service = mock(ElbV2Service.class);
dataPlane.certificateResolver = mock(CertificateReferenceResolver.class);
String certificateArn = "arn:aws:acm:us-west-2:000000000000:certificate/sni";
listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/lb/1/2");
listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/lb/1");
listener.setPort(443);
listener.setProtocol("HTTPS");
listener.setDefaultCertificate(certificateArn);
LoadBalancer loadBalancer = new LoadBalancer();
loadBalancer.setDnsName("lb-1.elb.example.test");
when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn())).thenReturn(loadBalancer);
CertificateGenerator.GeneratedCertificate certificate = new CertificateGenerator().generateSelfSignedCertificate(
"www.example.test", List.of(), KeyAlgorithm.RSA_2048);
when(dataPlane.certificateResolver.publishedMaterial(listener.getListenerArn(), "us-west-2", certificateArn))
.thenReturn(new CertificateMaterial(certificateArn, certificate.certificatePem(),
certificate.privateKeyPem(), null));
RuleCondition condition = new RuleCondition();
condition.setField("host-header");
condition.setValues(List.of("api.example.test"));
hostRule.setDefault(false);
hostRule.setConditions(List.of(condition));
}
void publish() {
publishRuntime(dataPlane, listener, "us-west-2", 443, List.of(hostRule));
}
TlsProxyServer.ServerNameRoute route() {
ArgumentCaptor<TlsProxyServer.ServerNameRoute> route = ArgumentCaptor.forClass(TlsProxyServer.ServerNameRoute.class);
verify(proxy).routeServerNames(any(), route.capture());
return route.getValue();
}
/** What tells the proxy whether a ClientHello on a port is worth reading for its server name. */
IntPredicate claimsServerNames() {
ArgumentCaptor<IntPredicate> claims = ArgumentCaptor.forClass(IntPredicate.class);
verify(proxy).routeServerNames(claims.capture(), any());
return claims.getValue();
}
}
@Test
void anHttpsListenerOnTheProxyPortIsServedLocallyAndRoutedByServerName() {
ProxiedPort fixture = new ProxiedPort();
try {
fixture.publish();
ArgumentCaptor<HttpServerOptions> options = ArgumentCaptor.forClass(HttpServerOptions.class);
verify(fixture.vertx).createHttpServer(options.capture());
assertEquals("127.0.0.1", options.getValue().getHost());
assertEquals(0, options.getValue().getPort());
assertTrue(options.getValue().isSsl());
TlsProxyServer.ServerNameRoute route = fixture.route();
IntPredicate claims = fixture.claimsServerNames();
assertTrue(claims.test(443));
assertFalse(claims.test(8443));
ServerNameTarget expected = new ServerNameTarget(50443, fixture.listener.getListenerArn());
assertEquals(expected, route.resolve(443, "lb-1.elb.example.test", false));
assertNull(route.resolve(443, "api.example.test", false));
assertEquals(expected, route.resolve(443, "www.example.test", true));
assertEquals(expected, route.resolve(443, "api.example.test", true));
assertNull(route.resolve(443, "s3.amazonaws.com", true),
"an unclaimed name stays with Floci even when a single load balancer serves the port");
assertNull(route.resolve(8443, "lb-1.elb.example.test", true));
ArgumentCaptor<IntConsumer> released = ArgumentCaptor.forClass(IntConsumer.class);
verify(fixture.proxy).onPortReleased(released.capture());
fixture.proxyHolds443.set(false);
released.getValue().accept(443);
verify(fixture.local).close();
verify(fixture.vertx, times(2)).createHttpServer(options.capture());
assertEquals("0.0.0.0", options.getValue().getHost());
assertEquals(443, options.getValue().getPort());
assertNull(route.resolve(443, "lb-1.elb.example.test", true),
"once the listener owns 443 itself the proxy no longer forwards to it");
assertFalse(claims.test(443), "nor waits for a whole ClientHello on it");
} finally {
fixture.dataPlane.shutdown();
}
}
@ParameterizedTest
@ValueSource(strings = {"HTTP", "TCP"})
void modifyingTheProxiedListenerAwayFromHttpsStopsRoutingAndWarnsTheirPortIsReserved(String protocol) {
ProxiedPort fixture = new ProxiedPort();
try {
fixture.publish();
TlsProxyServer.ServerNameRoute route = fixture.route();
IntPredicate claims = fixture.claimsServerNames();
assertTrue(claims.test(443));
assertEquals(new ServerNameTarget(50443, fixture.listener.getListenerArn()),
route.resolve(443, "lb-1.elb.example.test", false));
assertNull(route.resolve(443, "api.example.test", false));
fixture.listener.setProtocol(protocol);
fixture.listener.setDefaultCertificate(null);
List<LogRecord> records = LogCapture.capture(ElbV2DataPlane.class, fixture::publish);
verify(fixture.local).close();
verify(fixture.vertx, times(1)).createHttpServer(any(HttpServerOptions.class));
verify(fixture.vertx, never()).createNetServer(any(NetServerOptions.class));
assertNull(route.resolve(443, "lb-1.elb.example.test", true));
assertFalse(claims.test(443), "an HTTP or TCP listener on the proxy port claims no server names");
assertTrue(records.stream().map(LogCapture::formatted)
.anyMatch(message -> message.contains("port 443 is reserved by Floci itself")),
"expected the reserved-port warning, got " + records.stream().map(LogCapture::formatted).toList());
} finally {
fixture.dataPlane.shutdown();
}
}
@Test
void leavesOrdinaryListenerPortsAlone() {
ElbV2DataPlane dataPlane = dataPlaneWith(4566, true, 443);