mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(elbv2): relay TCP listeners without HTTP parsing (#7044)
* fix(elbv2): relay TCP listeners without HTTP parsing Forward raw TCP traffic and TLS passthrough to registered targets while preserving per-connection routing. Cover the data plane through AWS SDK integration tests and document dedicated-port limitations. Refs #5870 * test(elbv2): make TCP data plane test cleanup resilient to partial failures * refactor(elbv2): share target selection helpers between TCP and HTTP paths Extract targetCandidates and pickRoundRobin to remove the duplicated healthy-or-registered fallback and round-robin pick from the TCP relay and HTTP forwarding paths, unifying both on the floorMod counter that cannot go negative. * fix(elbv2): honor listener tcp idle timeout and park colliding listeners Use tcp.idle_timeout.seconds attribute dynamically in the TCP relay tunnel, and register colliding listeners on in-use ports as parked with a warning, promoting them once the active listener is removed. * fix(elbv2): validate tcp idle timeout range and reuse timeout parser * fix(elbv2): unify parse failure and range check in listener attribute validation
This commit is contained in:
1 parent
cedc1073ec
commit
8499581af3
5 files changed
+770
-48
No files matched your search
+14
-12
@@ -2,7 +2,7 @@
|
||||
|
||||
**Protocol:** Query (XML) — `POST http://localhost:4566/` with `Action=` parameter
|
||||
|
||||
Floci supports Application Load Balancers (ALB) and Network Load Balancers (NLB) through the ELBv2 management API. The control plane is AWS SDK / CLI / Terraform compatible, and HTTP and HTTPS listeners can forward to registered instance targets using the target's reachable local address.
|
||||
Floci supports Application Load Balancers (ALB) and Network Load Balancers (NLB) through the ELBv2 management API. The control plane is AWS SDK / CLI / Terraform compatible. HTTP, HTTPS, and TCP listeners can forward to registered instance and IP targets using the target's reachable local address.
|
||||
|
||||
> Classic (v1) Elastic Load Balancing is a **different API** served from the same endpoint host —
|
||||
> see [ELB Classic (v1)](elb-classic.md). Requests are routed by their `Version` parameter:
|
||||
@@ -88,11 +88,13 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on
|
||||
|
||||
## Behavior Notes
|
||||
|
||||
- TCP listeners relay bytes bidirectionally without parsing HTTP or terminating TLS. TLS passthrough requires a TCP listener, with certificates configured at the target, not at the listener. Targets are selected per connection using round-robin among healthy targets, falling back to registered targets when none are healthy. The default TCP idle timeout is 350 seconds, configurable via the `tcp.idle_timeout.seconds` listener attribute (60 to 6000 seconds).
|
||||
- TCP listeners require a dedicated local port. Floci still shares its address across load balancers, so a second listener on an in-use TCP port registers successfully and logs a warning, but serves no traffic until the listener holding the port is deleted or moved, and ports reserved by Floci remain unavailable. Address isolation and TLS-terminating NLB listeners are not provided by the TCP proxy.
|
||||
- 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.
|
||||
- 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.
|
||||
- Listeners sharing a local port must use the same protocol. Requests select a load balancer by its DNS name, a hostname declared by its rules, or a certificate hostname; ambiguous hostnames return 502.
|
||||
- HTTP or HTTPS listeners sharing a local port must use the same protocol. Requests select a load balancer by its DNS name, a hostname declared by its rules, or a certificate hostname; ambiguous hostnames return 502. TCP never serves a port alongside either protocol; see the TCP note above.
|
||||
- Load balancer, target group, listener, rule, and tag state is persisted through Floci storage and rebuilt on service startup.
|
||||
- Load balancers are created in `active` state.
|
||||
- `CreateLoadBalancer` takes `Subnets` or `SubnetMappings` for every load balancer type, and both together are refused with `ValidationError`. An Application Load Balancer takes at least two: with one or none it returns `ValidationError` `At least two subnets in two different Availability Zones must be specified` and creates nothing. The count comes before any subnet is looked up, as on AWS, so one subnet that does not exist gets that error too. A Network or Gateway Load Balancer with neither returns `ValidationError` `At least one subnet must be specified`. CloudFormation refuses such an `AWS::ElasticLoadBalancingV2::LoadBalancer` the same way when it creates or replaces the balancer; an update that keeps the balancer and names no subnets leaves it on its subnets.
|
||||
@@ -133,24 +135,24 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on
|
||||
## Forwarding and network-security boundaries
|
||||
|
||||
An accepted NLB, listener, or target-group declaration confirms control-plane storage.
|
||||
It does not establish that the declared transport is implemented. ELBv2 currently runs
|
||||
an HTTP proxy on its listener sockets, including sockets declared as NLB listeners.
|
||||
It does not establish that the declared transport is implemented. ELBv2 supports local
|
||||
HTTP, HTTPS, and TCP listener sockets; other declared listener protocols and target
|
||||
types remain control-plane only.
|
||||
|
||||
| Declared listener protocol | Local forwarding behavior | Target types and transport |
|
||||
|---|---|---|
|
||||
| `HTTP` | Parses and forwards HTTP requests; supports WebSocket upgrades. | `instance` resolves an EC2 private address; `ip` uses the registered address. Backend requests use plain HTTP. `lambda` invokes the registered function with an ALB event. |
|
||||
| `HTTPS` | Terminates TLS with an ACM or IAM certificate, then handles HTTP as above. | Same targets as HTTP; an HTTPS target-group setting does not enable TLS to the backend. |
|
||||
| `TCP` | Stored, but the local socket still parses HTTP. Arbitrary TCP byte forwarding is unsupported. | A successful HTTP request through a TCP-labelled listener proves only HTTP forwarding. |
|
||||
| `TLS` | Stored; certificate references are checked, but only `HTTPS` enables TLS on the local socket. TLS termination and TLS pass-through for NLB listeners are unsupported. | No NLB TLS backend transport is implemented. |
|
||||
| `TCP` | Relays bytes bidirectionally without HTTP parsing or TLS termination (enabling TLS pass-through to the target). Requires a dedicated local port. | `instance` resolves an EC2 private address; `ip` uses the registered address. Selected round-robin per connection. |
|
||||
| `TLS` | Stored; certificate references are checked, but only `HTTPS` enables TLS on the local socket. TLS termination for NLB `TLS` listeners is unsupported (use a `TCP` listener for TLS pass-through). | No NLB TLS backend transport is implemented. |
|
||||
| `UDP`, `TCP_UDP` | Stored declarations do not create UDP sockets or UDP forwarding. | Datagram targets are unsupported. |
|
||||
| Gateway `GENEVE` | Portless control-plane metadata only. | No GENEVE packet forwarding. |
|
||||
|
||||
`alb` target-type declarations do not implement NLB-to-ALB chaining. Use the HTTP/HTTPS
|
||||
rows for local application routing. Do not use a successful registration or an HTTP
|
||||
smoke test as evidence of TCP, TLS, UDP, or NLB target-type compatibility. There is no
|
||||
supported non-HTTP TCP echo recipe for this implementation. Unsupported transports
|
||||
are not consistently rejected by the management API: clients can instead see HTTP
|
||||
parse errors, failed TLS handshakes, or timeouts on the listener socket.
|
||||
`alb` target-type declarations do not implement NLB-to-ALB chaining. Use the HTTP, HTTPS,
|
||||
or TCP rows for local routing. Do not use a successful registration alone as evidence of
|
||||
TLS, UDP, or NLB target-type compatibility. Unsupported transports are not consistently
|
||||
rejected by the management API: clients can instead see failed TLS handshakes or timeouts
|
||||
on the listener socket.
|
||||
|
||||
### Health checks
|
||||
|
||||
|
||||
@@ -33,6 +33,10 @@ import io.vertx.core.http.HttpServerResponse;
|
||||
import io.vertx.core.http.RequestOptions;
|
||||
import io.vertx.core.net.JdkSSLEngineOptions;
|
||||
import io.vertx.core.net.KeyCertOptions;
|
||||
import io.vertx.core.net.NetClient;
|
||||
import io.vertx.core.net.NetClientOptions;
|
||||
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 jakarta.annotation.PostConstruct;
|
||||
@@ -94,8 +98,12 @@ public class ElbV2DataPlane {
|
||||
static final int MAX_REQUEST_LINE_LENGTH = 16 * 1024;
|
||||
static final int MAX_RESPONSE_HEADER_SIZE = 32 * 1024;
|
||||
private static final String IDLE_TIMEOUT_ATTRIBUTE = "idle_timeout.timeout_seconds";
|
||||
static final String TCP_IDLE_TIMEOUT_ATTRIBUTE = "tcp.idle_timeout.seconds";
|
||||
private static final long DEFAULT_IDLE_TIMEOUT_SECONDS = 60;
|
||||
private static final int MAX_LAMBDA_BODY_BYTES = 1024 * 1024;
|
||||
static final int TCP_IDLE_TIMEOUT_SECONDS = 350;
|
||||
static final int MIN_TCP_IDLE_TIMEOUT_SECONDS = 60;
|
||||
static final int MAX_TCP_IDLE_TIMEOUT_SECONDS = 6000;
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
@@ -125,6 +133,7 @@ public class ElbV2DataPlane {
|
||||
ObjectMapper objectMapper;
|
||||
|
||||
private final Map<Integer, HttpServer> servers = new ConcurrentHashMap<>();
|
||||
private final Map<Integer, NetServer> tcpServers = new ConcurrentHashMap<>();
|
||||
private final Map<Integer, PortState> portStates = new ConcurrentHashMap<>();
|
||||
private volatile boolean stopping;
|
||||
|
||||
@@ -183,7 +192,7 @@ public class ElbV2DataPlane {
|
||||
}
|
||||
|
||||
private void retirePortState(int port, PortState state) {
|
||||
if (state.depth == 0 && state.closing == 0 && !servers.containsKey(port)
|
||||
if (state.depth == 0 && state.closing == 0 && !servers.containsKey(port) && !tcpServers.containsKey(port)
|
||||
&& !listenersByHostAndPort.containsKey(port)) {
|
||||
portStates.remove(port, state);
|
||||
}
|
||||
@@ -199,6 +208,7 @@ public class ElbV2DataPlane {
|
||||
private final ElbV2StickyCookie stickyCookie = new ElbV2StickyCookie();
|
||||
|
||||
private HttpClient proxyClient;
|
||||
private NetClient tcpClient;
|
||||
|
||||
public ElbV2DataPlane() {
|
||||
this(new ConcurrentHashMap<>());
|
||||
@@ -209,7 +219,8 @@ public class ElbV2DataPlane {
|
||||
}
|
||||
|
||||
record ListenerBinding(int port, String host, String loadBalancerArn,
|
||||
boolean secure, Set<String> certificateHosts, List<CertificateMaterial> certificates) {}
|
||||
boolean secure, Set<String> certificateHosts, List<CertificateMaterial> certificates,
|
||||
boolean tcp) {}
|
||||
|
||||
@PostConstruct
|
||||
void init() {
|
||||
@@ -218,6 +229,8 @@ public class ElbV2DataPlane {
|
||||
.setConnectTimeout(5000)
|
||||
.setKeepAlive(true)
|
||||
.setMaxHeaderSize(MAX_RESPONSE_HEADER_SIZE));
|
||||
tcpClient = vertx.createNetClient(new NetClientOptions().setConnectTimeout(5000)
|
||||
.setTcpKeepAlive(true));
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
@@ -229,10 +242,18 @@ public class ElbV2DataPlane {
|
||||
if (server != null) {
|
||||
server.close();
|
||||
}
|
||||
NetServer tcpServer = tcpServers.remove(entry.getKey());
|
||||
if (tcpServer != null) {
|
||||
tcpServer.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
portStates.clear();
|
||||
servers.clear();
|
||||
tcpServers.clear();
|
||||
if (tcpClient != null) {
|
||||
tcpClient.close();
|
||||
}
|
||||
listenersByHostAndPort.clear();
|
||||
listenerBindings.clear();
|
||||
ruleChains.clear();
|
||||
@@ -344,11 +365,19 @@ public class ElbV2DataPlane {
|
||||
ruleChains.put(arn, new AtomicReference<>(compiled.get()));
|
||||
}
|
||||
listenerRegions.put(arn, region);
|
||||
if (conflictsWithServedListener(prepared.port(), prepared.tcp(), arn)) {
|
||||
LOG.warnv("ELBv2 listener {0} on port {1} is registered but serves no traffic: a TCP listener "
|
||||
+ "needs a dedicated local port and another listener already serves it. It takes over "
|
||||
+ "the port once the serving listener is deleted or moved.", arn, String.valueOf(prepared.port()));
|
||||
return true;
|
||||
}
|
||||
Map<String, String> peers = listenersByHostAndPort.computeIfAbsent(
|
||||
prepared.port(), ignored -> new ConcurrentHashMap<>());
|
||||
warnOnSharedPort(prepared, peers);
|
||||
addHostBindings(arn, prepared);
|
||||
if (expected != null && expected.port() == prepared.port() && expected.secure() != prepared.secure()) {
|
||||
promoteParkedListeners(prepared.port());
|
||||
if (expected != null && expected.port() == prepared.port()
|
||||
&& (expected.secure() != prepared.secure() || expected.tcp() != prepared.tcp())) {
|
||||
restartPortServer(prepared.port());
|
||||
} else {
|
||||
HttpServer server = servers.get(prepared.port());
|
||||
@@ -372,7 +401,9 @@ public class ElbV2DataPlane {
|
||||
private void removePortBinding(String listenerArn, ListenerBinding binding) {
|
||||
removeHostBindings(listenerArn, binding);
|
||||
Map<String, String> listenersByHost = listenersByHostAndPort.get(binding.port());
|
||||
if (listenersByHost == null || listenersByHost.isEmpty()) {
|
||||
if ((listenersByHost == null || listenersByHost.isEmpty()) && promoteParkedListeners(binding.port())) {
|
||||
restartPortServer(binding.port());
|
||||
} else if (listenersByHost == null || listenersByHost.isEmpty()) {
|
||||
closePortServerIfUnused(binding.port(), listenersByHost);
|
||||
} else if (binding.secure()) {
|
||||
HttpServer server = servers.get(binding.port());
|
||||
@@ -429,6 +460,53 @@ public class ElbV2DataPlane {
|
||||
return tlsProxyServer.reservesPort(port);
|
||||
}
|
||||
|
||||
/** Bindings of the listeners that actually serve a port, excluding parked ones. */
|
||||
private Stream<ListenerBinding> servedBindings(int port) {
|
||||
Map<String, String> served = listenersByHostAndPort.getOrDefault(port, Map.of());
|
||||
return served.values().stream()
|
||||
.map(listenerBindings::get)
|
||||
.filter(binding -> binding != null && binding.port() == port);
|
||||
}
|
||||
|
||||
/**
|
||||
* A TCP listener owns its local port outright, so it cannot share it with any other listener.
|
||||
* Only listeners that serve the port count: a parked one must not keep a newcomer off it.
|
||||
*/
|
||||
private boolean conflictsWithServedListener(int port, boolean tcp, String listenerArn) {
|
||||
Map<String, String> served = listenersByHostAndPort.getOrDefault(port, Map.of());
|
||||
for (String otherArn : served.values()) {
|
||||
ListenerBinding other = listenerBindings.get(otherArn);
|
||||
if (!otherArn.equals(listenerArn) && other != null && other.port() == port && (other.tcp() || tcp)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets parked listeners serve a port that no longer conflicts with them, in ARN order so the
|
||||
* outcome does not depend on map iteration. Returns whether any listener was promoted.
|
||||
*/
|
||||
private boolean promoteParkedListeners(int port) {
|
||||
Set<String> served = Set.copyOf(listenersByHostAndPort.getOrDefault(port, Map.of()).values());
|
||||
List<String> parked = listenerBindings.entrySet().stream()
|
||||
.filter(entry -> entry.getValue().port() == port && !served.contains(entry.getKey())
|
||||
&& ruleChains.containsKey(entry.getKey()) && listenerRegions.containsKey(entry.getKey()))
|
||||
.map(Map.Entry::getKey)
|
||||
.sorted()
|
||||
.toList();
|
||||
boolean promoted = false;
|
||||
for (String parkedArn : parked) {
|
||||
ListenerBinding binding = listenerBindings.get(parkedArn);
|
||||
if (binding != null && !conflictsWithServedListener(port, binding.tcp(), parkedArn)) {
|
||||
addHostBindings(parkedArn, binding);
|
||||
LOG.infov("ELBv2 listener {0} now serves port {1}", parkedArn, String.valueOf(port));
|
||||
promoted = true;
|
||||
}
|
||||
}
|
||||
return promoted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds any registered listener whose port the proxy has just released. Yielding a port whose
|
||||
* bind had not resolved yet is the safe default, but if that bind then fails nothing else
|
||||
@@ -464,7 +542,7 @@ public class ElbV2DataPlane {
|
||||
|
||||
private void ensurePortServer(int port) {
|
||||
PortState state = portStates.get(port);
|
||||
if (!stopping && state != null && state.closing == 0 && !servers.containsKey(port)
|
||||
if (!stopping && state != null && state.closing == 0 && !servers.containsKey(port) && !tcpServers.containsKey(port)
|
||||
&& listenersByHostAndPort.containsKey(port)) {
|
||||
startPortServer(port, state);
|
||||
}
|
||||
@@ -482,6 +560,10 @@ public class ElbV2DataPlane {
|
||||
+ "registered but serves no traffic. {1}", String.valueOf(port), remedy);
|
||||
return;
|
||||
}
|
||||
if (servedBindings(port).anyMatch(ListenerBinding::tcp)) {
|
||||
startTcpServer(port, state);
|
||||
return;
|
||||
}
|
||||
boolean secure = portIsSecure(port);
|
||||
HttpServerOptions options = new HttpServerOptions()
|
||||
.setHost("0.0.0.0")
|
||||
@@ -525,6 +607,83 @@ public class ElbV2DataPlane {
|
||||
}
|
||||
}
|
||||
|
||||
private void startTcpServer(int port, PortState state) {
|
||||
NetServer server = vertx.createNetServer(new NetServerOptions()
|
||||
.setHost("0.0.0.0").setPort(port).setTcpKeepAlive(true));
|
||||
long generation = ++state.generation;
|
||||
tcpServers.put(port, server);
|
||||
try {
|
||||
server.connectHandler(socket -> handleTcpConnection(socket, state));
|
||||
server.listen().onSuccess(ignored -> LOG.infov("ELBv2 TCP listener port started on {0}", String.valueOf(port)))
|
||||
.onFailure(err -> onCurrentPort(port, state, () -> {
|
||||
if (state.generation == generation && tcpServers.remove(port, server)) {
|
||||
clearPortBindings(port);
|
||||
closeOwnedServer(port, state, server::close);
|
||||
} else {
|
||||
server.close();
|
||||
}
|
||||
LOG.warnv("ELBv2 TCP listener port failed to start on {0}: {1}",
|
||||
String.valueOf(port), err.getMessage());
|
||||
}));
|
||||
} catch (RuntimeException failure) {
|
||||
if (state.generation == generation && tcpServers.remove(port, server)) {
|
||||
clearPortBindings(port);
|
||||
try {
|
||||
closeOwnedServer(port, state, server::close);
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
}
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleTcpConnection(NetSocket socket, PortState state) {
|
||||
socket.pause();
|
||||
socket.exceptionHandler(err -> socket.close());
|
||||
RoutingView routing = state.routing;
|
||||
if (routing.listeners().size() != 1) {
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
RoutedListener listener = routing.listeners().values().iterator().next();
|
||||
Action action = listener.chain().stream().map(rule -> rule.action)
|
||||
.filter(candidate -> candidate != null && "forward".equals(candidate.getType()))
|
||||
.findFirst().orElse(null);
|
||||
String tgArn = action == null ? null : resolveTgArn(action);
|
||||
TargetGroup tg = tgArn == null ? null : elbV2Service.getTargetGroup(listener.region(), tgArn);
|
||||
if (tg == null || "lambda".equals(tg.getTargetType())) {
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
List<TargetDescription> candidates = targetCandidates(tgArn, tg);
|
||||
if (candidates == null) {
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
TargetDescription target = pickRoundRobin(tgArn, candidates);
|
||||
int port = ElbV2HealthChecker.effectivePort(target, tg);
|
||||
String host = ElbV2TargetResolver.resolveHost(ec2Service, tg, target);
|
||||
AtomicBoolean disconnected = new AtomicBoolean();
|
||||
socket.closeHandler(ignored -> disconnected.set(true));
|
||||
vertx.executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host))
|
||||
.compose(address -> disconnected.get() ? Future.<NetSocket>failedFuture("Client disconnected")
|
||||
: tcpClient.connect(port, address))
|
||||
.onSuccess(upstream -> {
|
||||
if (disconnected.get()) {
|
||||
upstream.close();
|
||||
return;
|
||||
}
|
||||
long idleTimeoutMillis = tcpIdleTimeoutMillis(listener.arn(), listener.region());
|
||||
tunnel(socket, upstream, idleTimeoutMillis);
|
||||
socket.resume();
|
||||
})
|
||||
.onFailure(err -> {
|
||||
LOG.debugv("ELBv2 TCP connection to {0}:{1} failed: {2}", host, port, err.getMessage());
|
||||
socket.close();
|
||||
});
|
||||
}
|
||||
|
||||
private void closePortServerIfUnused(int port, Map<String, String> listenersByHost) {
|
||||
if (listenersByHost != null && !listenersByHost.isEmpty()) {
|
||||
return;
|
||||
@@ -592,7 +751,7 @@ public class ElbV2DataPlane {
|
||||
addCertificateHosts(hosts, replacement);
|
||||
}
|
||||
return new ListenerBinding(peer.port(), peer.host(), peer.loadBalancerArn(), true,
|
||||
Set.copyOf(hosts), List.copyOf(material));
|
||||
Set.copyOf(hosts), List.copyOf(material), false);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -622,7 +781,7 @@ public class ElbV2DataPlane {
|
||||
}
|
||||
}
|
||||
return new ListenerBinding(listener.getPort(), host, listener.getLoadBalancerArn(),
|
||||
secure, Set.copyOf(hosts), List.copyOf(certificates));
|
||||
secure, Set.copyOf(hosts), List.copyOf(certificates), "TCP".equalsIgnoreCase(listener.getProtocol()));
|
||||
}
|
||||
|
||||
public void requireCompatibleListenerProtocol(String listenerArn, int port, String protocol) {
|
||||
@@ -630,21 +789,20 @@ public class ElbV2DataPlane {
|
||||
return;
|
||||
}
|
||||
onPort(port, state -> {
|
||||
requireCompatiblePort(port, "HTTPS".equalsIgnoreCase(protocol), listenerArn);
|
||||
requireCompatiblePort(port, "HTTPS".equalsIgnoreCase(protocol), "TCP".equalsIgnoreCase(protocol), listenerArn);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void requireCompatiblePort(ListenerBinding binding, String listenerArn) {
|
||||
requireCompatiblePort(binding.port(), binding.secure(), listenerArn);
|
||||
requireCompatiblePort(binding.port(), binding.secure(), binding.tcp(), listenerArn);
|
||||
}
|
||||
|
||||
private void requireCompatiblePort(int port, boolean secure, String listenerArn) {
|
||||
private void requireCompatiblePort(int port, boolean secure, boolean tcp, String listenerArn) {
|
||||
for (Map.Entry<String, ListenerBinding> entry : listenerBindings.entrySet()) {
|
||||
ListenerBinding existing = entry.getValue();
|
||||
if (!entry.getKey().equals(listenerArn)
|
||||
&& existing.port() == port
|
||||
&& existing.secure() != secure) {
|
||||
if (!entry.getKey().equals(listenerArn) && existing.port() == port && existing.secure() != secure
|
||||
&& !existing.tcp() && !tcp) {
|
||||
throw new IncompatibleListenerProtocolException(port);
|
||||
}
|
||||
}
|
||||
@@ -654,6 +812,10 @@ public class ElbV2DataPlane {
|
||||
IncompatibleListenerProtocolException(int port) {
|
||||
super("ELBv2 listeners sharing port " + port + " must use the same front-end protocol");
|
||||
}
|
||||
|
||||
IncompatibleListenerProtocolException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
private void addHostBindings(String listenerArn, ListenerBinding binding) {
|
||||
@@ -682,6 +844,11 @@ public class ElbV2DataPlane {
|
||||
|
||||
private void restartPortServer(int port) {
|
||||
PortState state = portStates.get(port);
|
||||
NetServer tcpServer = tcpServers.remove(port);
|
||||
if (tcpServer != null) {
|
||||
closeOwnedServer(port, state, tcpServer::close);
|
||||
return;
|
||||
}
|
||||
HttpServer server = servers.remove(port);
|
||||
if (server == null) {
|
||||
ensurePortServer(port);
|
||||
@@ -691,11 +858,15 @@ public class ElbV2DataPlane {
|
||||
}
|
||||
|
||||
private void closeOwnedServer(int port, PortState state, HttpServer server) {
|
||||
closeOwnedServer(port, state, server::close);
|
||||
}
|
||||
|
||||
private void closeOwnedServer(int port, PortState state, Supplier<Future<Void>> close) {
|
||||
long generation = ++state.generation;
|
||||
state.closing++;
|
||||
Future<Void> closed;
|
||||
try {
|
||||
closed = server.close();
|
||||
closed = close.get();
|
||||
} catch (RuntimeException failure) {
|
||||
state.closing--;
|
||||
throw failure;
|
||||
@@ -710,11 +881,7 @@ public class ElbV2DataPlane {
|
||||
|
||||
private PemKeyCertOptions tlsKeyCertOptions(int port) {
|
||||
Map<String, CertificateMaterial> certificates = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, ListenerBinding> entry : listenerBindings.entrySet()) {
|
||||
ListenerBinding binding = entry.getValue();
|
||||
if (binding.port() != port || !binding.secure()) {
|
||||
continue;
|
||||
}
|
||||
for (ListenerBinding binding : servedBindings(port).filter(ListenerBinding::secure).toList()) {
|
||||
for (CertificateMaterial certificate : binding.certificates()) {
|
||||
certificates.putIfAbsent(certificate.arn(), certificate);
|
||||
}
|
||||
@@ -736,8 +903,7 @@ public class ElbV2DataPlane {
|
||||
}
|
||||
|
||||
private boolean portIsSecure(int port) {
|
||||
return listenerBindings.values().stream()
|
||||
.filter(binding -> binding.port() == port)
|
||||
return servedBindings(port)
|
||||
.findFirst()
|
||||
.map(ListenerBinding::secure)
|
||||
.orElse(false);
|
||||
@@ -905,12 +1071,8 @@ public class ElbV2DataPlane {
|
||||
return;
|
||||
}
|
||||
|
||||
List<TargetDescription> allTargets = tg.getTargets();
|
||||
List<TargetDescription> healthy = allTargets.stream()
|
||||
.filter(t -> healthChecker.isHealthy(tgArn, t, ElbV2HealthChecker.effectivePort(t, tg)))
|
||||
.collect(Collectors.toList());
|
||||
List<TargetDescription> candidates = healthy.isEmpty() ? allTargets : healthy;
|
||||
if (candidates.isEmpty()) {
|
||||
List<TargetDescription> candidates = targetCandidates(tgArn, tg);
|
||||
if (candidates == null) {
|
||||
req.response().setStatusCode(503).end("No targets available");
|
||||
return;
|
||||
}
|
||||
@@ -919,9 +1081,7 @@ public class ElbV2DataPlane {
|
||||
String scope = binding != null ? binding.loadBalancerArn() + "\n" + tgArn : "";
|
||||
TargetDescription target = stickyCookie.target(req.headers().getAll("Cookie"), scope, tg, candidates, duration);
|
||||
if (target == null) {
|
||||
AtomicInteger counter = rrCounters.computeIfAbsent(tgArn, k -> new AtomicInteger(0));
|
||||
int idx = Math.abs(counter.getAndIncrement() % candidates.size());
|
||||
target = candidates.get(idx);
|
||||
target = pickRoundRobin(tgArn, candidates);
|
||||
}
|
||||
List<String> cookies = duration > 0 ? stickyCookie.headers(scope, tg, target) : List.of();
|
||||
int targetPort = ElbV2HealthChecker.effectivePort(target, tg);
|
||||
@@ -947,17 +1107,51 @@ public class ElbV2DataPlane {
|
||||
return loadBalancer.getAttributes().get(key);
|
||||
}
|
||||
|
||||
private long idleTimeoutMillis(String listenerArn, String region) {
|
||||
String configured = loadBalancerAttribute(listenerArn, region, IDLE_TIMEOUT_ATTRIBUTE);
|
||||
long seconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
|
||||
private long parseTimeoutMillis(String configured, String attributeKey, long defaultSeconds) {
|
||||
long seconds = defaultSeconds;
|
||||
if (configured != null) {
|
||||
try {
|
||||
seconds = Long.parseLong(configured.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.debugv("Ignoring non-numeric {0} value {1}", IDLE_TIMEOUT_ATTRIBUTE, configured);
|
||||
LOG.debugv("Ignoring non-numeric {0} value {1}", attributeKey, configured);
|
||||
}
|
||||
}
|
||||
return Math.max(1, seconds) * 1000;
|
||||
return Math.max(1, seconds) * 1000L;
|
||||
}
|
||||
|
||||
private long idleTimeoutMillis(String listenerArn, String region) {
|
||||
return parseTimeoutMillis(loadBalancerAttribute(listenerArn, region, IDLE_TIMEOUT_ATTRIBUTE),
|
||||
IDLE_TIMEOUT_ATTRIBUTE, DEFAULT_IDLE_TIMEOUT_SECONDS);
|
||||
}
|
||||
|
||||
private String listenerAttribute(String listenerArn, String region, String key) {
|
||||
Listener listener = elbV2Service.getListener(region, listenerArn);
|
||||
if (listener == null || listener.getAttributes() == null) {
|
||||
return null;
|
||||
}
|
||||
return listener.getAttributes().get(key);
|
||||
}
|
||||
|
||||
long tcpIdleTimeoutMillis(String listenerArn, String region) {
|
||||
return parseTimeoutMillis(listenerAttribute(listenerArn, region, TCP_IDLE_TIMEOUT_ATTRIBUTE),
|
||||
TCP_IDLE_TIMEOUT_ATTRIBUTE, TCP_IDLE_TIMEOUT_SECONDS);
|
||||
}
|
||||
|
||||
/** Healthy targets, falling back to all registered ones; null when none are registered at all. */
|
||||
private List<TargetDescription> targetCandidates(String tgArn, TargetGroup tg) {
|
||||
List<TargetDescription> all = tg.getTargets();
|
||||
List<TargetDescription> healthy = all.stream()
|
||||
.filter(t -> healthChecker.isHealthy(tgArn, t, ElbV2HealthChecker.effectivePort(t, tg)))
|
||||
.toList();
|
||||
List<TargetDescription> candidates = healthy.isEmpty() ? all : healthy;
|
||||
return candidates.isEmpty() ? null : candidates;
|
||||
}
|
||||
|
||||
private TargetDescription pickRoundRobin(String tgArn, List<TargetDescription> candidates) {
|
||||
int index = Math.floorMod(
|
||||
rrCounters.computeIfAbsent(tgArn, ignored -> new AtomicInteger()).getAndIncrement(),
|
||||
candidates.size());
|
||||
return candidates.get(index);
|
||||
}
|
||||
|
||||
private void invokeLambdaTarget(HttpServerRequest req, String functionArn, String region) {
|
||||
@@ -1331,7 +1525,8 @@ public class ElbV2DataPlane {
|
||||
|
||||
/**
|
||||
* Relays bytes both ways until either side closes or no data crosses the tunnel in either
|
||||
* direction for the load balancer's {@code idle_timeout.timeout_seconds}, as an ALB does.
|
||||
* direction for the configured idle timeout (an ALB load balancer's
|
||||
* {@code idle_timeout.timeout_seconds} or an NLB listener's {@code tcp.idle_timeout.seconds}).
|
||||
*/
|
||||
private void tunnel(NetSocket client, NetSocket target, long idleTimeoutMillis) {
|
||||
AtomicLong lastActivity = new AtomicLong(System.nanoTime());
|
||||
|
||||
@@ -405,6 +405,10 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
|
||||
return loadBalancers.getOrDefault(region, Map.of()).get(arn);
|
||||
}
|
||||
|
||||
Listener getListener(String region, String arn) {
|
||||
return listeners.getOrDefault(region, Map.of()).get(arn);
|
||||
}
|
||||
|
||||
/** Capacity reservation status for a load balancer. All fields are {@code null} when no
|
||||
* capacity is reserved, which is always the case in Floci (capacity cannot be reserved). */
|
||||
public record CapacityReservation(Integer decreaseRequestsRemaining,
|
||||
@@ -706,10 +710,33 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
|
||||
|
||||
public void modifyListenerAttributes(String region, String arn, Map<String, String> newAttrs) {
|
||||
Listener listener = requireListener(region, arn);
|
||||
validateListenerAttributes(newAttrs);
|
||||
listener.getAttributes().putAll(newAttrs);
|
||||
persistRegion(listeners, region);
|
||||
}
|
||||
|
||||
private void validateListenerAttributes(Map<String, String> newAttrs) {
|
||||
if (newAttrs == null) {
|
||||
return;
|
||||
}
|
||||
for (Map.Entry<String, String> entry : newAttrs.entrySet()) {
|
||||
if (ElbV2DataPlane.TCP_IDLE_TIMEOUT_ATTRIBUTE.equals(entry.getKey())) {
|
||||
String value = entry.getValue();
|
||||
long seconds = -1;
|
||||
try {
|
||||
seconds = Long.parseLong(value != null ? value.trim() : "");
|
||||
} catch (NumberFormatException ignored) {
|
||||
// Handled by range check below
|
||||
}
|
||||
if (seconds < ElbV2DataPlane.MIN_TCP_IDLE_TIMEOUT_SECONDS
|
||||
|| seconds > ElbV2DataPlane.MAX_TCP_IDLE_TIMEOUT_SECONDS) {
|
||||
throw new AwsException("InvalidConfigurationRequest",
|
||||
"The attribute 'tcp.idle_timeout.seconds' must be between 60 and 6000", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteListener(String region, String listenerArn) {
|
||||
while (true) {
|
||||
Map<String, Listener> regionListeners = listeners.get(region);
|
||||
|
||||
@@ -958,6 +958,30 @@ class ElbV2ServiceTest {
|
||||
assertEquals(listenerArn, listenerCaptor.getValue().getListenerArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyListenerAttributesValidatesTcpIdleTimeoutRange() {
|
||||
String lb = service.createLoadBalancer(REGION, "nlb-attr", "internal", "network", "ipv4",
|
||||
ALB_SUBNETS, List.of(), Map.of()).getLoadBalancerArn();
|
||||
Listener listener = service.createListener(REGION, lb, "TCP", 9876, null,
|
||||
List.of(), List.of(), List.of(), Map.of());
|
||||
String listenerArn = listener.getListenerArn();
|
||||
|
||||
AwsException tooLow = assertThrows(AwsException.class, () ->
|
||||
service.modifyListenerAttributes(REGION, listenerArn, Map.of("tcp.idle_timeout.seconds", "1")));
|
||||
assertEquals("InvalidConfigurationRequest", tooLow.getErrorCode());
|
||||
|
||||
AwsException tooHigh = assertThrows(AwsException.class, () ->
|
||||
service.modifyListenerAttributes(REGION, listenerArn, Map.of("tcp.idle_timeout.seconds", "6001")));
|
||||
assertEquals("InvalidConfigurationRequest", tooHigh.getErrorCode());
|
||||
|
||||
AwsException nonNumeric = assertThrows(AwsException.class, () ->
|
||||
service.modifyListenerAttributes(REGION, listenerArn, Map.of("tcp.idle_timeout.seconds", "abc")));
|
||||
assertEquals("InvalidConfigurationRequest", nonNumeric.getErrorCode());
|
||||
|
||||
service.modifyListenerAttributes(REGION, listenerArn, Map.of("tcp.idle_timeout.seconds", "120"));
|
||||
assertEquals("120", service.describeListenerAttributes(REGION, listenerArn).get("tcp.idle_timeout.seconds"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteListenerIsIgnoredForRegionWithNoListeners() {
|
||||
String emptyRegion = "eu-central-1";
|
||||
|
||||
+474
@@ -0,0 +1,474 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.Pem;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.vertx.core.Handler;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
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 jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.Action;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.ActionTypeEnum;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.FixedResponseActionConfig;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.InvalidConfigurationRequestException;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.Listener;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.ListenerAttribute;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancer;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancerTypeEnum;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.ProtocolEnum;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetDescription;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetHealthStateEnum;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetTypeEnum;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.BindException;
|
||||
import java.net.ConnectException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyStore;
|
||||
import java.time.Duration;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(RealElbV2DataPlaneProfile.class)
|
||||
class ElbV2TcpDataPlaneIntegrationTest {
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
|
||||
@Inject
|
||||
ElbV2DataPlane dataPlane;
|
||||
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
|
||||
private ElasticLoadBalancingV2Client client;
|
||||
private NetServer backend;
|
||||
private HttpServer healthBackend;
|
||||
private String loadBalancerArn;
|
||||
private String targetGroupArn;
|
||||
private String listenerArn;
|
||||
private int listenerPort;
|
||||
|
||||
@BeforeEach
|
||||
void createTcpListenerWithHealthyTarget() throws Exception {
|
||||
backend = vertx.createNetServer()
|
||||
.connectHandler(socket -> socket.handler(socket::write))
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
healthBackend = vertx.createHttpServer()
|
||||
.requestHandler(request -> request.response().end("healthy"))
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
client = ElasticLoadBalancingV2Client.builder()
|
||||
.endpointOverride(endpoint)
|
||||
.region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
|
||||
.httpClientBuilder(UrlConnectionHttpClient.builder())
|
||||
.build();
|
||||
|
||||
loadBalancerArn = client.createLoadBalancer(request -> request
|
||||
.name("tcp-regression-nlb")
|
||||
.type(LoadBalancerTypeEnum.NETWORK)
|
||||
.subnets(Ec2Service.defaultSubnetId("us-east-1", "a")))
|
||||
.loadBalancers().getFirst().loadBalancerArn();
|
||||
targetGroupArn = client.createTargetGroup(request -> request
|
||||
.name("tcp-regression-tg")
|
||||
.protocol(ProtocolEnum.TCP)
|
||||
.port(backend.actualPort())
|
||||
.vpcId(Ec2Service.defaultVpcId("us-east-1"))
|
||||
.targetType(TargetTypeEnum.IP)
|
||||
.healthCheckProtocol(ProtocolEnum.HTTP)
|
||||
.healthCheckPort(Integer.toString(healthBackend.actualPort()))
|
||||
.healthCheckIntervalSeconds(5)
|
||||
.healthyThresholdCount(2))
|
||||
.targetGroups().getFirst().targetGroupArn();
|
||||
client.registerTargets(request -> request.targetGroupArn(targetGroupArn)
|
||||
.targets(TargetDescription.builder().id("127.0.0.1").port(backend.actualPort()).build()));
|
||||
|
||||
await().atMost(Duration.ofSeconds(15)).untilAsserted(() -> assertEquals(
|
||||
TargetHealthStateEnum.HEALTHY,
|
||||
client.describeTargetHealth(request -> request.targetGroupArn(targetGroupArn))
|
||||
.targetHealthDescriptions().getFirst().targetHealth().state()));
|
||||
|
||||
try (ServerSocket reservation = new ServerSocket(0)) {
|
||||
listenerPort = reservation.getLocalPort();
|
||||
}
|
||||
listenerArn = client.createListener(request -> request
|
||||
.loadBalancerArn(loadBalancerArn)
|
||||
.protocol(ProtocolEnum.TCP)
|
||||
.port(listenerPort)
|
||||
.defaultActions(Action.builder().type(ActionTypeEnum.FORWARD)
|
||||
.targetGroupArn(targetGroupArn).build()))
|
||||
.listeners().getFirst().listenerArn();
|
||||
await().atMost(Duration.ofSeconds(5)).ignoreException(ConnectException.class).untilAsserted(() -> {
|
||||
try (Socket socket = connect(listenerPort)) {
|
||||
assertEquals(listenerPort, socket.getPort());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
assertAll("Clean up every TCP fixture resource even if another cleanup fails",
|
||||
() -> {
|
||||
if (client != null && listenerArn != null) {
|
||||
client.deleteListener(request -> request.listenerArn(listenerArn));
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (client != null && loadBalancerArn != null) {
|
||||
client.deleteLoadBalancer(request -> request.loadBalancerArn(loadBalancerArn));
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (client != null && targetGroupArn != null) {
|
||||
client.deleteTargetGroup(request -> request.targetGroupArn(targetGroupArn));
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (backend != null) {
|
||||
backend.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (healthBackend != null) {
|
||||
healthBackend.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void tcpListenerRelaysBinaryBytesWithoutInterpretingHttp() throws Exception {
|
||||
// PostgreSQL SSLRequest: valid TCP payload, not an HTTP request.
|
||||
byte[] payload = {0, 0, 0, 8, 4, (byte) 0xd2, 0x16, 0x2f};
|
||||
try (Socket direct = connect(backend.actualPort())) {
|
||||
assertEcho(direct, payload);
|
||||
}
|
||||
try (Socket socket = connect(listenerPort)) {
|
||||
assertEcho(socket, payload);
|
||||
assertEcho(socket, new byte[]{(byte) 0xff, 0, 1, 2, 13, 10, (byte) 0x80, 42});
|
||||
byte[] larger = new byte[64 * 1024];
|
||||
for (int index = 0; index < larger.length; index++) {
|
||||
larger[index] = (byte) index;
|
||||
}
|
||||
assertEcho(socket, larger);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tcpListenerPassesTlsThroughToTarget() throws Exception {
|
||||
CertificateGenerator.GeneratedCertificate certificate = new CertificateGenerator()
|
||||
.generateSelfSignedCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048);
|
||||
replaceBackend(new NetServerOptions().setSsl(true).setPemKeyCertOptions(new PemKeyCertOptions()
|
||||
.setKeyValue(Buffer.buffer(certificate.privateKeyPem()))
|
||||
.setCertValue(Buffer.buffer(certificate.certificatePem()))),
|
||||
socket -> socket.handler(socket::write));
|
||||
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||
trustStore.load(null, null);
|
||||
trustStore.setCertificateEntry("target", Pem.parseCertificate(certificate.certificatePem()));
|
||||
TrustManagerFactory trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
trust.init(trustStore);
|
||||
SSLContext context = SSLContext.getInstance("TLS");
|
||||
context.init(null, trust.getTrustManagers(), null);
|
||||
try (SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket()) {
|
||||
socket.connect(new InetSocketAddress("127.0.0.1", listenerPort), 2000);
|
||||
socket.setSoTimeout(5000);
|
||||
socket.startHandshake();
|
||||
assertEquals(Pem.parseCertificate(certificate.certificatePem()),
|
||||
socket.getSession().getPeerCertificates()[0]);
|
||||
assertEcho(socket, new byte[]{0, 1, (byte) 0xff, 13, 10});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tcpListenerRelaysServerGreetingBeforeClientSendsBytes() throws Exception {
|
||||
byte[] greeting = {0, 5, 42, (byte) 0xff};
|
||||
replaceBackend(new NetServerOptions(), socket -> {
|
||||
socket.write(Buffer.buffer(greeting));
|
||||
socket.handler(socket::write);
|
||||
});
|
||||
try (Socket socket = connect(listenerPort)) {
|
||||
assertArrayEquals(greeting, socket.getInputStream().readNBytes(greeting.length));
|
||||
assertEcho(socket, new byte[]{1, 2, 3});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tcpListenerClosesConnectionWhenNoTargetsAreRegistered() throws Exception {
|
||||
client.deregisterTargets(request -> request.targetGroupArn(targetGroupArn)
|
||||
.targets(TargetDescription.builder().id("127.0.0.1").port(backend.actualPort()).build()));
|
||||
try (Socket socket = connect(listenerPort)) {
|
||||
assertEquals(-1, socket.getInputStream().read());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tcpListenerClosesConnectionWhenTargetRefusesConnection() throws Exception {
|
||||
backend.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
backend = null;
|
||||
try (Socket socket = connect(listenerPort)) {
|
||||
assertEquals(-1, socket.getInputStream().read());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyingTcpListenerPortReleasesOldPortAndServesNewPort() throws Exception {
|
||||
int oldPort = listenerPort;
|
||||
try (ServerSocket reservation = new ServerSocket(0)) {
|
||||
listenerPort = reservation.getLocalPort();
|
||||
}
|
||||
client.modifyListener(request -> request.listenerArn(listenerArn).port(listenerPort));
|
||||
await().atMost(Duration.ofSeconds(5)).ignoreException(ConnectException.class).untilAsserted(() -> {
|
||||
try (Socket socket = connect(listenerPort)) {
|
||||
assertEcho(socket, new byte[]{0, 7, (byte) 0xff});
|
||||
}
|
||||
});
|
||||
assertPortReleased(oldPort);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingTcpListenerReleasesItsPort() {
|
||||
client.deleteListener(request -> request.listenerArn(listenerArn));
|
||||
listenerArn = null;
|
||||
assertPortReleased(listenerPort);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = ProtocolEnum.class, names = {"TCP", "HTTP"})
|
||||
void secondListenerOnTcpPortRegistersWithoutTakingThePort(ProtocolEnum protocol) throws Exception {
|
||||
String otherLbArn = client.createLoadBalancer(request -> request.name("tcp-regression-other")
|
||||
.type(protocol == ProtocolEnum.TCP ? LoadBalancerTypeEnum.NETWORK : LoadBalancerTypeEnum.APPLICATION)
|
||||
.subnets(Ec2Service.defaultSubnetId("us-east-1", "a"),
|
||||
Ec2Service.defaultSubnetId("us-east-1", "b")))
|
||||
.loadBalancers().getFirst().loadBalancerArn();
|
||||
try {
|
||||
Action action = protocol == ProtocolEnum.TCP
|
||||
? Action.builder().type(ActionTypeEnum.FORWARD).targetGroupArn(targetGroupArn).build()
|
||||
: Action.builder().type(ActionTypeEnum.FIXED_RESPONSE).fixedResponseConfig(
|
||||
FixedResponseActionConfig.builder().statusCode("200").contentType("text/plain").build()).build();
|
||||
Listener created = client.createListener(request -> request.loadBalancerArn(otherLbArn)
|
||||
.protocol(protocol).port(listenerPort).defaultActions(action))
|
||||
.listeners().getFirst();
|
||||
assertEquals(otherLbArn, created.loadBalancerArn());
|
||||
List<Listener> described = client.describeListeners(request -> request.loadBalancerArn(otherLbArn)).listeners();
|
||||
assertEquals(1, described.size());
|
||||
assertEquals(created.listenerArn(), described.getFirst().listenerArn());
|
||||
try (Socket socket = connect(listenerPort)) {
|
||||
assertEcho(socket, new byte[]{0, 8, 13, 10});
|
||||
}
|
||||
} finally {
|
||||
client.deleteLoadBalancer(request -> request.loadBalancerArn(otherLbArn));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void parkedListenerServesThePortOnceTheTcpListenerIsDeleted() throws Exception {
|
||||
LoadBalancer other = client.createLoadBalancer(
|
||||
request -> request.name("tcp-regression-parked")
|
||||
.type(LoadBalancerTypeEnum.APPLICATION)
|
||||
.subnets(Ec2Service.defaultSubnetId("us-east-1", "a"),
|
||||
Ec2Service.defaultSubnetId("us-east-1", "b")))
|
||||
.loadBalancers().getFirst();
|
||||
try {
|
||||
client.createListener(request -> request.loadBalancerArn(other.loadBalancerArn())
|
||||
.protocol(ProtocolEnum.HTTP).port(listenerPort)
|
||||
.defaultActions(Action.builder().type(ActionTypeEnum.FIXED_RESPONSE).fixedResponseConfig(
|
||||
FixedResponseActionConfig.builder().statusCode("200").contentType("text/plain")
|
||||
.messageBody("parked").build()).build()));
|
||||
try (Socket socket = connect(listenerPort)) {
|
||||
assertEcho(socket, new byte[]{0, 9, 13, 10});
|
||||
}
|
||||
|
||||
client.deleteListener(request -> request.listenerArn(listenerArn));
|
||||
listenerArn = null;
|
||||
|
||||
await().atMost(Duration.ofSeconds(5)).ignoreExceptions().untilAsserted(() -> {
|
||||
try (Socket socket = connect(listenerPort)) {
|
||||
socket.setSoTimeout(2000);
|
||||
socket.getOutputStream().write(("GET / HTTP/1.1\r\nHost: " + other.dnsName()
|
||||
+ "\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
|
||||
String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII);
|
||||
assertTrue(response.startsWith("HTTP/1.1 200"), response);
|
||||
assertTrue(response.endsWith("parked"), response);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
client.deleteLoadBalancer(request -> request.loadBalancerArn(other.loadBalancerArn()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tcpConnectionsUseRoundRobinAndKeepTheirSelectedTarget() throws Exception {
|
||||
NetServer second = vertx.createNetServer().connectHandler(socket -> socket.handler(buffer -> {
|
||||
byte[] bytes = buffer.getBytes();
|
||||
for (int index = 0; index < bytes.length; index++) {
|
||||
bytes[index]++;
|
||||
}
|
||||
socket.write(Buffer.buffer(bytes));
|
||||
})).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
try {
|
||||
client.registerTargets(request -> request.targetGroupArn(targetGroupArn).targets(TargetDescription.builder()
|
||||
.id("127.0.0.1").port(second.actualPort()).build()));
|
||||
await().atMost(Duration.ofSeconds(15)).untilAsserted(() -> {
|
||||
List<TargetHealthStateEnum> states = client.describeTargetHealth(request -> request
|
||||
.targetGroupArn(targetGroupArn)).targetHealthDescriptions().stream()
|
||||
.map(description -> description.targetHealth().state()).toList();
|
||||
assertEquals(List.of(TargetHealthStateEnum.HEALTHY, TargetHealthStateEnum.HEALTHY), states);
|
||||
});
|
||||
Set<Integer> replies = new HashSet<>();
|
||||
for (int index = 0; index < 2; index++) {
|
||||
try (Socket socket = connect(listenerPort)) {
|
||||
socket.getOutputStream().write(42);
|
||||
int reply = socket.getInputStream().read();
|
||||
replies.add(reply);
|
||||
socket.getOutputStream().write(42);
|
||||
assertEquals(reply, socket.getInputStream().read(), "A connection must keep its selected target");
|
||||
}
|
||||
}
|
||||
assertEquals(Set.of(42, 43), replies);
|
||||
} finally {
|
||||
assertAll("Deregister and close the second TCP target",
|
||||
() -> client.deregisterTargets(request -> request.targetGroupArn(targetGroupArn)
|
||||
.targets(TargetDescription.builder().id("127.0.0.1").port(second.actualPort()).build())),
|
||||
() -> second.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatingForwardActionOnlyChangesNewTcpConnections() throws Exception {
|
||||
String emptyTgArn = client.createTargetGroup(request -> request.name("tcp-regression-empty")
|
||||
.protocol(ProtocolEnum.TCP).port(12345).vpcId(Ec2Service.defaultVpcId("us-east-1"))
|
||||
.targetType(TargetTypeEnum.IP)).targetGroups().getFirst().targetGroupArn();
|
||||
try {
|
||||
try (Socket established = connect(listenerPort)) {
|
||||
assertEcho(established, new byte[]{0, 1, 2});
|
||||
client.modifyListener(request -> request.listenerArn(listenerArn).defaultActions(Action.builder()
|
||||
.type(ActionTypeEnum.FORWARD).targetGroupArn(emptyTgArn).build()));
|
||||
try (Socket next = connect(listenerPort)) {
|
||||
assertEquals(-1, next.getInputStream().read());
|
||||
}
|
||||
assertEcho(established, new byte[]{3, 4, 5});
|
||||
}
|
||||
} finally {
|
||||
assertAll("Restore the listener and delete the temporary target group",
|
||||
() -> client.modifyListener(request -> request.listenerArn(listenerArn).defaultActions(Action.builder()
|
||||
.type(ActionTypeEnum.FORWARD).targetGroupArn(targetGroupArn).build())),
|
||||
() -> client.deleteTargetGroup(request -> request.targetGroupArn(emptyTgArn)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsOutOfRangeTcpIdleTimeout() {
|
||||
InvalidConfigurationRequestException tooLow = assertThrows(InvalidConfigurationRequestException.class,
|
||||
() -> client.modifyListenerAttributes(request -> request.listenerArn(listenerArn)
|
||||
.attributes(ListenerAttribute.builder().key("tcp.idle_timeout.seconds").value("1").build())));
|
||||
assertEquals("InvalidConfigurationRequest", tooLow.awsErrorDetails().errorCode());
|
||||
|
||||
InvalidConfigurationRequestException tooHigh = assertThrows(InvalidConfigurationRequestException.class,
|
||||
() -> client.modifyListenerAttributes(request -> request.listenerArn(listenerArn)
|
||||
.attributes(ListenerAttribute.builder().key("tcp.idle_timeout.seconds").value("6001").build())));
|
||||
assertEquals("InvalidConfigurationRequest", tooHigh.awsErrorDetails().errorCode());
|
||||
|
||||
InvalidConfigurationRequestException nonNumeric = assertThrows(InvalidConfigurationRequestException.class,
|
||||
() -> client.modifyListenerAttributes(request -> request.listenerArn(listenerArn)
|
||||
.attributes(ListenerAttribute.builder().key("tcp.idle_timeout.seconds").value("not-a-number").build())));
|
||||
assertEquals("InvalidConfigurationRequest", nonNumeric.awsErrorDetails().errorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void relayReadsConfiguredTcpIdleTimeout() {
|
||||
assertEquals(350_000L, dataPlane.tcpIdleTimeoutMillis(listenerArn, "us-east-1"));
|
||||
|
||||
client.modifyListenerAttributes(request -> request.listenerArn(listenerArn)
|
||||
.attributes(ListenerAttribute.builder().key("tcp.idle_timeout.seconds").value("120").build()));
|
||||
assertEquals(120_000L, dataPlane.tcpIdleTimeoutMillis(listenerArn, "us-east-1"));
|
||||
}
|
||||
|
||||
private void replaceBackend(NetServerOptions options, Handler<NetSocket> handler) throws Exception {
|
||||
int port = backend.actualPort();
|
||||
backend.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
backend = vertx.createNetServer(options).connectHandler(handler).listen(port, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static Socket connect(int port) throws IOException {
|
||||
Socket socket = new Socket();
|
||||
try {
|
||||
socket.connect(new InetSocketAddress("127.0.0.1", port), 2000);
|
||||
socket.setSoTimeout(3000);
|
||||
return socket;
|
||||
} catch (IOException failure) {
|
||||
try {
|
||||
socket.close();
|
||||
} catch (IOException cleanupFailure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertPortReleased(int port) {
|
||||
await().atMost(Duration.ofSeconds(5)).ignoreException(BindException.class).untilAsserted(() -> {
|
||||
assertThrows(ConnectException.class, () -> {
|
||||
try (Socket socket = connect(port)) {
|
||||
assertEquals(port, socket.getPort());
|
||||
}
|
||||
});
|
||||
try (ServerSocket reservation = new ServerSocket()) {
|
||||
reservation.setReuseAddress(true);
|
||||
reservation.bind(new InetSocketAddress("0.0.0.0", port));
|
||||
assertEquals(port, reservation.getLocalPort());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void assertEcho(Socket socket, byte[] payload) throws IOException {
|
||||
socket.getOutputStream().write(payload);
|
||||
socket.getOutputStream().flush();
|
||||
assertArrayEquals(payload, socket.getInputStream().readNBytes(payload.length),
|
||||
"TCP traffic must reach the echo target unchanged, without an HTTP response");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user