From 9c2a2c2a029e76c1aa5db9366c4181e7c8882412 Mon Sep 17 00:00:00 2001 From: Andre Kurait Date: Tue, 3 Nov 2026 14:29:45 -0600 Subject: [PATCH] fix(elbv2): honor backend TLS and bound health probes (#7433) --- docs/services/elb.md | 30 +- .../common/concurrent/SocketDeadline.java | 80 ++++ .../floci/services/elbv2/ElbV2DataPlane.java | 56 ++- .../services/elbv2/ElbV2HealthChecker.java | 169 +++++-- .../floci/services/elbv2/ElbV2Service.java | 11 + .../common/concurrent/SocketDeadlineTest.java | 127 +++++ .../elbv2/ElbV2BackendTlsIntegrationTest.java | 445 ++++++++++++++++++ .../elbv2/ElbV2HealthCheckerTest.java | 189 +++++++- .../ElbV2HealthTimeoutIntegrationTest.java | 66 +++ ...lbV2PreserveHostHeaderIntegrationTest.java | 2 +- .../services/elbv2/ElbV2ServiceTest.java | 46 ++ 11 files changed, 1150 insertions(+), 71 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/core/common/concurrent/SocketDeadline.java create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/concurrent/SocketDeadlineTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2BackendTlsIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthTimeoutIntegrationTest.java diff --git a/docs/services/elb.md b/docs/services/elb.md index 4e9db3942b..762426dd0e 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -88,6 +88,25 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on ## Behavior Notes +- HTTP and HTTPS target groups use their configured protocol for both application requests + and WebSocket upgrades. An HTTPS target requires a TLS handshake; a failed handshake + never falls back to plaintext. Backend certificates may be self-signed or expired, as on + AWS ALB. This trust setting applies only to the target clients and health checks. +- Backend connection and TLS handshake errors return 502 for HTTP requests and WebSocket + upgrades. Connection and handshake timeouts use ten-second deadlines and return 504. +- HTTP and HTTPS health checks use their own configured protocol and port, independently + of the target's application protocol. HTTPS health checks require a TLS handshake, + preserve the configured success-code matcher, and do not follow redirects. +- One health-check deadline covers connection, TLS handshake and response headers. + Partial bytes do not renew it. Expiry closes the probe and counts toward `Target.Timeout`. +- Health probes connect directly without JVM proxy settings. A timed-out lookup keeps + its target and shared worker slot until the underlying work actually exits. This bounds + background work even when name resolution ignores interruption. +- Backend TLS uses the runtime's supported protocols and ciphers. Floci does not reproduce + AWS ALB's backend security-policy selection from the frontend listener policy. +- ALB listeners share the emulator's network address. Stored subnet and security-group + associations do not create a load-balancer VPC network boundary or enforce frontend + ingress and backend egress rules. These listeners cannot yet reproduce NAT allowlisting failures. - 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. @@ -150,8 +169,8 @@ 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. | +| `HTTP` | Parses and forwards HTTP requests; supports WebSocket upgrades. | `instance` resolves an EC2 private address; `ip` uses the registered address. The target-group protocol selects HTTP or HTTPS to the backend. `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 and backend protocol selection as HTTP. | | `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. | @@ -165,11 +184,12 @@ on the listener socket. ### Health checks -For non-Lambda targets, the checker sends a **plain HTTP GET** to `HealthCheckPath` +For non-Lambda targets, the checker sends an HTTP or HTTPS GET to `HealthCheckPath` on `HealthCheckPort`, or the target's traffic port when configured as `traffic-port`. +`HealthCheckProtocol` selects TLS independently of the target's application protocol. The response-code matcher and healthy/unhealthy thresholds affect target health. -`HealthCheckProtocol=TCP` does not perform a TCP-only probe, and `HTTPS` does not enable -TLS for the probe. Lambda targets are not actively probed. In ELBv2 mock mode, sockets +`HealthCheckProtocol=TCP` does not perform a TCP-only probe. +Lambda targets are not actively probed. In ELBv2 mock mode, sockets and active monitoring are disabled. The proxy can route to initial targets and fails open to registered targets when none are healthy, so a successful request alone does not prove that a health check passed. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/concurrent/SocketDeadline.java b/src/main/java/io/github/hectorvent/floci/core/common/concurrent/SocketDeadline.java new file mode 100644 index 0000000000..6611ca481f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/concurrent/SocketDeadline.java @@ -0,0 +1,80 @@ +package io.github.hectorvent.floci.core.common.concurrent; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.net.SocketTimeoutException; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; + +/** One deadline for socket operations, including peers that continually send incomplete responses. */ +public final class SocketDeadline { + + private SocketDeadline() {} + + public static T call(int timeoutSeconds, Callable operation) throws IOException { + return call(timeoutSeconds, operation, () -> {}); + } + + /** + * Releases worker ownership before publishing a normal result. Cancelled work retains ownership + * until it actually finishes, even when it ignores interruption. + */ + public static T call(int timeoutSeconds, Callable operation, Runnable onWorkerExit) throws IOException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds); + AtomicBoolean exited = new AtomicBoolean(); + Runnable finish = () -> { + if (exited.compareAndSet(false, true)) { + onWorkerExit.run(); + } + }; + FutureTask result = new FutureTask<>(() -> { + try { + return operation.call(); + } finally { + // Publish an ordinary result only after resource admission is released. + finish.run(); + } + }); + // Interrupting a virtual thread closes its blocking java.net sockets. + try { + Thread.ofVirtual().name("socket-deadline").start(() -> { + try { + result.run(); + } finally { + finish.run(); + } + }); + } catch (RuntimeException | Error failure) { + finish.run(); + throw failure; + } + try { + return result.get(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS); + } catch (TimeoutException timeout) { + throw new SocketTimeoutException("Socket operation exceeded " + timeoutSeconds + " seconds"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + InterruptedIOException failure = new InterruptedIOException("Socket operation interrupted"); + failure.initCause(interrupted); + throw failure; + } catch (ExecutionException failed) { + Throwable cause = failed.getCause(); + if (cause instanceof IOException io) { + throw io; + } + if (cause instanceof RuntimeException runtime) { + throw runtime; + } + if (cause instanceof Error error) { + throw error; + } + throw new IOException("Socket operation failed", cause); + } finally { + result.cancel(true); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java index 05426f39ab..a3a428ab72 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java @@ -21,6 +21,8 @@ import io.github.hectorvent.floci.services.elbv2.model.TargetGroup; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.InvocationType; import io.github.hectorvent.floci.services.lambda.model.InvokeResult; +import io.netty.channel.ConnectTimeoutException; +import io.netty.handler.ssl.SslHandshakeTimeoutException; import io.vertx.core.Future; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; @@ -53,6 +55,7 @@ import javax.naming.ldap.Rdn; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.net.SocketTimeoutException; import java.nio.charset.StandardCharsets; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; @@ -70,6 +73,8 @@ import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; @@ -226,8 +231,12 @@ public class ElbV2DataPlane { @PostConstruct void init() { proxyClient = vertx.createHttpClient(new HttpClientOptions() + .setTrustAll(true) + .setVerifyHost(false) .setMaxPoolSize(100) - .setConnectTimeout(5000) + .setConnectTimeout(10_000) + .setSslHandshakeTimeout(10) + .setSslHandshakeTimeoutUnit(TimeUnit.SECONDS) .setKeepAlive(true) .setMaxHeaderSize(MAX_RESPONSE_HEADER_SIZE)); tcpClient = vertx.createNetClient(new NetClientOptions().setConnectTimeout(5000) @@ -1100,12 +1109,13 @@ public class ElbV2DataPlane { List cookies = duration > 0 ? stickyCookie.headers(scope, tg, target) : List.of(); int targetPort = ElbV2HealthChecker.effectivePort(target, tg); String host = ElbV2TargetResolver.resolveHost(ec2Service, tg, target); + boolean secure = "HTTPS".equals(tg.getProtocol()); if (isWebSocketUpgrade(req)) { - proxyUpgrade(req, host, targetPort, hostHeader, forwarded, + proxyUpgrade(req, host, targetPort, secure, hostHeader, forwarded, idleTimeoutMillis(listenerArn, region), cookies); return; } - proxyRequest(req, host, targetPort, hostHeader, forwarded, cookies); + proxyRequest(req, host, targetPort, secure, hostHeader, forwarded, cookies); } private String loadBalancerAttribute(String listenerArn, String region, String key) { @@ -1365,20 +1375,20 @@ public class ElbV2DataPlane { return tuples.get(tuples.size() - 1).getTargetGroupArn(); } - private void proxyRequest(HttpServerRequest req, String host, int port, String hostHeader, + private void proxyRequest(HttpServerRequest req, String host, int port, boolean secure, String hostHeader, ElbV2ForwardedHeaders forwarded, List cookies) { req.pause(); if (ElbV2TargetResolver.isIpLiteral(host)) { try { proxyRequestTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port, - hostHeader, forwarded, cookies); + secure, hostHeader, forwarded, cookies); } catch (IOException e) { rejectTarget(req, host, e); } return; } vertx.executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host)) - .onSuccess(address -> proxyRequestTo(req, address, host, port, hostHeader, forwarded, cookies)) + .onSuccess(address -> proxyRequestTo(req, address, host, port, secure, hostHeader, forwarded, cookies)) .onFailure(err -> rejectTarget(req, host, err)); } @@ -1388,9 +1398,10 @@ public class ElbV2DataPlane { req.response().setStatusCode(503).end("Service unavailable"); } - private void proxyRequestTo(HttpServerRequest req, String address, String host, int port, + private void proxyRequestTo(HttpServerRequest req, String address, String host, int port, boolean secure, String hostHeader, ElbV2ForwardedHeaders forwarded, List cookies) { RequestOptions opts = new RequestOptions() + .setSsl(secure) .setHost(address) .setPort(port) .setURI(req.uri()) @@ -1442,10 +1453,19 @@ public class ElbV2DataPlane { clientReq.send(req); req.resume(); }) - .onFailure(err -> { - req.resume(); - req.response().setStatusCode(503).end("Service unavailable"); - }); + .onFailure(err -> backendConnectionFailed(req, err)); + } + + private void backendConnectionFailed(HttpServerRequest req, Throwable error) { + req.resume(); + for (Throwable cause = error; cause != null; cause = cause.getCause()) { + if (cause instanceof ConnectTimeoutException || cause instanceof SslHandshakeTimeoutException + || cause instanceof SocketTimeoutException || cause instanceof TimeoutException) { + req.response().setStatusCode(504).end("Gateway timeout"); + return; + } + } + req.response().setStatusCode(502).end("Bad gateway"); } private static void copyTargetResponseHeaders(MultiMap headers, HttpServerResponse response) { @@ -1461,20 +1481,20 @@ public class ElbV2DataPlane { return WebSocketUpgrades.isHandshake(req); } - private void proxyUpgrade(HttpServerRequest req, String host, int port, String hostHeader, + private void proxyUpgrade(HttpServerRequest req, String host, int port, boolean secure, String hostHeader, ElbV2ForwardedHeaders forwarded, long idleTimeoutMillis, List cookies) { req.pause(); if (ElbV2TargetResolver.isIpLiteral(host)) { try { proxyUpgradeTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port, - hostHeader, forwarded, idleTimeoutMillis, cookies); + secure, hostHeader, forwarded, idleTimeoutMillis, cookies); } catch (IOException e) { rejectTarget(req, host, e); } return; } vertx.executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host)) - .onSuccess(address -> proxyUpgradeTo(req, address, host, port, hostHeader, + .onSuccess(address -> proxyUpgradeTo(req, address, host, port, secure, hostHeader, forwarded, idleTimeoutMillis, cookies)) .onFailure(err -> rejectTarget(req, host, err)); } @@ -1484,10 +1504,11 @@ public class ElbV2DataPlane { * relays that answer and joins the two connections into a byte tunnel. Any other answer means * the target refused the upgrade and is relayed as an ordinary response. */ - private void proxyUpgradeTo(HttpServerRequest req, String address, String host, int port, + private void proxyUpgradeTo(HttpServerRequest req, String address, String host, int port, boolean secure, String hostHeader, ElbV2ForwardedHeaders forwarded, long idleTimeoutMillis, List cookies) { RequestOptions opts = new RequestOptions() + .setSsl(secure) .setHost(address) .setPort(port) .setURI(req.uri()) @@ -1541,10 +1562,7 @@ public class ElbV2DataPlane { } }); }) - .onFailure(err -> { - req.resume(); - req.response().setStatusCode(503).end("Service unavailable"); - }); + .onFailure(err -> backendConnectionFailed(req, err)); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java index 789aed7561..e46f94fa63 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java @@ -2,42 +2,57 @@ package io.github.hectorvent.floci.services.elbv2; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.Resettable; +import io.github.hectorvent.floci.core.common.concurrent.SocketDeadline; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.elbv2.model.TargetDescription; import io.github.hectorvent.floci.services.elbv2.model.TargetGroup; +import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.vertx.core.Vertx; +import io.vertx.core.WorkerExecutor; +import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; import java.io.IOException; import java.net.HttpURLConnection; +import java.net.Proxy; import java.net.SocketTimeoutException; import java.net.URL; +import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Semaphore; @ApplicationScoped public class ElbV2HealthChecker implements Resettable { private static final Logger LOG = Logger.getLogger(ElbV2HealthChecker.class); + private static final int MAX_CONCURRENT_PROBES = 32; private final Vertx vertx; + private final WorkerExecutor probeWorkers; private final EmulatorConfig config; private final Ec2Service ec2Service; + private final SSLSocketFactory backendTls = backendTls(); // tgArn → (targetKey → TargetState) private final Map> states = new ConcurrentHashMap<>(); // tgArn → timerId private final Map timers = new ConcurrentHashMap<>(); + private final Semaphore probeSlots = new Semaphore(MAX_CONCURRENT_PROBES); @Inject public ElbV2HealthChecker(Vertx vertx, EmulatorConfig config, Ec2Service ec2Service) { this.vertx = vertx; this.config = config; this.ec2Service = ec2Service; + this.probeWorkers = vertx.createSharedWorkerExecutor("floci-elbv2-health-probes", MAX_CONCURRENT_PROBES); } public static int effectivePort(TargetDescription target, TargetGroup tg) { @@ -79,6 +94,12 @@ public class ElbV2HealthChecker implements Resettable { states.clear(); } + @PreDestroy + void destroy() { + clear(); + probeWorkers.close(); + } + public void addTargets(String tgArn, List targets, TargetGroup tg) { if (config.services().elbv2().mock()) { return; @@ -118,7 +139,9 @@ public class ElbV2HealthChecker implements Resettable { if (s == null) { return TargetHealthStatus.registrationInProgress(); } - return new TargetHealthStatus(s.status, s.reason, s.description); + synchronized (s) { + return new TargetHealthStatus(s.status, s.reason, s.description); + } } public boolean isHealthy(String tgArn, TargetDescription target, int port) { @@ -145,7 +168,7 @@ public class ElbV2HealthChecker implements Resettable { } catch (NumberFormatException e) { continue; } - String host = ElbV2TargetResolver.resolveHost(ec2Service, tg, targetId); + String protocol = tg.getHealthCheckProtocol(); String path = tg.getHealthCheckPath() != null ? tg.getHealthCheckPath() : "/"; String matcher = tg.getMatcher() != null ? tg.getMatcher() : "200"; int timeout = tg.getHealthCheckTimeoutSeconds() != null ? tg.getHealthCheckTimeoutSeconds() : 5; @@ -153,54 +176,99 @@ public class ElbV2HealthChecker implements Resettable { int unhealthyThreshold = tg.getUnhealthyThresholdCount() != null ? tg.getUnhealthyThresholdCount() : 2; int probePort = healthCheckPort(tg, port); - vertx.executeBlocking(() -> { - return probe(host, probePort, path, timeout); - }).onSuccess(statusCode -> { - boolean success = matchesStatusCode(statusCode, matcher); - if (success) { - state.consecutiveFailures = 0; - state.consecutiveSuccesses++; - boolean initialApplicationTarget = "initial".equals(state.status) - && ("HTTP".equals(tg.getProtocol()) || "HTTPS".equals(tg.getProtocol()) - || "lambda".equals(tg.getTargetType())); - if (initialApplicationTarget || state.consecutiveSuccesses >= healthyThreshold) { - state.status = "healthy"; - state.reason = null; - state.description = null; - } else if ("initial".equals(state.status)) { - state.reason = "Elb.InitialHealthChecking"; - state.description = "Initial health checks in progress"; - } - } else { - state.consecutiveSuccesses = 0; - state.consecutiveFailures++; - if (state.consecutiveFailures >= unhealthyThreshold) { - state.status = "unhealthy"; - state.reason = "Target.ResponseCodeMismatch"; - state.description = "Health checks failed with these codes: [" + statusCode + "]"; - } + synchronized (state) { + if (state.inFlight || state.workerRunning) { + continue; } - }).onFailure(err -> { - state.consecutiveSuccesses = 0; - state.consecutiveFailures++; - if (state.consecutiveFailures >= unhealthyThreshold) { - state.status = "unhealthy"; - if (isTimeout(err)) { - state.reason = "Target.Timeout"; - state.description = "Request timed out"; - } else { - state.reason = "Target.FailedHealthChecks"; - state.description = "Health checks failed"; + state.inFlight = true; + } + try { + probeWorkers.executeBlocking(() -> { + synchronized (state) { + if (states.get(tgArn) != tgStates || tgStates.get(key) != state + || !probeSlots.tryAcquire()) { + return null; + } + state.workerRunning = true; } + return SocketDeadline.call(timeout, () -> { + String host = ElbV2TargetResolver.resolveHost(ec2Service, tg, targetId); + return probeOnce(host, probePort, path, timeout, protocol); + }, () -> { + synchronized (state) { + state.workerRunning = false; + probeSlots.release(); + } + }); + }, false).onComplete(outcome -> { + synchronized (state) { + try { + if (states.get(tgArn) != tgStates || tgStates.get(key) != state) { + return; + } + if (outcome.failed()) { + state.consecutiveSuccesses = 0; + state.consecutiveFailures++; + if (state.consecutiveFailures >= unhealthyThreshold) { + state.status = "unhealthy"; + if (isTimeout(outcome.cause())) { + state.reason = "Target.Timeout"; + state.description = "Request timed out"; + } else { + state.reason = "Target.FailedHealthChecks"; + state.description = "Health checks failed"; + } + } + LOG.debugv("Health check failed for {0}:{1} - {2}", + targetId, port, outcome.cause().getMessage()); + } else if (outcome.result() != null) { + int statusCode = outcome.result(); + if (matchesStatusCode(statusCode, matcher)) { + state.consecutiveFailures = 0; + state.consecutiveSuccesses++; + boolean initialApplicationTarget = "initial".equals(state.status) + && ("HTTP".equals(tg.getProtocol()) || "HTTPS".equals(tg.getProtocol()) + || "lambda".equals(tg.getTargetType())); + if (initialApplicationTarget || state.consecutiveSuccesses >= healthyThreshold) { + state.status = "healthy"; + state.reason = null; + state.description = null; + } else if ("initial".equals(state.status)) { + state.reason = "Elb.InitialHealthChecking"; + state.description = "Initial health checks in progress"; + } + } else { + state.consecutiveSuccesses = 0; + state.consecutiveFailures++; + if (state.consecutiveFailures >= unhealthyThreshold) { + state.status = "unhealthy"; + state.reason = "Target.ResponseCodeMismatch"; + state.description = "Health checks failed with these codes: [" + statusCode + "]"; + } + } + } + } finally { + state.inFlight = false; + } + } + }); + } catch (RuntimeException | Error error) { + synchronized (state) { + state.inFlight = false; } - LOG.debugv("Health check failed for {0}:{1} - {2}", host, port, err.getMessage()); - }); + throw error; + } } } - private int probe(String host, int port, String path, int timeoutSeconds) throws IOException { - URL url = new URL("http", ElbV2TargetResolver.resolveCheckedAddress(host), port, path); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + private int probeOnce(String host, int port, String path, int timeoutSeconds, String protocol) throws IOException { + String scheme = "HTTPS".equals(protocol) ? "https" : "http"; + URL url = new URL(scheme, ElbV2TargetResolver.resolveCheckedAddress(host), port, path); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); + if (conn instanceof HttpsURLConnection https) { + https.setSSLSocketFactory(backendTls); + https.setHostnameVerifier((hostname, session) -> true); + } conn.setConnectTimeout(timeoutSeconds * 1000); conn.setReadTimeout(timeoutSeconds * 1000); conn.setRequestMethod("GET"); @@ -213,6 +281,17 @@ public class ElbV2HealthChecker implements Resettable { } } + private static SSLSocketFactory backendTls() { + try { + // ALB encrypts target connections without validating target certificates. + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null); + return context.getSocketFactory(); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Cannot initialize ELBv2 backend TLS", e); + } + } + /** * AWS probes {@code HealthCheckPort} when it is a number and the target's own port when it is * {@code traffic-port} or unset. Health state stays keyed by the traffic port either way. @@ -286,6 +365,8 @@ public class ElbV2HealthChecker implements Resettable { } private static class TargetState { + boolean inFlight; + boolean workerRunning; volatile String status = "initial"; volatile String reason = "Elb.RegistrationInProgress"; volatile String description = "Target registration is in progress"; diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java index 0476094b32..eb3079cfe2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java @@ -494,6 +494,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc Integer healthyThreshold, Integer unhealthyThreshold, String matcher, String ipAddressType, Map initialTags) { + validateHealthCheckTimeout(healthCheckTimeout); validatePort(port, "port"); validateName(name, "target group"); if (port == null && !"lambda".equals(targetType)) { @@ -592,6 +593,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc String healthCheckPath, Integer healthCheckInterval, Integer healthCheckTimeout, Integer healthyThreshold, Integer unhealthyThreshold, String matcher) { + validateHealthCheckTimeout(healthCheckTimeout); TargetGroup tg = requireTargetGroup(region, arn); validateHealthCheckPort(healthCheckPort); if (healthCheckProtocol != null) tg.setHealthCheckProtocol(healthCheckProtocol); @@ -606,6 +608,15 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc persistRegion(targetGroups, region); } + private static void validateHealthCheckTimeout(Integer timeout) { + if (timeout != null && (timeout < 2 || timeout > 120)) { + String constraint = timeout < 2 ? "greater than or equal to 2" : "less than or equal to 120"; + throw new AwsException("ValidationError", "1 validation error detected: Value '" + timeout + + "' at 'healthCheckTimeoutSeconds' failed to satisfy constraint: Member must have value " + + constraint, 400); + } + } + public Map describeTargetGroupAttributes(String region, String arn) { TargetGroup tg = requireTargetGroup(region, arn); return ElbV2DefaultAttributes.merge(ElbV2DefaultAttributes.forTargetGroup(tg), tg.getAttributes()); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/concurrent/SocketDeadlineTest.java b/src/test/java/io/github/hectorvent/floci/core/common/concurrent/SocketDeadlineTest.java new file mode 100644 index 0000000000..aeadc38d1f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/concurrent/SocketDeadlineTest.java @@ -0,0 +1,127 @@ +package io.github.hectorvent.floci.core.common.concurrent; + +import io.github.hectorvent.floci.testing.ThreadStates; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.net.SocketTimeoutException; +import java.time.Duration; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.*; + +class SocketDeadlineTest { + + @Test + void resultWaitsForAdmissionCleanup() throws Exception { + assertCleanupBeforeCompletion(false); + } + + @Test + void failureWaitsForAdmissionCleanup() throws Exception { + assertCleanupBeforeCompletion(true); + } + + private void assertCleanupBeforeCompletion(boolean fail) throws Exception { + CountDownLatch cleaning = new CountDownLatch(1); + CompletableFuture release = new CompletableFuture<>(); + AtomicInteger exits = new AtomicInteger(); + IOException failure = new IOException("probe failed"); + FutureTask result = new FutureTask<>(() -> SocketDeadline.call(10, () -> { + if (fail) { + throw failure; + } + return "healthy"; + }, () -> { + cleaning.countDown(); + release.join(); + exits.incrementAndGet(); + })); + Thread caller = Thread.ofVirtual().start(result); + try { + assertTrue(cleaning.await(5, TimeUnit.SECONDS)); + ThreadStates.awaitState(caller, Set.of(Thread.State.TIMED_WAITING, Thread.State.TERMINATED), + Duration.ofSeconds(5), "probe caller"); + assertFalse(result.isDone(), "the next queued probe must not run before admission cleanup"); + } finally { + release.complete(null); + caller.join(5000); + assertFalse(caller.isAlive()); + } + if (fail) { + assertSame(failure, assertThrows(ExecutionException.class, + () -> result.get(5, TimeUnit.SECONDS)).getCause()); + } else { + assertEquals("healthy", result.get(5, TimeUnit.SECONDS)); + } + assertEquals(1, exits.get()); + } + + @Test + void interruptedCallerRetainsAdmissionUntilIgnoringWorkerFinishes() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch exited = new CountDownLatch(1); + CompletableFuture release = new CompletableFuture<>(); + AtomicInteger exits = new AtomicInteger(); + FutureTask result = new FutureTask<>(() -> SocketDeadline.call(10, () -> { + started.countDown(); + release.join(); + return "late"; + }, () -> { + exits.incrementAndGet(); + exited.countDown(); + })); + Thread caller = Thread.ofVirtual().start(result); + try { + assertTrue(started.await(5, TimeUnit.SECONDS)); + caller.interrupt(); + ExecutionException failure = assertThrows(ExecutionException.class, + () -> result.get(5, TimeUnit.SECONDS)); + assertInstanceOf(InterruptedIOException.class, failure.getCause()); + assertEquals(0, exits.get(), "cancellation must not release a running probe's permit"); + } finally { + release.complete(null); + assertTrue(exited.await(5, TimeUnit.SECONDS)); + caller.join(5000); + assertFalse(caller.isAlive()); + } + assertEquals(1, exits.get()); + } + + @Test + void expiredCallsAlwaysReleaseAdmissionExactlyOnce() throws Exception { + for (int attempt = 0; attempt < 100; attempt++) { + CountDownLatch exited = new CountDownLatch(1); + AtomicInteger exits = new AtomicInteger(); + try { + SocketDeadline.call(0, () -> "healthy", () -> { + exits.incrementAndGet(); + exited.countDown(); + }); + } catch (SocketTimeoutException expected) { + // The deadline may expire before the callable starts; cleanup is still required. + } + assertTrue(exited.await(5, TimeUnit.SECONDS)); + assertEquals(1, exits.get()); + } + } + + @Test + void cleanupFailureIsReportedOnce() { + IllegalStateException failure = new IllegalStateException("cleanup failed"); + AtomicInteger exits = new AtomicInteger(); + assertSame(failure, assertThrows(IllegalStateException.class, + () -> SocketDeadline.call(10, () -> "healthy", () -> { + exits.incrementAndGet(); + throw failure; + }))); + assertEquals(1, exits.get()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2BackendTlsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2BackendTlsIntegrationTest.java new file mode 100644 index 0000000000..e618dea331 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2BackendTlsIntegrationTest.java @@ -0,0 +1,445 @@ +package io.github.hectorvent.floci.services.elbv2; + +import io.github.hectorvent.floci.services.acm.CertificateGenerator; +import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; +import io.github.hectorvent.floci.testing.AwsTestClients; +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.Vertx; +import io.vertx.core.buffer.Buffer; +import io.vertx.core.http.HttpClient; +import io.vertx.core.http.HttpServer; +import io.vertx.core.http.HttpServerOptions; +import io.vertx.core.http.UpgradeRejectedException; +import io.vertx.core.http.WebSocket; +import io.vertx.core.http.WebSocketConnectOptions; +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.api.function.Executable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.Action; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancer; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.Matcher; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetDescription; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetHealthDescription; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.*; + +@QuarkusTest +@TestProfile(RealElbV2DataPlaneProfile.class) +class ElbV2BackendTlsIntegrationTest { + + private final String name = "alb-tls-" + UUID.randomUUID().toString().substring(0, 8); + private final List cleanup = new ArrayList<>(); + private final AtomicInteger healthStatus = new AtomicInteger(200); + private final AtomicBoolean encrypted = new AtomicBoolean(); + private final AtomicReference received = new AtomicReference<>(); + private Ec2Client ec2; + private ElasticLoadBalancingV2Client elb; + private String vpc; + private List subnets; + private String groupArn; + private String dns; + private int listenerPort; + + @Inject + Vertx vertx; + + @TestHTTPResource("/") + URI endpoint; + + @BeforeEach + void createSdkNetwork() { + ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.EU_WEST_1, endpoint); + cleanup.add(ec2::close); + elb = AwsTestClients.create(ElasticLoadBalancingV2Client.builder(), "test", Region.EU_WEST_1, endpoint); + cleanup.add(elb::close); + vpc = ec2.createVpc(r -> r.cidrBlock("10.83.0.0/16")).vpc().vpcId(); + cleanup.add(() -> ec2.deleteVpc(r -> r.vpcId(vpc))); + subnets = new ArrayList<>(); + for (int index = 0; index < 2; index++) { + String cidr = "10.83." + index + ".0/24"; + String zone = "eu-west-1" + (char) ('a' + index); + String subnet = ec2.createSubnet(r -> r.vpcId(vpc).cidrBlock(cidr) + .availabilityZone(zone)).subnet().subnetId(); + subnets.add(subnet); + cleanup.add(() -> ec2.deleteSubnet(r -> r.subnetId(subnet))); + } + } + + @AfterEach + void removeOnlyThisTestsResources() { + assertAll(cleanup.reversed()); + } + + @Test + void httpsTargetUsesTlsEvenWhenItsHealthCheckUsesHttp() throws Exception { + HttpServer application = backend(true); + HttpServer health = backend(false); + createTarget("HTTPS", application.actualPort(), "HTTP", health.actualPort(), "200"); + awaitHealth("healthy", null); + + given().baseUri("http://127.0.0.1").port(listenerPort).urlEncodingEnabled(false) + .header("Host", dns).header("Authorization", "native-client-signature") + .contentType("application/octet-stream").body("native request".getBytes(StandardCharsets.UTF_8)) + .post("/packages/prepare?version=3%2E0").then().statusCode(200).body(equalTo("native request")); + + assertTrue(encrypted.get()); + assertEquals("POST /packages/prepare?version=3%2E0 native-client-signature", received.get()); + } + + @Test + void httpTargetCanUseAnIndependentHttpsHealthEndpoint() throws Exception { + HttpServer application = backend(false); + HttpServer health = backend(true); + createTarget("HTTP", application.actualPort(), "HTTPS", health.actualPort(), "200"); + awaitHealth("healthy", null); + given().baseUri("http://127.0.0.1").port(listenerPort).header("Host", dns) + .body("plain target".getBytes(StandardCharsets.UTF_8)).post("/echo") + .then().statusCode(200).body(equalTo("plain target")); + assertFalse(encrypted.get()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void healthProbeConnectsDirectlyDespiteJvmProxyConfiguration(boolean tls) throws Exception { + HttpServer health = backend(tls); + AtomicInteger proxied = new AtomicInteger(); + HttpServer proxy = vertx.createHttpServer().requestHandler(request -> { + proxied.incrementAndGet(); + request.response().setStatusCode(503).end(); + }).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); + cleanup.add(() -> proxy.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS)); + ProxySelector previous = ProxySelector.getDefault(); + ProxySelector.setDefault(new ProxySelector() { + @Override + public List select(URI uri) { + if (uri.getPort() == health.actualPort()) { + return List.of(new Proxy(Proxy.Type.HTTP, + new InetSocketAddress("127.0.0.1", proxy.actualPort()))); + } + return previous == null ? List.of(Proxy.NO_PROXY) : previous.select(uri); + } + + @Override + public void connectFailed(URI uri, SocketAddress address, IOException failure) { + fail("Health checks must connect directly to the target: " + uri, failure); + } + }); + try { + createTarget("HTTP", health.actualPort(), tls ? "HTTPS" : "HTTP", health.actualPort(), "200"); + await().atMost(Duration.ofSeconds(5)).until(() -> proxied.get() > 0 + || "healthy".equals(elb.describeTargetHealth(r -> r.targetGroupArn(groupArn)) + .targetHealthDescriptions().getFirst().targetHealth().stateAsString())); + assertEquals(0, proxied.get(), "The JVM proxy must not receive target health probes"); + awaitHealth("healthy", null); + } finally { + ProxySelector.setDefault(previous); + } + } + + @Test + void httpsHealthRejectsAReachablePlaintextServer() throws Exception { + HttpServer plain = backend(false); + createTarget("HTTP", plain.actualPort(), "HTTPS", plain.actualPort(), "200"); + awaitHealth("unhealthy", "Target.FailedHealthChecks"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void httpsTargetNeverFallsBackToPlaintext(boolean websocket) throws Exception { + HttpServer plain = backend(false); + createTarget("HTTPS", plain.actualPort(), "HTTP", plain.actualPort(), "200"); + awaitHealth("healthy", null); + + assertForwardingFailure(websocket, 502); + assertNull(received.get(), "The plaintext application must not receive the request"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void unansweredBackendTlsHandshakeReturnsGatewayTimeout(boolean websocket) throws Exception { + CompletableFuture disconnected = new CompletableFuture<>(); + AtomicBoolean clientHello = new AtomicBoolean(); + NetServer stalled = vertx.createNetServer().connectHandler(socket -> { + long accepted = System.nanoTime(); + socket.handler(buffer -> { + if (buffer.length() > 0 && buffer.getUnsignedByte(0) == 22) { + clientHello.set(true); + } + }); + socket.closeHandler(ignored -> + disconnected.complete(Duration.ofNanos(System.nanoTime() - accepted))); + }).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); + cleanup.add(() -> stalled.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS)); + HttpServer health = backend(false); + createTarget("HTTPS", stalled.actualPort(), "HTTP", health.actualPort(), "200"); + awaitHealth("healthy", null); + + assertForwardingFailure(websocket, 504); + assertTrue(clientHello.get(), "The backend must receive the real TLS ClientHello"); + Duration elapsed = disconnected.get(5, TimeUnit.SECONDS); + assertTrue(elapsed.compareTo(Duration.ofSeconds(9)) >= 0 + && elapsed.compareTo(Duration.ofSeconds(15)) < 0, + "An ALB backend TLS handshake has a ten-second deadline: " + elapsed); + assertNull(received.get(), "The native wait must end before an application request is sent"); + } + + @Test + void httpsHealthPreservesCustomMatchersAndRecovers() throws Exception { + HttpServer tls = backend(true); + healthStatus.set(302); + createTarget("HTTPS", tls.actualPort(), "HTTPS", tls.actualPort(), "302"); + awaitHealth("healthy", null); + + healthStatus.set(503); + awaitHealth("unhealthy", "Target.ResponseCodeMismatch"); + + elb.modifyTargetGroup(r -> r.targetGroupArn(groupArn) + .matcher(Matcher.builder().httpCode("200-299").build())); + healthStatus.set(204); + awaitHealth("healthy", null); + } + + @Test + void changingHealthProtocolAndPortReplacesTheProbeSettings() throws Exception { + HttpServer plain = backend(false); + HttpServer tls = backend(true); + createTarget("HTTP", plain.actualPort(), "HTTP", plain.actualPort(), "200"); + awaitHealth("healthy", null); + + elb.modifyTargetGroup(r -> r.targetGroupArn(groupArn).healthCheckProtocol("HTTPS")); + awaitHealth("unhealthy", "Target.FailedHealthChecks"); + + elb.modifyTargetGroup(r -> r.targetGroupArn(groupArn).healthCheckPort(String.valueOf(tls.actualPort()))); + awaitHealth("healthy", null); + } + + @Test + void anUnansweredTlsHandshakeExpiresAtTheConfiguredHealthTimeout() throws Exception { + CompletableFuture handshakeWait = new CompletableFuture<>(); + AtomicBoolean clientHelloReceived = new AtomicBoolean(); + NetServer stalled = vertx.createNetServer().connectHandler(socket -> { + long accepted = System.nanoTime(); + socket.handler(buffer -> { + if (buffer.length() > 0 && buffer.getUnsignedByte(0) == 22) { + clientHelloReceived.set(true); + } + }); + socket.closeHandler(ignored -> handshakeWait.complete(Duration.ofNanos(System.nanoTime() - accepted))); + }).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); + cleanup.add(() -> stalled.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS)); + HttpServer application = backend(false); + createTarget("HTTP", application.actualPort(), "HTTPS", stalled.actualPort(), "200"); + + awaitHealth("unhealthy", "Target.Timeout"); + assertTrue(clientHelloReceived.get(), "The probe must start a real TLS handshake"); + Duration elapsed = handshakeWait.get(5, TimeUnit.SECONDS); + assertTrue(elapsed.compareTo(Duration.ofMillis(1500)) >= 0 + && elapsed.compareTo(Duration.ofSeconds(4)) < 0, + "The configured two-second timeout must bound the handshake: " + elapsed); + } + + @Test + void websocketUpgradeUsesTheTargetsHttpsProtocol() throws Exception { + HttpServer application = backend(true); + HttpServer health = backend(false); + createTarget("HTTPS", application.actualPort(), "HTTP", health.actualPort(), "200"); + awaitHealth("healthy", null); + HttpClient client = vertx.createHttpClient(); + cleanup.add(() -> client.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS)); + WebSocket socket = client.webSocket(new WebSocketConnectOptions().setHost("127.0.0.1") + .setPort(listenerPort).setURI("/socket.io/?transport=websocket").addHeader("Host", dns)) + .toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); + cleanup.add(() -> socket.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS)); + CompletableFuture reply = new CompletableFuture<>(); + socket.textMessageHandler(reply::complete); + socket.writeTextMessage("native-frame").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); + assertEquals("echo:native-frame", reply.get(5, TimeUnit.SECONDS)); + assertTrue(encrypted.get(), "The WebSocket handshake must reach the backend over TLS"); + } + + @ParameterizedTest + @ValueSource(strings = {"HTTP", "HTTPS"}) + void slowResponseBytesCannotKeepAnUnhealthyTargetHealthy(String protocol) throws Exception { + HttpServer healthy = backend("HTTPS".equals(protocol)); + createTarget(protocol, healthy.actualPort(), protocol, healthy.actualPort(), "200"); + awaitHealth("healthy", null); + NetServer slow = slowPeer("HTTPS".equals(protocol), false); + elb.modifyTargetGroup(r -> r.targetGroupArn(groupArn).healthCheckPort(String.valueOf(slow.actualPort()))); + + awaitHealth("unhealthy", "Target.Timeout"); + } + + @Test + void slowTlsRecordsCannotKeepAnUnhealthyTargetHealthy() throws Exception { + HttpServer healthy = backend(false); + createTarget("HTTP", healthy.actualPort(), "HTTP", healthy.actualPort(), "200"); + awaitHealth("healthy", null); + NetServer slow = slowPeer(false, true); + elb.modifyTargetGroup(r -> r.targetGroupArn(groupArn).healthCheckProtocol("HTTPS") + .healthCheckPort(String.valueOf(slow.actualPort()))); + + awaitHealth("unhealthy", "Target.Timeout"); + } + + private NetServer slowPeer(boolean tls, boolean handshake) throws Exception { + NetServerOptions options = new NetServerOptions(); + if (tls) { + CertificateGenerator.GeneratedCertificate certificate = new CertificateGenerator() + .generateSelfSignedCertificate("backend.example.test", List.of(), KeyAlgorithm.RSA_2048); + options.setSsl(true).setPemKeyCertOptions(new PemKeyCertOptions() + .setCertValue(Buffer.buffer(certificate.certificatePem())) + .setKeyValue(Buffer.buffer(certificate.privateKeyPem()))); + } + List connections = new CopyOnWriteArrayList<>(); + List timers = new CopyOnWriteArrayList<>(); + List closed = new CopyOnWriteArrayList<>(); + NetServer server = vertx.createNetServer(options).connectHandler(socket -> { + connections.add(socket); + long accepted = System.nanoTime(); + socket.handler(ignored -> {}); + socket.write(handshake ? Buffer.buffer(new byte[]{22, 3, 3, 0, 100}) + : Buffer.buffer("HTTP/1.1 200 OK\r\nX-Incomplete: ")); + long timer = vertx.setPeriodic(250, ignored -> socket.write(Buffer.buffer(new byte[]{0}))); + timers.add(timer); + socket.closeHandler(ignored -> { + vertx.cancelTimer(timer); + closed.add(Duration.ofNanos(System.nanoTime() - accepted)); + }); + }).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); + cleanup.add(() -> { + timers.forEach(vertx::cancelTimer); + for (NetSocket socket : connections) { + socket.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); + } + server.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); + }); + cleanup.add(() -> { + await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> assertTrue(closed.size() >= 2, + "Both timed-out probe connections must be closed without fixture cleanup")); + assertTrue(closed.stream().allMatch(wait -> wait.compareTo(Duration.ofSeconds(4)) < 0), + "Peer connections exceeded the configured health deadline: " + closed); + }); + return server; + } + + private void assertForwardingFailure(boolean websocket, int status) throws Exception { + if (!websocket) { + given().baseUri("http://127.0.0.1").port(listenerPort).header("Host", dns) + .body("must remain encrypted").post("/should-not-arrive") + .then().statusCode(status); + return; + } + HttpClient client = vertx.createHttpClient(); + cleanup.add(() -> client.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS)); + ExecutionException failure = assertThrows(ExecutionException.class, () -> + client.webSocket(new WebSocketConnectOptions().setHost("127.0.0.1") + .setPort(listenerPort).setURI("/socket.io/").addHeader("Host", dns)) + .toCompletionStage().toCompletableFuture().get(15, TimeUnit.SECONDS)); + assertEquals(status, assertInstanceOf(UpgradeRejectedException.class, failure.getCause()).getStatus()); + } + + private HttpServer backend(boolean tls) throws Exception { + HttpServerOptions options = new HttpServerOptions(); + if (tls) { + CertificateGenerator.GeneratedCertificate certificate = new CertificateGenerator() + .generateSelfSignedCertificate("backend.example.test", List.of(), KeyAlgorithm.RSA_2048); + options.setSsl(true).setPemKeyCertOptions(new PemKeyCertOptions() + .setCertValue(Buffer.buffer(certificate.certificatePem())) + .setKeyValue(Buffer.buffer(certificate.privateKeyPem()))); + } + HttpServer backend = vertx.createHttpServer(options).requestHandler(request -> { + if ("/health".equals(request.path())) { + request.response().setStatusCode(healthStatus.get()).putHeader("Location", "/healthy").end(); + return; + } + encrypted.set(request.isSSL()); + received.set(request.method() + " " + request.uri() + " " + request.getHeader("Authorization")); + if ("websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) { + request.toWebSocket().onSuccess(socket -> socket.textMessageHandler( + message -> socket.writeTextMessage("echo:" + message))); + } else { + request.body().onSuccess(body -> request.response().end(body)); + } + }).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); + cleanup.add(() -> backend.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS)); + return backend; + } + + private void createTarget(String protocol, int port, String healthProtocol, int healthPort, String matcher) + throws Exception { + LoadBalancer loadBalancer = elb.createLoadBalancer(r -> r.name(name).type("application") + .subnets(subnets)).loadBalancers().getFirst(); + String arn = loadBalancer.loadBalancerArn(); + dns = loadBalancer.dnsName(); + cleanup.add(() -> elb.deleteLoadBalancer(r -> r.loadBalancerArn(arn))); + groupArn = elb.createTargetGroup(r -> r.name(name).protocol(protocol).port(port).vpcId(vpc) + .targetType("ip").healthCheckProtocol(healthProtocol).healthCheckPort(String.valueOf(healthPort)) + .healthCheckPath("/health").healthCheckIntervalSeconds(5).healthCheckTimeoutSeconds(2) + .healthyThresholdCount(2).unhealthyThresholdCount(2) + .matcher(Matcher.builder().httpCode(matcher).build())) + .targetGroups().getFirst().targetGroupArn(); + cleanup.add(() -> elb.deleteTargetGroup(r -> r.targetGroupArn(groupArn))); + try (ServerSocket reservation = new ServerSocket(0)) { + listenerPort = reservation.getLocalPort(); + } + String listener = elb.createListener(r -> r.loadBalancerArn(arn).protocol("HTTP").port(listenerPort) + .defaultActions(Action.builder().type("forward").targetGroupArn(groupArn).build())) + .listeners().getFirst().listenerArn(); + cleanup.add(() -> elb.deleteListener(r -> r.listenerArn(listener))); + elb.registerTargets(r -> r.targetGroupArn(groupArn) + .targets(TargetDescription.builder().id("127.0.0.1").port(port).build())); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress("127.0.0.1", listenerPort), 1000); + } + }); + } + + private void awaitHealth(String state, String reason) { + await().atMost(Duration.ofSeconds(20)).untilAsserted(() -> { + List targets = elb.describeTargetHealth(r -> r.targetGroupArn(groupArn)) + .targetHealthDescriptions(); + assertEquals(1, targets.size()); + assertEquals(state, targets.getFirst().targetHealth().stateAsString()); + assertEquals(reason, targets.getFirst().targetHealth().reasonAsString()); + }); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthCheckerTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthCheckerTest.java index 40cfb4b38a..79be022310 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthCheckerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthCheckerTest.java @@ -2,18 +2,24 @@ package io.github.hectorvent.floci.services.elbv2; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.Instance; import io.github.hectorvent.floci.services.elbv2.model.TargetDescription; import io.github.hectorvent.floci.services.elbv2.model.TargetGroup; import io.vertx.core.Future; import io.vertx.core.Handler; +import io.vertx.core.Promise; import io.vertx.core.Vertx; +import io.vertx.core.VertxOptions; +import io.vertx.core.WorkerExecutor; import io.vertx.core.http.HttpServer; +import io.vertx.core.http.HttpServerResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import java.time.Duration; +import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; @@ -22,10 +28,12 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -41,6 +49,48 @@ class ElbV2HealthCheckerTest { vertx.close().toCompletionStage().toCompletableFuture().join(); } + @Test + void slowProbeDoesNotOccupyTheSharedVertxWorker() throws Exception { + Vertx isolated = Vertx.vertx(new VertxOptions().setWorkerPoolSize(1)); + HttpServer server = null; + ElbV2HealthChecker checker = null; + CompletableFuture response = new CompletableFuture<>(); + try { + server = isolated.createHttpServer().requestHandler(request -> response.complete(request.response())) + .listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().elbv2().mock()).thenReturn(false); + checker = new ElbV2HealthChecker(isolated, config, mock(Ec2Service.class)); + TargetGroup group = targetGroup(server.actualPort(), "200", 1, 1); + group.setHealthCheckTimeoutSeconds(10); + TargetDescription target = target("127.0.0.1", server.actualPort()); + checker.addTargets(group.getTargetGroupArn(), List.of(target), group); + HttpServerResponse pendingResponse = response.get(2, TimeUnit.SECONDS); + + assertEquals("unrelated", assertDoesNotThrow(() -> isolated.executeBlocking(() -> "unrelated", false) + .toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS)), + "A probe awaiting its response must not occupy the shared worker"); + pendingResponse.end().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS); + ElbV2HealthChecker observed = checker; + await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> assertEquals("healthy", + observed.getState(group.getTargetGroupArn(), target.getId(), target.getPort()))); + } finally { + try { + if (checker != null) { + checker.destroy(); + } + if (response.isDone() && !response.join().ended()) { + response.join().end(); + } + if (server != null) { + server.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS); + } + } finally { + isolated.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); + } + } + } + @Test void successfulProbeTransitionsTargetToHealthy() throws Exception { HttpServer server = startServer(200); @@ -107,6 +157,100 @@ class ElbV2HealthCheckerTest { } } + @Test + void timedOutLookupKeepsOneProbeUntilTheLookupActuallyCompletes() throws Exception { + HttpServer server = startServer(200); + CompletableFuture entered = new CompletableFuture<>(); + CompletableFuture release = new CompletableFuture<>(); + AtomicInteger lookups = new AtomicInteger(); + Ec2Service ec2 = mock(Ec2Service.class); + Instance instance = new Instance(); + instance.setContainerBridgeIp("127.0.0.1"); + when(ec2.findInstanceById("000000000000", "i-blocked")).thenAnswer(ignored -> { + lookups.incrementAndGet(); + entered.complete(null); + // Like a native hostname lookup, join does not stop when its thread is interrupted. + release.join(); + return instance; + }); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + ElbV2HealthChecker checker = new ElbV2HealthChecker(vertx, config, ec2); + TargetGroup group = targetGroup(server.actualPort(), "200", 1, 1); + group.setTargetType("instance"); + TargetDescription blocked = target("i-blocked", server.actualPort()); + try { + checker.addTargets(group.getTargetGroupArn(), List.of(blocked), group); + entered.get(2, TimeUnit.SECONDS); + await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> assertEquals("Target.Timeout", + checker.getHealth(group.getTargetGroupArn(), blocked.getId(), blocked.getPort()).reason())); + checker.addTargets(group.getTargetGroupArn(), List.of(target("127.0.0.1", server.actualPort())), group); + await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> assertEquals("healthy", + checker.getState(group.getTargetGroupArn(), "127.0.0.1", server.actualPort()))); + await().during(Duration.ofMillis(250)).atMost(Duration.ofSeconds(1)).untilAsserted(() -> { + checker.probeAll(group.getTargetGroupArn(), group); + assertEquals(1, lookups.get(), "A timed-out lookup still owns its target's probe"); + }); + release.complete(null); + await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> { + checker.probeAll(group.getTargetGroupArn(), group); + assertEquals("healthy", + checker.getState(group.getTargetGroupArn(), blocked.getId(), blocked.getPort())); + }); + } finally { + release.complete(null); + close(server); + } + } + + @Test + void timedOutLookupsRetainTheirSharedProbeSlotsUntilTheyFinish() throws Exception { + HttpServer server = startServer(200); + CompletableFuture release = new CompletableFuture<>(); + AtomicInteger lookups = new AtomicInteger(); + Ec2Service ec2 = mock(Ec2Service.class); + Instance instance = new Instance(); + instance.setContainerBridgeIp("127.0.0.1"); + when(ec2.findInstanceById(eq("000000000000"), any())).thenAnswer(invocation -> { + if (invocation.getArgument(1).startsWith("i-held-")) { + lookups.incrementAndGet(); + release.join(); + } + return instance; + }); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + ElbV2HealthChecker checker = new ElbV2HealthChecker(vertx, config, ec2); + TargetGroup group = targetGroup(server.actualPort(), "200", 1, 1); + group.setTargetType("instance"); + List held = new ArrayList<>(); + for (int i = 0; i < 32; i++) { + held.add(target("i-held-" + i, server.actualPort())); + } + try { + checker.addTargets(group.getTargetGroupArn(), held, group); + await().atMost(Duration.ofSeconds(3)).until(() -> lookups.get() == 32); + await().atMost(Duration.ofSeconds(3)).until(() -> held.stream().allMatch(target -> + "Target.Timeout".equals(checker.getHealth( + group.getTargetGroupArn(), target.getId(), target.getPort()).reason()))); + checker.addTargets(group.getTargetGroupArn(), List.of(target("127.0.0.1", server.actualPort())), group); + await().during(Duration.ofMillis(250)).atMost(Duration.ofSeconds(1)).untilAsserted(() -> { + checker.probeAll(group.getTargetGroupArn(), group); + assertEquals(32, lookups.get()); + assertEquals("initial", checker.getState( + group.getTargetGroupArn(), "127.0.0.1", server.actualPort()), + "An expired caller deadline must not release a still-running worker's slot"); + }); + release.complete(null); + await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> { + checker.probeAll(group.getTargetGroupArn(), group); + assertEquals("healthy", + checker.getState(group.getTargetGroupArn(), "127.0.0.1", server.actualPort())); + }); + } finally { + release.complete(null); + close(server); + } + } + @Test void firstSuccessfulProbeMakesNewTargetHealthyRegardlessOfRecoveryThreshold() throws Exception { HttpServer server = startServer(200); @@ -231,7 +375,9 @@ class ElbV2HealthCheckerTest { @SuppressWarnings("unchecked") void initialAdmissionRespectsTargetGroupKind(String protocol, int requiredSuccesses) { Vertx immediate = mock(Vertx.class); - when(immediate.executeBlocking(any(Callable.class))).thenReturn(Future.succeededFuture(200)); + WorkerExecutor workers = mock(WorkerExecutor.class); + when(immediate.createSharedWorkerExecutor("floci-elbv2-health-probes", 32)).thenReturn(workers); + when(workers.executeBlocking(any(Callable.class), eq(false))).thenReturn(Future.succeededFuture(200)); doAnswer(invocation -> { Handler callback = invocation.getArgument(1); callback.handle(1L); @@ -265,7 +411,9 @@ class ElbV2HealthCheckerTest { @SuppressWarnings("unchecked") void periodicProbeRetainsIntervalAndNetworkAdmissionThreshold() { Vertx scheduled = mock(Vertx.class); - when(scheduled.executeBlocking(any(Callable.class))).thenReturn(Future.succeededFuture(200)); + WorkerExecutor workers = mock(WorkerExecutor.class); + when(scheduled.createSharedWorkerExecutor("floci-elbv2-health-probes", 32)).thenReturn(workers); + when(workers.executeBlocking(any(Callable.class), eq(false))).thenReturn(Future.succeededFuture(200)); AtomicReference> periodic = new AtomicReference<>(); doAnswer(invocation -> { Handler callback = invocation.getArgument(1); @@ -297,6 +445,43 @@ class ElbV2HealthCheckerTest { assertEquals("initial", checker.getState(group.getTargetGroupArn(), target.getId(), target.getPort())); } + @ParameterizedTest + @CsvSource({"false", "true"}) + @SuppressWarnings("unchecked") + void queuedProbeRetainsItsHealthProtocol(boolean changeProtocol) throws Exception { + HttpServer server = startServer(200); + try { + Vertx queued = mock(Vertx.class); + WorkerExecutor workers = mock(WorkerExecutor.class); + when(queued.createSharedWorkerExecutor("floci-elbv2-health-probes", 32)).thenReturn(workers); + AtomicReference> work = new AtomicReference<>(); + Promise result = Promise.promise(); + when(workers.executeBlocking(any(Callable.class), eq(false))).thenAnswer(invocation -> { + work.set(invocation.getArgument(0)); + return result.future(); + }); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().elbv2().mock()).thenReturn(false); + ElbV2HealthChecker checker = new ElbV2HealthChecker(queued, config, mock(Ec2Service.class)); + TargetGroup group = targetGroup(server.actualPort(), "200", 1, 1); + group.setHealthCheckProtocol("HTTP"); + TargetDescription target = target("127.0.0.1", server.actualPort()); + checker.addTargets(group.getTargetGroupArn(), List.of(target), group); + checker.probeAll(group.getTargetGroupArn(), group); + if (changeProtocol) { + group.setHealthCheckProtocol("HTTPS"); + } + + int status = assertDoesNotThrow(() -> work.get().call(), + "A queued HTTP probe must keep its captured protocol"); + result.complete(status); + assertEquals(200, status); + assertEquals("healthy", checker.getState(group.getTargetGroupArn(), target.getId(), target.getPort())); + } finally { + close(server); + } + } + private ElbV2HealthChecker healthChecker() { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(config.services().elbv2().mock()).thenReturn(false); diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthTimeoutIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthTimeoutIntegrationTest.java new file mode 100644 index 0000000000..28a84938ab --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthTimeoutIntegrationTest.java @@ -0,0 +1,66 @@ +package io.github.hectorvent.floci.services.elbv2; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.ElasticLoadBalancingV2Exception; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetGroup; + +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 +class ElbV2HealthTimeoutIntegrationTest { + + @ParameterizedTest + @ValueSource(ints = {-1, 0, 1, 121}) + void invalidTimeoutRejectsCreateAndPreservesUpdatedGroup(int timeout) { + try (ElasticLoadBalancingV2Client client = AwsTestClients.create( + ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) { + String name = "timeout-rejected-" + Math.abs(timeout); + ElasticLoadBalancingV2Exception createError = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.createTargetGroup(b -> b.name(name).targetType("ip").protocol("HTTP") + .port(80).healthCheckTimeoutSeconds(timeout))); + assertEquals("ValidationError", createError.awsErrorDetails().errorCode()); + assertTrue(client.describeTargetGroups().targetGroups().stream() + .noneMatch(group -> name.equals(group.targetGroupName()))); + String arn = client.createTargetGroup(b -> b.name(name).targetType("ip").protocol("HTTP") + .port(80).healthCheckPath("/original")).targetGroups().getFirst().targetGroupArn(); + try { + ElasticLoadBalancingV2Exception modifyError = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.modifyTargetGroup(b -> b.targetGroupArn(arn) + .healthCheckPath("/changed").healthCheckTimeoutSeconds(timeout))); + assertEquals("ValidationError", modifyError.awsErrorDetails().errorCode()); + TargetGroup group = client.describeTargetGroups(b -> b.targetGroupArns(arn)) + .targetGroups().getFirst(); + assertEquals("/original", group.healthCheckPath()); + assertEquals(5, group.healthCheckTimeoutSeconds()); + } finally { + client.deleteTargetGroup(b -> b.targetGroupArn(arn)); + } + } + } + + @Test + void upperBoundValidationPrecedesMissingGroupLookup() { + try (ElasticLoadBalancingV2Client client = AwsTestClients.create( + ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) { + String arn = "arn:aws:elasticloadbalancing:us-east-1:000000000000:" + + "targetgroup/timeout-missing/0000000000000000"; + ElasticLoadBalancingV2Exception error = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.modifyTargetGroup(b -> b.targetGroupArn(arn).healthCheckTimeoutSeconds(121))); + assertEquals("ValidationError", error.awsErrorDetails().errorCode()); + assertTrue(error.getMessage().contains("less than or equal to 120")); + for (int timeout : new int[]{2, 120}) { + ElasticLoadBalancingV2Exception missing = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.modifyTargetGroup(b -> b.targetGroupArn(arn).healthCheckTimeoutSeconds(timeout))); + assertEquals("TargetGroupNotFound", missing.awsErrorDetails().errorCode()); + } + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java index 7adec04182..4fe9d1a194 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java @@ -180,7 +180,7 @@ class ElbV2PreserveHostHeaderIntegrationTest { BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream(), StandardCharsets.ISO_8859_1)); - assertEquals(503, readStatus(input)); + assertEquals(502, readStatus(input)); output.write(("GET /healthy HTTP/1.1\r\n" + "Host: " + host + "\r\n" diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java index 8bb46f6409..9ab4ec41eb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java @@ -1225,6 +1225,52 @@ class ElbV2ServiceTest { return target; } + @ParameterizedTest + @ValueSource(ints = {-1, 0, 1, 121, Integer.MAX_VALUE}) + void createRejectsInvalidHealthTimeoutBeforePublishing(int timeout) { + AwsException error = assertThrows(AwsException.class, () -> service.createTargetGroup( + REGION, "invalid-timeout", "HTTP", "HTTP1", 80, "vpc-a", "ip", + "HTTP", "traffic-port", true, "/", 30, timeout, 5, 2, "200", "ipv4", Map.of())); + assertEquals("ValidationError", error.getErrorCode()); + assertTrue(error.getMessage().contains("healthCheckTimeoutSeconds")); + assertTrue(service.describeTargetGroups(REGION, null, null, null).isEmpty()); + verifyNoInteractions(healthChecker); + } + + @ParameterizedTest + @ValueSource(ints = {-1, 0, 1, 121, Integer.MAX_VALUE}) + void modifyRejectsInvalidHealthTimeoutBeforeAnyMutation(int timeout) { + String arn = createTargetGroup("timeout-state"); + AwsException error = assertThrows(AwsException.class, () -> service.modifyTargetGroup( + REGION, arn, "HTTPS", "443", false, "/changed", 60, timeout, 3, 4, "204")); + assertEquals("ValidationError", error.getErrorCode()); + TargetGroup group = service.describeTargetGroups(REGION, null, List.of(arn), null).getFirst(); + assertEquals("HTTP", group.getHealthCheckProtocol()); + assertEquals("traffic-port", group.getHealthCheckPort()); + assertTrue(group.getHealthCheckEnabled()); + assertEquals("/v1/ready", group.getHealthCheckPath()); + assertEquals(30, group.getHealthCheckIntervalSeconds()); + assertEquals(5, group.getHealthCheckTimeoutSeconds()); + assertEquals(5, group.getHealthyThresholdCount()); + assertEquals(2, group.getUnhealthyThresholdCount()); + assertEquals("200", group.getMatcher()); + } + + @ParameterizedTest + @ValueSource(ints = {2, 120}) + void healthTimeoutBoundariesAndOmittedUpdateRemainValid(int timeout) { + TargetGroup group = service.createTargetGroup(REGION, "timeout-boundary", "HTTP", "HTTP1", 80, + "vpc-a", "ip", "HTTP", "traffic-port", true, "/", 30, timeout, 5, 2, + "200", "ipv4", Map.of()); + assertEquals(timeout, group.getHealthCheckTimeoutSeconds()); + service.modifyTargetGroup(REGION, group.getTargetGroupArn(), null, null, null, + "/changed", null, null, null, null, null); + assertEquals(timeout, group.getHealthCheckTimeoutSeconds()); + service.modifyTargetGroup(REGION, group.getTargetGroupArn(), null, null, null, + null, null, timeout == 2 ? 120 : 2, null, null, null); + assertEquals(timeout == 2 ? 120 : 2, group.getHealthCheckTimeoutSeconds()); + } + private String createTargetGroup(String name) { return service.createTargetGroup( REGION, name, "HTTP", "HTTP1", 9999, "vpc-a", "instance",