diff --git a/docs/services/elb.md b/docs/services/elb.md index 49b08ac302..2f360115e3 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -147,7 +147,8 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on - Gateway listeners require `Protocol` and `Port` to be omitted on create and modify. Their control-plane response reports `GENEVE` without a port. CloudFormation preserves omitted gateway listener settings on create and update; other load balancer types retain their existing `HTTP` and port 80 defaults. - Instance targets are resolved through EC2 instance private addresses so local load balancer traffic can reach containers. An instance port that an ECS task on that container instance publishes resolves to the task's container instead, which is how an ECS service in `bridge` or `host` network mode serves an `instance` target group (see [ECS](ecs.md)). - Target health starts in `initial` state with reason `Elb.RegistrationInProgress` and is updated by Floci's health checker when monitoring is active. -- A newly registered Application Load Balancer target (HTTP/HTTPS target group or Lambda target) becomes healthy after its first successful check. Network and Gateway target groups retain `HealthyThresholdCount` for initial admission. The threshold applies to every group when recovering from `unhealthy`. +- A newly registered non-Lambda Application Load Balancer target (HTTP/HTTPS target group) becomes healthy after its first successful check. Network and Gateway target groups retain `HealthyThresholdCount` for initial admission. The threshold applies to every group when recovering from `unhealthy`. +- Lambda target groups default to disabled health checks. A registered Lambda target with checks disabled reports `unavailable` and `Target.HealthCheckDisabled`. Checks may be enabled or disabled for Lambda groups; enabled checks currently report `healthy` without invoking the function. Disabling checks for any non-Lambda target group fails with `InvalidConfigurationRequest` before changing its settings. The message names the target type, for example `Health check enabled must be true for target groups with target type 'ip'`. - Health checks probe the target group's `HealthCheckPort` when it is a port number, and each target's own port when it is `traffic-port` (the default). - `HealthCheckProtocol` defaults to `HTTP` for `HTTP` and `HTTPS` target groups and for target type `alb`, and to `TCP` for every other protocol, as for Network and Gateway Load Balancers. A health check uses `HTTP`, `HTTPS` or `TCP`. `TCP` is refused for `HTTP` and `HTTPS` target groups and for target type `alb`. `GENEVE`, `TLS`, `UDP`, `TCP_UDP`, `QUIC` and `TCP_QUIC` are refused for every target group. Each refusal is a `ValidationError` naming the protocols the target group takes, such as `Health check protocol 'TCP' must be one of 'HTTP, HTTPS'`, from `CreateTargetGroup` and `ModifyTargetGroup` alike, and changes nothing. - A `TCP` check has no `HealthCheckPath` or `Matcher`. Naming either for one, the default `TCP` check included, is refused with `InvalidConfigurationRequest` (`Health check paths are not supported for TCP health checks`, and the same for matchers). Moving a `TCP` check to `HTTP` or `HTTPS` takes both, or `ModifyTargetGroup` answers `ValidationError` `Path and return code are required for layer 7 health checks.`. Moving a check to `TCP` drops its path and matcher. diff --git a/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java b/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java index ef2aa99a4d..a3fd21c67f 100644 --- a/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java +++ b/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java @@ -590,6 +590,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc : defaultHealthCheckProtocol(groupProtocol, groupTargetType); validateLayer7Members(checkProtocol, healthCheckPath, matcher); boolean layer7Check = isHttpProtocol(checkProtocol); + validateHealthCheckEnabled(groupTargetType, healthCheckEnabled); Map regionTgs = targetGroups.computeIfAbsent(region, k -> new ConcurrentHashMap<>()); boolean duplicate = regionTgs.values().stream() .anyMatch(tg -> tg.getTargetGroupName().equals(name)); @@ -613,7 +614,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc tg.setRegion(region); // health check defaults - tg.setHealthCheckEnabled(healthCheckEnabled != null ? healthCheckEnabled : true); + tg.setHealthCheckEnabled(healthCheckEnabled != null ? healthCheckEnabled : !"lambda".equals(groupTargetType)); tg.setHealthCheckProtocol(checkProtocol); tg.setHealthCheckPort(healthCheckPort != null ? healthCheckPort : "traffic-port"); tg.setHealthCheckPath(layer7Check ? (healthCheckPath != null ? healthCheckPath : "/") : null); @@ -685,6 +686,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc validateHealthCheckTimeout(healthCheckTimeout); TargetGroup tg = requireTargetGroup(region, arn); validateHealthCheckPort(healthCheckPort); + validateHealthCheckEnabled(tg.getTargetType(), healthCheckEnabled); validateHealthCheckProtocol(healthCheckProtocol, tg.getProtocol(), tg.getTargetType()); String checkProtocol = healthCheckProtocol != null ? healthCheckProtocol : tg.getHealthCheckProtocol(); validateLayer7Members(checkProtocol, healthCheckPath, matcher); @@ -778,6 +780,13 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc return "HTTP".equals(protocol) || "HTTPS".equals(protocol); } + private static void validateHealthCheckEnabled(String targetType, Boolean enabled) { + if (Boolean.FALSE.equals(enabled) && !"lambda".equals(targetType)) { + throw new AwsException("InvalidConfigurationRequest", + "Health check enabled must be true for target groups with target type '" + targetType + "'", 400); + } + } + 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"; @@ -1330,7 +1339,13 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc th.setTarget(t); if (isLambdaTg) { th.setHealthCheckPort("N/A"); - th.setState("healthy"); + if (Boolean.FALSE.equals(tg.getHealthCheckEnabled())) { + th.setState("unavailable"); + th.setReason("Target.HealthCheckDisabled"); + th.setDescription("Health checks are disabled for the target group"); + } else { + th.setState("healthy"); + } return th; } int port = ElbV2HealthChecker.effectivePort(t, tg); diff --git a/src/test/java/io/floci/aws/services/cloudfront/CloudFrontWebSocketIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudfront/CloudFrontWebSocketIntegrationTest.java index 704f67d1fe..0482da1984 100644 --- a/src/test/java/io/floci/aws/services/cloudfront/CloudFrontWebSocketIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudfront/CloudFrontWebSocketIntegrationTest.java @@ -40,6 +40,7 @@ import static io.floci.aws.testing.AlbFixtures.deleteLoadBalancer; import static io.floci.aws.testing.AlbFixtures.deleteTargetGroup; import static io.floci.aws.testing.AlbFixtures.exchange; import static io.floci.aws.testing.AlbFixtures.registerTarget; +import static io.floci.aws.testing.AlbFixtures.withHealthCheck; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.equalTo; @@ -86,7 +87,7 @@ class CloudFrontWebSocketIntegrationTest { @BeforeEach void startAlbOrigin() throws Exception { backend = vertx.createHttpServer() - .requestHandler(request -> { + .requestHandler(withHealthCheck(request -> { originCustomHeader.set(request.getHeader("X-Origin-Verify")); if (!"websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) { request.response().setStatusCode(400).end("not an upgrade"); @@ -105,7 +106,7 @@ class CloudFrontWebSocketIntegrationTest { request.toWebSocket().onSuccess(socket -> socket.textMessageHandler( text -> socket.writeTextMessage(query + ":" + text))); } - }) + })) .listen(0, "127.0.0.1") .toCompletionStage() .toCompletableFuture() diff --git a/src/test/java/io/floci/aws/services/ecs/EcsLoadBalancerRegistrarTest.java b/src/test/java/io/floci/aws/services/ecs/EcsLoadBalancerRegistrarTest.java index 0d5e661e80..222694b029 100644 --- a/src/test/java/io/floci/aws/services/ecs/EcsLoadBalancerRegistrarTest.java +++ b/src/test/java/io/floci/aws/services/ecs/EcsLoadBalancerRegistrarTest.java @@ -61,7 +61,7 @@ class EcsLoadBalancerRegistrarTest { private String createTargetGroup(String name, String targetType) { TargetGroup tg = elbV2Service.createTargetGroup(REGION, name, "HTTP", "HTTP1", 8080, "vpc-regtest", targetType, - null, null, false, null, null, null, null, null, null, null, Map.of()); + null, null, true, null, null, null, null, null, null, null, Map.of()); return tg.getTargetGroupArn(); } diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendConnectionTestSupport.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendConnectionTestSupport.java index ce60de553b..c859479ad9 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendConnectionTestSupport.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendConnectionTestSupport.java @@ -16,6 +16,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static io.floci.aws.testing.AlbFixtures.HEALTH_CHECK_PATH; import static io.floci.aws.testing.AlbFixtures.createListener; import static io.floci.aws.testing.AlbFixtures.createLoadBalancer; import static io.floci.aws.testing.AlbFixtures.createTargetGroup; @@ -23,6 +24,7 @@ import static io.floci.aws.testing.AlbFixtures.deleteListener; import static io.floci.aws.testing.AlbFixtures.deleteLoadBalancer; import static io.floci.aws.testing.AlbFixtures.deleteTargetGroup; import static io.floci.aws.testing.AlbFixtures.registerTarget; +import static io.floci.aws.testing.AlbFixtures.withHealthCheck; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertAll; @@ -40,7 +42,7 @@ abstract class ElbV2BackendConnectionTestSupport { private String listenerArn; void startBackend(Handler handler) throws Exception { - backend = vertx.createHttpServer().requestHandler(handler) + backend = vertx.createHttpServer().requestHandler(withHealthCheck(handler)) .listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); listenerPort = FreePorts.anyInterfacePort(); loadBalancerArn = createLoadBalancer("backend-connection-lb"); @@ -55,6 +57,22 @@ abstract class ElbV2BackendConnectionTestSupport { }); } + @Test + void healthProbesDoNotReachTheApplicationHandler() throws Exception { + AtomicInteger requests = new AtomicInteger(); + startBackend(request -> { + requests.incrementAndGet(); + request.response().end("application"); + }); + + given().baseUri("http://127.0.0.1").port(backend.actualPort()) + .get(HEALTH_CHECK_PATH).then().statusCode(200); + assertEquals(0, requests.get()); + assertEquals("application", given().baseUri("http://127.0.0.1").port(listenerPort) + .get("/application").asString()); + assertEquals(1, requests.get()); + } + @Test void returnsBadGatewayWhenTargetClosesOnItsFirstRequest() throws Exception { AtomicInteger requests = new AtomicInteger(); diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2DisabledHealthIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2DisabledHealthIntegrationTest.java new file mode 100644 index 0000000000..b39b18f791 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2DisabledHealthIntegrationTest.java @@ -0,0 +1,92 @@ +package io.floci.aws.services.elbv2; + +import io.floci.aws.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 software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetHealthDescription; + +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class ElbV2DisabledHealthIntegrationTest { + + @Test + void lambdaDefaultsAndDisableUpdateAreVisibleThroughSdk() { + try (ElasticLoadBalancingV2Client client = AwsTestClients.create( + ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) { + String name = "disabled-" + UUID.randomUUID().toString().substring(0, 8); + TargetGroup group = client.createTargetGroup(r -> r.name(name).targetType("lambda")) + .targetGroups().getFirst(); + String arn = group.targetGroupArn(); + try { + assertFalse(group.healthCheckEnabled()); + client.registerTargets(r -> r.targetGroupArn(arn).targets(t -> t + .id("arn:aws:lambda:us-east-1:000000000000:function:disabled-health"))); + assertDisabled(client, arn); + client.modifyTargetGroup(r -> r.targetGroupArn(arn).healthCheckEnabled(true)); + assertTrue(client.describeTargetGroups(r -> r.targetGroupArns(arn)) + .targetGroups().getFirst().healthCheckEnabled()); + client.modifyTargetGroup(r -> r.targetGroupArn(arn).healthCheckEnabled(false)); + assertDisabled(client, arn); + } finally { + client.deleteTargetGroup(r -> r.targetGroupArn(arn)); + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"instance", "ip", "alb"}) + void networkDisableRejectsBeforeOtherUpdateFieldsChange(String targetType) { + try (ElasticLoadBalancingV2Client client = AwsTestClients.create( + ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) { + String name = "network-" + UUID.randomUUID().toString().substring(0, 8); + ElasticLoadBalancingV2Exception createError = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.createTargetGroup(r -> r.name(name).targetType(targetType) + .protocol("HTTP").port(80).vpcId("vpc-health").healthCheckEnabled(false))); + assertDisabledRefusal(createError, targetType); + assertTrue(client.describeTargetGroups().targetGroups().stream() + .noneMatch(group -> name.equals(group.targetGroupName()))); + TargetGroup group = client.createTargetGroup(r -> r.name(name).targetType(targetType) + .protocol("HTTP").port(80).vpcId("vpc-health")).targetGroups().getFirst(); + String arn = group.targetGroupArn(); + try { + ElasticLoadBalancingV2Exception error = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.modifyTargetGroup(r -> r.targetGroupArn(arn).healthCheckEnabled(false) + .healthCheckPath("/changed").healthCheckIntervalSeconds(60))); + assertDisabledRefusal(error, targetType); + TargetGroup retained = client.describeTargetGroups(r -> r.targetGroupArns(arn)) + .targetGroups().getFirst(); + assertTrue(retained.healthCheckEnabled()); + assertEquals(group.healthCheckPath(), retained.healthCheckPath()); + assertEquals(group.healthCheckIntervalSeconds(), retained.healthCheckIntervalSeconds()); + } finally { + client.deleteTargetGroup(r -> r.targetGroupArn(arn)); + } + } + } + + private static void assertDisabledRefusal(ElasticLoadBalancingV2Exception error, String targetType) { + assertEquals("InvalidConfigurationRequest", error.awsErrorDetails().errorCode()); + assertEquals("Health check enabled must be true for target groups with target type '" + targetType + "'", + error.awsErrorDetails().errorMessage()); + assertEquals(400, error.statusCode()); + } + + private static void assertDisabled(ElasticLoadBalancingV2Client client, String arn) { + TargetHealthDescription health = client.describeTargetHealth(r -> r.targetGroupArn(arn)) + .targetHealthDescriptions().getFirst(); + assertEquals("unavailable", health.targetHealth().stateAsString()); + assertEquals("Target.HealthCheckDisabled", health.targetHealth().reasonAsString()); + } +} diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2ForwardedHeadersIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2ForwardedHeadersIntegrationTest.java index fb90436421..f26ca9d78d 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2ForwardedHeadersIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2ForwardedHeadersIntegrationTest.java @@ -40,6 +40,7 @@ import static io.floci.aws.testing.AlbFixtures.deleteListener; import static io.floci.aws.testing.AlbFixtures.deleteLoadBalancer; import static io.floci.aws.testing.AlbFixtures.deleteTargetGroup; import static io.floci.aws.testing.AlbFixtures.registerTarget; +import static io.floci.aws.testing.AlbFixtures.withHealthCheck; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.containsString; @@ -73,7 +74,7 @@ class ElbV2ForwardedHeadersIntegrationTest { @BeforeEach void startBackend() throws Exception { backend = vertx.createHttpServer() - .requestHandler(request -> { + .requestHandler(withHealthCheck(request -> { if ("websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) { handshake.complete(MultiMap.caseInsensitiveMultiMap().addAll(request.headers())); request.toWebSocket(); @@ -85,7 +86,7 @@ class ElbV2ForwardedHeadersIntegrationTest { .putHeader("X-Seen-Proto", String.valueOf(request.getHeader("X-Forwarded-Proto"))) .putHeader("X-Seen-Port", String.valueOf(request.getHeader("X-Forwarded-Port"))) .end("ok"); - }) + })) .listen(0, "127.0.0.1") .toCompletionStage() .toCompletableFuture() diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2OtherAccountDataPlaneIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2OtherAccountDataPlaneIntegrationTest.java index 241e683fca..4d4abf6e93 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2OtherAccountDataPlaneIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2OtherAccountDataPlaneIntegrationTest.java @@ -19,6 +19,7 @@ import static io.floci.aws.testing.AlbFixtures.deleteListener; import static io.floci.aws.testing.AlbFixtures.deleteLoadBalancer; import static io.floci.aws.testing.AlbFixtures.deleteTargetGroup; import static io.floci.aws.testing.AlbFixtures.registerTarget; +import static io.floci.aws.testing.AlbFixtures.withHealthCheck; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.equalTo; @@ -43,7 +44,7 @@ class ElbV2OtherAccountDataPlaneIntegrationTest { @Test void listenerForwardsAndIsRestoredForItsOwnAccount() throws Exception { HttpServer backend = vertx.createHttpServer() - .requestHandler(request -> request.response().end("other-account")) + .requestHandler(withHealthCheck(request -> request.response().end("other-account"))) .listen(0, "127.0.0.1") .toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS); int listenerPort = FreePorts.anyInterfacePort(); diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java index 903b5ee62c..6c969fd28f 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java @@ -38,6 +38,7 @@ import static io.floci.aws.testing.AlbFixtures.deleteLoadBalancer; import static io.floci.aws.testing.AlbFixtures.deleteTargetGroup; import static io.floci.aws.testing.AlbFixtures.loadBalancerDnsName; import static io.floci.aws.testing.AlbFixtures.registerTarget; +import static io.floci.aws.testing.AlbFixtures.withHealthCheck; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.equalTo; @@ -57,7 +58,7 @@ class ElbV2PreserveHostHeaderIntegrationTest { @Test void preservesRepeatedTargetResponseHeaders() throws Exception { - HttpServer backend = vertx.createHttpServer().requestHandler(request -> { + HttpServer backend = vertx.createHttpServer().requestHandler(withHealthCheck(request -> { request.response().headers() .add("Set-Cookie", "a=1; Path=/") .add("Set-Cookie", "b=2; Path=/") @@ -66,7 +67,7 @@ class ElbV2PreserveHostHeaderIntegrationTest { .add("X-Multi", "two") .add("Keep-Alive", "timeout=5"); request.response().end("ok"); - }).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS); + })).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS); String loadBalancerArn = null; String targetGroupArn = null; String listenerArn = null; @@ -97,7 +98,7 @@ class ElbV2PreserveHostHeaderIntegrationTest { HttpServer backend = vertx.createHttpServer(new HttpServerOptions() .setMaxHeaderSize(ElbV2DataPlane.MAX_REQUEST_HEADER_SIZE) .setMaxInitialLineLength(ElbV2DataPlane.MAX_REQUEST_LINE_LENGTH)) - .requestHandler(request -> { + .requestHandler(withHealthCheck(request -> { if ("/stream".equals(request.path())) { request.body().onSuccess(body -> { request.response() @@ -117,7 +118,7 @@ class ElbV2PreserveHostHeaderIntegrationTest { } else { request.response().end(request.getHeader("Host")); } - }) + })) .listen(0, "127.0.0.1") .toCompletionStage() .toCompletableFuture() @@ -150,7 +151,7 @@ class ElbV2PreserveHostHeaderIntegrationTest { @Test void drainsRequestWhenTargetConnectionFails() throws Exception { HttpServer backend = vertx.createHttpServer() - .requestHandler(request -> request.response().end("healthy")) + .requestHandler(withHealthCheck(request -> request.response().end("healthy"))) .listen(0, "127.0.0.1") .toCompletionStage() .toCompletableFuture() @@ -164,7 +165,6 @@ class ElbV2PreserveHostHeaderIntegrationTest { loadBalancerArn = createLoadBalancer("preserve-host-header-lb"); targetGroupArn = createTargetGroup("preserve-host-header-tg", "ip", backend.actualPort()); registerTarget(targetGroupArn, "127.0.0.1", failedPort); - registerTarget(targetGroupArn, "127.0.0.1", backend.actualPort()); listenerArn = createListener(loadBalancerArn, targetGroupArn, LISTENER_PORT); String host = loadBalancerDnsName(loadBalancerArn); @@ -182,6 +182,14 @@ class ElbV2PreserveHostHeaderIntegrationTest { new InputStreamReader(socket.getInputStream(), StandardCharsets.ISO_8859_1)); assertEquals(502, readStatus(input)); + given().formParam("Action", "DeregisterTargets") + .formParam("TargetGroupArn", targetGroupArn) + .formParam("Targets.member.1.Id", "127.0.0.1") + .formParam("Targets.member.1.Port", failedPort) + .header("Authorization", AUTH) + .post("/").then().statusCode(200); + registerTarget(targetGroupArn, "127.0.0.1", backend.actualPort()); + output.write(("GET /healthy HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n").getBytes(StandardCharsets.ISO_8859_1)); diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java index e190b47668..c658ef508c 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java @@ -1548,6 +1548,70 @@ class ElbV2ServiceTest { assertTrue(service.describeTargetHealth(REGION, arn, null).isEmpty()); } + @Test + void lambdaHealthChecksDefaultDisabledAndDescribeUnavailable() { + TargetGroup group = service.createTargetGroup(REGION, "lambda-disabled", null, null, null, + null, "lambda", null, null, null, null, null, null, null, null, null, null, Map.of()); + assertFalse(group.getHealthCheckEnabled()); + service.registerTargets(REGION, group.getTargetGroupArn(), List.of(target("function", null))); + TargetHealth health = service.describeTargetHealth(REGION, group.getTargetGroupArn(), null).getFirst(); + assertEquals("unavailable", health.getState()); + assertEquals("Target.HealthCheckDisabled", health.getReason()); + assertEquals("N/A", health.getHealthCheckPort()); + } + + @Test + void lambdaHealthChecksCanBeDisabledAfterExplicitEnablement() { + TargetGroup group = service.createTargetGroup(REGION, "lambda-toggle", null, null, null, + null, "lambda", null, null, true, null, null, null, null, null, null, null, Map.of()); + assertTrue(group.getHealthCheckEnabled()); + service.registerTargets(REGION, group.getTargetGroupArn(), List.of(target("function", null))); + service.modifyTargetGroup(REGION, group.getTargetGroupArn(), null, null, false, + null, null, null, null, null, null); + TargetHealth health = service.describeTargetHealth(REGION, group.getTargetGroupArn(), null).getFirst(); + assertEquals("unavailable", health.getState()); + assertEquals("Target.HealthCheckDisabled", health.getReason()); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {"instance", "ip", "alb"}) + void nonLambdaHealthChecksCannotBeDisabledAtCreate(String targetType) { + AwsException error = assertThrows(AwsException.class, () -> service.createTargetGroup( + REGION, "network-disabled", "HTTP", "HTTP1", 80, "vpc-a", targetType, + "HTTP", "traffic-port", false, "/", 30, 5, 5, 2, "200", "ipv4", Map.of())); + assertEquals("InvalidConfigurationRequest", error.getErrorCode()); + assertEquals("Health check enabled must be true for target groups with target type '" + + (targetType == null ? "instance" : targetType) + "'", error.getMessage()); + assertEquals(400, error.getHttpStatus()); + assertTrue(service.describeTargetGroups(REGION, null, null, null).isEmpty()); + verifyNoInteractions(healthChecker); + } + + @ParameterizedTest + @ValueSource(strings = {"instance", "ip", "alb"}) + void nonLambdaDisableRejectsAllChangesBeforeMutation(String targetType) { + TargetGroup group = service.createTargetGroup(REGION, "network-enabled", "HTTP", "HTTP1", 80, + "vpc-a", targetType, "HTTP", "traffic-port", null, "/", 30, 5, 5, 2, + "200", "ipv4", Map.of()); + assertTrue(group.getHealthCheckEnabled()); + clearInvocations(healthChecker); + AwsException error = assertThrows(AwsException.class, () -> service.modifyTargetGroup( + REGION, group.getTargetGroupArn(), "HTTPS", "443", false, "/changed", 60, 10, 3, 4, "204")); + assertEquals("InvalidConfigurationRequest", error.getErrorCode()); + assertEquals("Health check enabled must be true for target groups with target type '" + + (targetType == null ? "instance" : targetType) + "'", error.getMessage()); + assertEquals(400, error.getHttpStatus()); + assertTrue(group.getHealthCheckEnabled()); + assertEquals("HTTP", group.getHealthCheckProtocol()); + assertEquals("traffic-port", group.getHealthCheckPort()); + assertEquals("/", group.getHealthCheckPath()); + assertEquals(30, group.getHealthCheckIntervalSeconds()); + assertEquals(5, group.getHealthCheckTimeoutSeconds()); + assertEquals("200", group.getMatcher()); + verifyNoInteractions(healthChecker); + } + private void targetOperation(String operation, String arn, List targets) { Runnable request = switch (operation) { case "register" -> () -> service.registerTargets(REGION, arn, targets); diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2TraceHeaderIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2TraceHeaderIntegrationTest.java index 5860409dc7..3371a65842 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2TraceHeaderIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2TraceHeaderIntegrationTest.java @@ -25,6 +25,7 @@ import static io.floci.aws.testing.AlbFixtures.deleteListener; import static io.floci.aws.testing.AlbFixtures.deleteLoadBalancer; import static io.floci.aws.testing.AlbFixtures.deleteTargetGroup; import static io.floci.aws.testing.AlbFixtures.registerTarget; +import static io.floci.aws.testing.AlbFixtures.withHealthCheck; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; @@ -51,7 +52,7 @@ class ElbV2TraceHeaderIntegrationTest { @BeforeEach void startBackend() throws Exception { backend = vertx.createHttpServer() - .requestHandler(request -> { + .requestHandler(withHealthCheck(request -> { String trace = String.valueOf(request.getHeader(ElbV2TraceHeader.NAME)); if ("websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) { handshake.complete(trace); @@ -59,7 +60,7 @@ class ElbV2TraceHeaderIntegrationTest { return; } request.response().end(trace); - }) + })) .listen(0, "127.0.0.1") .toCompletionStage() .toCompletableFuture() diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2WebSocketIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2WebSocketIntegrationTest.java index 30e901b2ad..d8272493c6 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2WebSocketIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2WebSocketIntegrationTest.java @@ -34,6 +34,7 @@ import static io.floci.aws.testing.AlbFixtures.deleteTargetGroup; import static io.floci.aws.testing.AlbFixtures.exchange; import static io.floci.aws.testing.AlbFixtures.forwardDefaultActionTo; import static io.floci.aws.testing.AlbFixtures.registerTarget; +import static io.floci.aws.testing.AlbFixtures.withHealthCheck; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.anyOf; @@ -69,7 +70,7 @@ class ElbV2WebSocketIntegrationTest { @BeforeEach void startBackend() throws Exception { backend = vertx.createHttpServer() - .requestHandler(request -> { + .requestHandler(withHealthCheck(request -> { if (!"websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) { request.response().setStatusCode(400).end("not an upgrade"); } else if (request.path().startsWith("/broken/")) { @@ -89,7 +90,7 @@ class ElbV2WebSocketIntegrationTest { request.toWebSocket().onSuccess(socket -> socket.textMessageHandler( text -> socket.writeTextMessage(query + ":" + text))); } - }) + })) .listen(0, "127.0.0.1") .toCompletionStage() .toCompletableFuture() diff --git a/src/test/java/io/floci/aws/testing/AlbFixtures.java b/src/test/java/io/floci/aws/testing/AlbFixtures.java index cedb737578..7fffa3a96c 100644 --- a/src/test/java/io/floci/aws/testing/AlbFixtures.java +++ b/src/test/java/io/floci/aws/testing/AlbFixtures.java @@ -1,6 +1,8 @@ package io.floci.aws.testing; import io.floci.aws.services.ec2.Ec2Service; +import io.vertx.core.Handler; +import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.WebSocket; import java.util.List; @@ -17,6 +19,8 @@ import static org.hamcrest.Matchers.equalTo; */ public final class AlbFixtures { + public static final String HEALTH_CHECK_PATH = "/__alb_fixture_health"; + private static final String DEFAULT_ACCOUNT = "000000000000"; private AlbFixtures() { @@ -55,7 +59,7 @@ public final class AlbFixtures { .path("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.DNSName"); } - /** An HTTP target group with health checks off, so a target serves as soon as it is registered. */ + /** An HTTP target group probing the dedicated health path on the test backend. */ public static String createTargetGroup(String name, String targetType, int targetPort) { return createTargetGroup(DEFAULT_ACCOUNT, name, targetType, targetPort); } @@ -67,7 +71,7 @@ public final class AlbFixtures { .formParam("Protocol", "HTTP") .formParam("Port", targetPort) .formParam("TargetType", targetType) - .formParam("HealthCheckEnabled", "false") + .formParam("HealthCheckPath", HEALTH_CHECK_PATH) .header("Authorization", auth(account)) .when() .post("/") @@ -77,6 +81,17 @@ public final class AlbFixtures { .path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn"); } + /** Answers health probes without passing them to the application's request assertions. */ + public static Handler withHealthCheck(Handler application) { + return request -> { + if (HEALTH_CHECK_PATH.equals(request.path())) { + request.response().end(); + } else { + application.handle(request); + } + }; + } + public static void registerTarget(String targetGroupArn, String targetId, int targetPort) { registerTarget(DEFAULT_ACCOUNT, targetGroupArn, targetId, targetPort); }