diff --git a/docs/services/elb.md b/docs/services/elb.md index e629d31e8d..ea5051190a 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -99,6 +99,20 @@ Floci supports Application Load Balancers (ALB) and Network Load Balancers (NLB) - `DescribeSSLPolicies` returns a pre-seeded list of standard AWS SSL policies (`ELBSecurityPolicy-*`). - `DescribeAccountLimits` returns standard default limits (e.g., 50 load balancers per region, 100 target groups, etc.). - Responses from HTTP targets preserve repeated header values, including multiple `Set-Cookie` headers. This also applies when a target rejects a WebSocket upgrade. +- Duration-based ALB target stickiness is applied for instance and IP targets when + `stickiness.enabled=true` and `stickiness.type=lb_cookie` (the default type). Requests + without a usable cookie select a target normally; subsequent requests carrying the + cookie return to that target while it remains eligible. Deregistered or unhealthy + targets are replaced using the existing health-aware selection, including fail-open + behavior when every target is unhealthy. +- Sticky responses include opaque, authenticated `AWSALB` and `AWSALBCORS` cookies, without + replacing application cookies. `AWSALBCORS` takes precedence and has + `SameSite=None; Secure`. Both cookies use `Expires` seven days in the future; the + configured `stickiness.lb_cookie.duration_seconds` (default 86400, range 1 to 604800) + separately limits the age of a target binding. Each response renews the binding. + Restarting Floci invalidates existing bindings. Application-cookie stickiness, + weighted target-group affinity, and NLB stickiness are not implemented. Cookie + stickiness is not applied with target-group cross-zone balancing disabled or `weighted_random` routing. - `routing.http.preserve_host_header.enabled` (default `false`) controls whether the original client Host header is forwarded to targets unchanged, or replaced with the target's `host:port`. - `RegisterTargets` rejects link-local and cloud instance-metadata addresses (`169.254.0.0/16`, `fe80::/10`, `fd00:ec2::254`) with `InvalidTarget`, and the load balancer and its health checks refuse to connect to them. Loopback and private addresses stay reachable so a load balancer can front a neighbouring container. 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 a3f3481e59..5dab19bc89 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 @@ -96,6 +96,7 @@ public class ElbV2DataPlane { private final Map>> ruleChains = new ConcurrentHashMap<>(); private final Map rrCounters = new ConcurrentHashMap<>(); private final Map listenerRegions = new ConcurrentHashMap<>(); + private final ElbV2StickyCookie stickyCookie = new ElbV2StickyCookie(); private HttpClient proxyClient; @@ -464,18 +465,25 @@ public class ElbV2DataPlane { req.response().setStatusCode(503).end("No targets available"); return; } - AtomicInteger counter = rrCounters.computeIfAbsent(tgArn, k -> new AtomicInteger(0)); - int idx = Math.abs(counter.getAndIncrement() % candidates.size()); - TargetDescription target = candidates.get(idx); + ListenerBinding binding = listenerBindings.get(listenerArn); + long duration = ElbV2StickyCookie.durationSeconds(tg); + String scope = binding != null ? binding.loadBalancerArn() + "\n" + tgArn : ""; + TargetDescription target = stickyCookie.target(req.headers().getAll("Cookie"), scope, tg, candidates, duration); + if (target == null) { + AtomicInteger counter = rrCounters.computeIfAbsent(tgArn, k -> new AtomicInteger(0)); + int idx = Math.abs(counter.getAndIncrement() % candidates.size()); + target = candidates.get(idx); + } + 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 preserveHostHeader = Boolean.parseBoolean( loadBalancerAttribute(listenerArn, region, PRESERVE_HOST_HEADER_ATTRIBUTE)); if (isWebSocketUpgrade(req)) { - proxyUpgrade(req, host, targetPort, preserveHostHeader, idleTimeoutMillis(listenerArn, region)); + proxyUpgrade(req, host, targetPort, preserveHostHeader, idleTimeoutMillis(listenerArn, region), cookies); return; } - proxyRequest(req, host, targetPort, preserveHostHeader); + proxyRequest(req, host, targetPort, preserveHostHeader, cookies); } private String loadBalancerAttribute(String listenerArn, String region, String key) { @@ -695,18 +703,18 @@ public class ElbV2DataPlane { } private void proxyRequest(io.vertx.core.http.HttpServerRequest req, String host, int port, - boolean preserveHostHeader) { + boolean preserveHostHeader, List cookies) { req.pause(); if (ElbV2TargetResolver.isIpLiteral(host)) { try { - proxyRequestTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port, preserveHostHeader); + proxyRequestTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port, preserveHostHeader, cookies); } catch (IOException e) { rejectTarget(req, host, e); } return; } vertx.executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host)) - .onSuccess(address -> proxyRequestTo(req, address, host, port, preserveHostHeader)) + .onSuccess(address -> proxyRequestTo(req, address, host, port, preserveHostHeader, cookies)) .onFailure(err -> rejectTarget(req, host, err)); } @@ -717,7 +725,7 @@ public class ElbV2DataPlane { } private void proxyRequestTo(HttpServerRequest req, String address, String host, int port, - boolean preserveHostHeader) { + boolean preserveHostHeader, List cookies) { RequestOptions opts = new RequestOptions() .setHost(address) .setPort(port) @@ -742,6 +750,7 @@ public class ElbV2DataPlane { responseStarted.set(true); req.response().setStatusCode(resp.statusCode()); copyTargetResponseHeaders(resp.headers(), req.response()); + cookies.forEach(cookie -> req.response().headers().add("Set-Cookie", cookie)); if (resp.getHeader("Content-Length") == null) { req.response().setChunked(true); } @@ -805,12 +814,12 @@ public class ElbV2DataPlane { } private void proxyUpgrade(HttpServerRequest req, String host, int port, boolean preserveHostHeader, - long idleTimeoutMillis) { + long idleTimeoutMillis, List cookies) { req.pause(); if (ElbV2TargetResolver.isIpLiteral(host)) { try { proxyUpgradeTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port, - preserveHostHeader, idleTimeoutMillis); + preserveHostHeader, idleTimeoutMillis, cookies); } catch (IOException e) { rejectTarget(req, host, e); } @@ -818,7 +827,7 @@ public class ElbV2DataPlane { } vertx.executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host)) .onSuccess(address -> proxyUpgradeTo(req, address, host, port, preserveHostHeader, - idleTimeoutMillis)) + idleTimeoutMillis, cookies)) .onFailure(err -> rejectTarget(req, host, err)); } @@ -828,7 +837,7 @@ public class ElbV2DataPlane { * the target refused the upgrade and is relayed as an ordinary response. */ private void proxyUpgradeTo(HttpServerRequest req, String address, String host, int port, - boolean preserveHostHeader, long idleTimeoutMillis) { + boolean preserveHostHeader, long idleTimeoutMillis, List cookies) { RequestOptions opts = new RequestOptions() .setHost(address) .setPort(port) @@ -850,6 +859,7 @@ public class ElbV2DataPlane { .onSuccess(resp -> { req.response().setStatusCode(resp.statusCode()); copyTargetResponseHeaders(resp.headers(), req.response()); + cookies.forEach(cookie -> req.response().headers().add("Set-Cookie", cookie)); if (resp.statusCode() != 101) { req.resume(); if (resp.getHeader("Content-Length") == null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickyCookie.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickyCookie.java new file mode 100644 index 0000000000..bfd10bc72b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickyCookie.java @@ -0,0 +1,133 @@ +package io.github.hectorvent.floci.services.elbv2; + +import io.github.hectorvent.floci.services.elbv2.model.TargetDescription; +import io.github.hectorvent.floci.services.elbv2.model.TargetGroup; + +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Base64; +import java.util.List; +import java.util.Map; + +/** + * Duration-based ALB cookies, scoped to one load balancer and target group. + * See https://docs.aws.amazon.com/elasticloadbalancing/latest/application/edit-target-group-attributes.html#sticky-sessions. + */ +final class ElbV2StickyCookie { + + private static final long COOKIE_LIFETIME_SECONDS = 604800; + private static final int NONCE_BYTES = 12; + private final SecureRandom random = new SecureRandom(); + private final SecretKeySpec key; + private final Clock clock; + + ElbV2StickyCookie() { + this(Clock.systemUTC()); + } + + ElbV2StickyCookie(Clock clock) { + this.clock = clock; + byte[] secret = new byte[32]; + random.nextBytes(secret); + key = new SecretKeySpec(secret, "AES"); + } + + static long durationSeconds(TargetGroup group) { + Map attributes = group.getAttributes(); + // ALB-level cross-zone balancing is always on; only the target group can disable it. + if (!Boolean.parseBoolean(attributes.get("stickiness.enabled")) + || !"lb_cookie".equals(attributes.getOrDefault("stickiness.type", "lb_cookie")) + || !("HTTP".equals(group.getProtocol()) || "HTTPS".equals(group.getProtocol())) + || !("instance".equals(group.getTargetType()) || "ip".equals(group.getTargetType())) + || "false".equals(attributes.get("load_balancing.cross_zone.enabled")) + || "weighted_random".equals(attributes.get("load_balancing.algorithm.type"))) { + return 0; + } + try { + long duration = Long.parseLong(attributes.getOrDefault("stickiness.lb_cookie.duration_seconds", "86400")); + return duration >= 1 && duration <= COOKIE_LIFETIME_SECONDS ? duration : 0; + } catch (NumberFormatException ignored) { + // Invalid stored attributes must not break data-plane requests. + return 0; + } + } + + TargetDescription target(List headers, String scope, TargetGroup group, + List candidates, long duration) { + if (duration == 0) { + return null; + } + String value = cookie(headers, "AWSALBCORS"); + if (value == null) { + value = cookie(headers, "AWSALB"); + } + if (value == null || value.length() > 2048) { + return null; + } + try { + byte[] encoded = Base64.getUrlDecoder().decode(value); + if (encoded.length < NONCE_BYTES + 16) { + return null; + } + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, encoded, 0, NONCE_BYTES)); + cipher.updateAAD(scope.getBytes(StandardCharsets.UTF_8)); + String[] binding = new String(cipher.doFinal(encoded, NONCE_BYTES, encoded.length - NONCE_BYTES), + StandardCharsets.UTF_8).split("\n", 3); + if (binding.length != 3) { + return null; + } + long age = clock.instant().getEpochSecond() - Long.parseLong(binding[0]); + int port = Integer.parseInt(binding[1]); + if (age < 0 || age >= duration || age >= COOKIE_LIFETIME_SECONDS) { + return null; + } + return candidates.stream().filter(target -> binding[2].equals(target.getId()) + && port == ElbV2HealthChecker.effectivePort(target, group)).findFirst().orElse(null); + } catch (GeneralSecurityException | IllegalArgumentException ignored) { + // A stale, malformed or modified client cookie selects a new target instead. + return null; + } + } + + List headers(String scope, TargetGroup group, TargetDescription target) { + byte[] nonce = new byte[NONCE_BYTES]; + random.nextBytes(nonce); + String binding = clock.instant().getEpochSecond() + "\n" + + ElbV2HealthChecker.effectivePort(target, group) + "\n" + target.getId(); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, nonce)); + cipher.updateAAD(scope.getBytes(StandardCharsets.UTF_8)); + byte[] encrypted = cipher.doFinal(binding.getBytes(StandardCharsets.UTF_8)); + String value = Base64.getUrlEncoder().withoutPadding().encodeToString( + ByteBuffer.allocate(nonce.length + encrypted.length).put(nonce).put(encrypted).array()); + String attributes = "; Expires=" + DateTimeFormatter.RFC_1123_DATE_TIME.format( + clock.instant().plusSeconds(COOKIE_LIFETIME_SECONDS).atZone(ZoneOffset.UTC)) + "; Path=/"; + return List.of("AWSALB=" + value + attributes, + "AWSALBCORS=" + value + attributes + "; SameSite=None; Secure"); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Cannot generate ALB stickiness cookie", e); + } + } + + private static String cookie(List headers, String name) { + for (String header : headers) { + for (String part : header.split(";")) { + String trimmed = part.trim(); + if (trimmed.startsWith(name + "=")) { + return trimmed.substring(name.length() + 1); + } + } + } + return null; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickinessIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickinessIntegrationTest.java new file mode 100644 index 0000000000..a2b69c6ddc --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickinessIntegrationTest.java @@ -0,0 +1,207 @@ +package io.github.hectorvent.floci.services.elbv2; + +import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile; +import io.github.hectorvent.floci.testutil.FreePorts; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServer; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@TestProfile(RealElbV2DataPlaneProfile.class) +class ElbV2StickinessIntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261019/us-east-1/elasticloadbalancing/aws4_request"; + + @Inject + Vertx vertx; + + private HttpServer first; + private HttpServer second; + private String loadBalancerArn; + private String targetGroupArn; + private int listenerPort; + private final AtomicReference unhealthy = new AtomicReference<>(); + + @BeforeEach + void startTargetsAndListener() throws Exception { + first = backend("first"); + second = backend("second"); + listenerPort = FreePorts.anyInterfacePort(); + loadBalancerArn = query("CreateLoadBalancer", "Name", "sticky-lb", "Type", "application") + .xmlPath().getString("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn"); + targetGroupArn = query("CreateTargetGroup", "Name", "sticky-tg", "Protocol", "HTTP", + "Port", first.actualPort(), "TargetType", "ip", "HealthCheckPath", "/health", + "HealthCheckIntervalSeconds", 1, "HealthyThresholdCount", 1, "UnhealthyThresholdCount", 1) + .xmlPath().getString("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn"); + query("RegisterTargets", "TargetGroupArn", targetGroupArn, + "Targets.member.1.Id", "127.0.0.1", "Targets.member.1.Port", first.actualPort(), + "Targets.member.2.Id", "127.0.0.1", "Targets.member.2.Port", second.actualPort()); + query("CreateListener", "LoadBalancerArn", loadBalancerArn, "Protocol", "HTTP", "Port", listenerPort, + "DefaultActions.member.1.Type", "forward", "DefaultActions.member.1.TargetGroupArn", targetGroupArn); + await().atMost(Duration.ofSeconds(3)).ignoreExceptions() + .untilAsserted(() -> assertEquals(200, request(null).statusCode())); + } + + @AfterEach + void cleanUp() throws Exception { + if (loadBalancerArn != null) { + query("DeleteLoadBalancer", "LoadBalancerArn", loadBalancerArn); + } + if (targetGroupArn != null) { + query("DeleteTargetGroup", "TargetGroupArn", targetGroupArn); + } + for (HttpServer backend : List.of(first, second)) { + backend.close().toCompletionStage().toCompletableFuture().get(3, TimeUnit.SECONDS); + } + } + + @Test + void enabledCookiePinsTargetAndPreservesApplicationCookies() { + enableStickiness(true); + Response initial = request(null); + String cookie = initial.getCookie("AWSALB"); + assertNotNull(cookie); + assertEquals(cookie, initial.getCookie("AWSALBCORS")); + assertTrue(initial.headers().getValues("Set-Cookie").contains("app=one; Path=/")); + assertTrue(initial.headers().getValues("Set-Cookie").contains("other=two; Path=/")); + for (int i = 0; i < 10; i++) { + Response next = request("AWSALB=" + cookie); + assertEquals(200, next.statusCode()); + assertEquals(initial.asString(), next.asString()); + assertNotNull(next.getCookie("AWSALB")); + } + } + + @Test + void disabledStickinessKeepsRoundRobinAndDoesNotIssueCookies() { + Response initial = request(null); + Response next = request("AWSALB=invalid"); + assertNotEquals(initial.asString(), next.asString()); + assertEquals(null, initial.getCookie("AWSALB")); + assertEquals(null, next.getCookie("AWSALBCORS")); + } + + @Test + void absentAndInvalidCookiesStillUseRoundRobin() { + enableStickiness(true); + Response initial = request(null); + Response next = request("AWSALB=not-a-valid-cookie"); + assertNotEquals(initial.asString(), next.asString()); + assertNotNull(next.getCookie("AWSALB")); + assertEquals(initial.asString(), request(null).asString()); + } + + @Test + void deregisteredTargetIsReplacedAndTheCookieIsUpdated() { + enableStickiness(true); + Response initial = request(null); + int removedPort = "first".equals(initial.asString()) ? first.actualPort() : second.actualPort(); + query("DeregisterTargets", "TargetGroupArn", targetGroupArn, + "Targets.member.1.Id", "127.0.0.1", "Targets.member.1.Port", removedPort); + Response replacement = request("AWSALB=" + initial.getCookie("AWSALB")); + assertNotEquals(initial.asString(), replacement.asString()); + assertNotNull(replacement.getCookie("AWSALB")); + assertEquals(replacement.asString(), request("AWSALB=" + replacement.getCookie("AWSALB")).asString()); + } + + @Test + void unhealthyTargetDoesNotKeepItsStickyClient() { + enableStickiness(true); + Response initial = request(null); + unhealthy.set(initial.asString()); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> { + List states = query("DescribeTargetHealth", "TargetGroupArn", targetGroupArn).xmlPath() + .getList("DescribeTargetHealthResponse.DescribeTargetHealthResult" + + ".TargetHealthDescriptions.member.TargetHealth.State"); + assertTrue(states.contains("unhealthy")); + }); + Response replacement = request("AWSALB=" + initial.getCookie("AWSALB")); + assertNotEquals(initial.asString(), replacement.asString()); + assertNotNull(replacement.getCookie("AWSALB")); + } + + @Test + void disablingStickinessIgnoresAnExistingCookie() { + enableStickiness(true); + Response initial = request(null); + enableStickiness(false); + Response next = request("AWSALB=" + initial.getCookie("AWSALB")); + assertNotEquals(initial.asString(), next.asString()); + assertEquals(null, next.getCookie("AWSALB")); + } + + @Test + void targetGroupCrossZoneSettingControlsExistingCookies() { + enableStickiness(true); + Response initial = request(null); + String cookie = initial.getCookie("AWSALB"); + assertNotNull(cookie); + query("ModifyTargetGroupAttributes", "TargetGroupArn", targetGroupArn, + "Attributes.member.1.Key", "load_balancing.cross_zone.enabled", "Attributes.member.1.Value", false); + Response next = request("AWSALB=" + cookie); + assertNotEquals(initial.asString(), next.asString()); + assertEquals(null, next.getCookie("AWSALB")); + assertEquals(null, next.getCookie("AWSALBCORS")); + + query("ModifyTargetGroupAttributes", "TargetGroupArn", targetGroupArn, + "Attributes.member.1.Key", "load_balancing.cross_zone.enabled", + "Attributes.member.1.Value", "use_load_balancer_configuration"); + Response restored = request("AWSALB=" + cookie); + assertEquals(initial.asString(), restored.asString()); + assertNotNull(restored.getCookie("AWSALB")); + } + + private void enableStickiness(boolean enabled) { + query("ModifyTargetGroupAttributes", "TargetGroupArn", targetGroupArn, + "Attributes.member.1.Key", "stickiness.enabled", "Attributes.member.1.Value", enabled); + } + + private HttpServer backend(String body) throws Exception { + return vertx.createHttpServer().requestHandler(request -> { + if ("/health".equals(request.path()) && body.equals(unhealthy.get())) { + request.response().setStatusCode(503).end(); + return; + } + request.response().headers().add("Set-Cookie", "app=one; Path=/") + .add("Set-Cookie", "other=two; Path=/"); + request.response().end(body); + }).listen(0, "127.0.0.1") + .toCompletionStage().toCompletableFuture().get(3, TimeUnit.SECONDS); + } + + private Response request(String cookie) { + RequestSpecification request = given().baseUri("http://127.0.0.1").port(listenerPort); + if (cookie != null) { + request.header("Cookie", cookie); + } + return request.get("/"); + } + + private static Response query(String action, Object... parameters) { + RequestSpecification request = given().header("Authorization", AUTH).formParam("Action", action); + for (int i = 0; i < parameters.length; i += 2) { + request.formParam(parameters[i].toString(), parameters[i + 1]); + } + return request.post("/").then().statusCode(200).extract().response(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickyCookieTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickyCookieTest.java new file mode 100644 index 0000000000..018aff24ac --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickyCookieTest.java @@ -0,0 +1,151 @@ +package io.github.hectorvent.floci.services.elbv2; + +import io.github.hectorvent.floci.services.elbv2.model.TargetDescription; +import io.github.hectorvent.floci.services.elbv2.model.TargetGroup; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Instant; +import java.util.Base64; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class ElbV2StickyCookieTest { + + private static final String SCOPE = "load-balancer\ntarget-group"; + private final Clock clock = mock(Clock.class); + private final TargetGroup group = new TargetGroup(); + private final TargetDescription first = target(8080); + private final TargetDescription second = target(8081); + private Instant now = Instant.parse("2026-10-19T00:00:00Z"); + private ElbV2StickyCookie cookies; + + @BeforeEach + void setUp() { + when(clock.instant()).thenAnswer(ignored -> now); + cookies = new ElbV2StickyCookie(clock); + group.setProtocol("HTTP"); + group.setTargetType("ip"); + group.setPort(8080); + group.getAttributes().put("stickiness.enabled", "true"); + } + + @Test + void bindsTheEffectivePortAndOnlyCurrentCandidates() { + String value = value(first); + assertSame(first, select("AWSALB=" + value, List.of(first, second), 10)); + assertNull(select("AWSALB=" + value, List.of(second), 10)); + first.setPort(null); + assertSame(first, select("AWSALB=" + value, List.of(first), 10)); + group.setPort(8082); + assertNull(select("AWSALB=" + value, List.of(first), 10)); + } + + @Test + void expiresAtTheConfiguredDurationAndRejectsFutureCookies() { + String value = value(first); + now = now.plusSeconds(4); + assertSame(first, select("AWSALB=" + value, List.of(first), 5)); + String refreshed = value(first); + now = now.plusSeconds(1); + assertNull(select("AWSALB=" + value, List.of(first), 5)); + assertSame(first, select("AWSALB=" + refreshed, List.of(first), 5)); + now = now.minusSeconds(6); + assertNull(select("AWSALB=" + value, List.of(first), 5)); + } + + @Test + void rejectsModifiedMalformedOversizedAndOtherScopeCookies() { + String value = value(first); + byte[] modified = Base64.getUrlDecoder().decode(value); + modified[modified.length - 1] ^= 1; + String tampered = Base64.getUrlEncoder().withoutPadding().encodeToString(modified); + for (String invalid : List.of(tampered, "not%encoded", "", "a", "x".repeat(2049))) { + assertNull(select("AWSALB=" + invalid, List.of(first), 10)); + } + assertNull(cookies.target(List.of("AWSALB=" + value), "other-load-balancer\ntarget-group", + group, List.of(first), 10)); + assertNull(cookies.target(List.of("AWSALB=" + value), "load-balancer\nother-group", + group, List.of(first), 10)); + assertNull(new ElbV2StickyCookie(clock).target(List.of("AWSALB=" + value), SCOPE, + group, List.of(first), 10)); + } + + @Test + void corsCookieTakesPrecedenceAcrossCookieHeaders() { + String regular = value(first); + String cors = value(second); + assertSame(second, cookies.target(List.of("other=one; AWSALB=" + regular, "AWSALBCORS=" + cors), + SCOPE, group, List.of(first, second), 10)); + assertNull(select("AWSALB=" + regular + "; AWSALBCORS=invalid", List.of(first, second), 10)); + assertNull(select("XAWSALB=" + regular, List.of(first), 10)); + } + + @Test + void emitsBothCookiesWithSevenDayExpiresAndCorsAttributes() { + List headers = cookies.headers(SCOPE, group, first); + assertEquals(2, headers.size()); + assertEquals(headers.get(0).substring("AWSALB".length()), + headers.get(1).substring("AWSALBCORS".length()).replace("; SameSite=None; Secure", "")); + assertTrue(headers.get(0).contains("; Expires=Mon, 26 Oct 2026 00:00:00 GMT; Path=/")); + assertTrue(headers.get(1).endsWith("; SameSite=None; Secure")); + assertFalse(headers.get(0).contains("Max-Age")); + } + + @Test + void enablesOnlySupportedDurationBasedConfigurations() { + assertEquals(86400, ElbV2StickyCookie.durationSeconds(group)); + for (String duration : List.of("0", "604801", "-1", "oops")) { + group.getAttributes().put("stickiness.lb_cookie.duration_seconds", duration); + assertEquals(0, ElbV2StickyCookie.durationSeconds(group)); + } + group.getAttributes().put("stickiness.lb_cookie.duration_seconds", "604800"); + assertEquals(604800, ElbV2StickyCookie.durationSeconds(group)); + group.getAttributes().put("stickiness.type", "app_cookie"); + assertEquals(0, ElbV2StickyCookie.durationSeconds(group)); + group.getAttributes().put("stickiness.type", "lb_cookie"); + group.getAttributes().put("load_balancing.algorithm.type", "weighted_random"); + assertEquals(0, ElbV2StickyCookie.durationSeconds(group)); + group.getAttributes().remove("load_balancing.algorithm.type"); + group.getAttributes().put("load_balancing.cross_zone.enabled", "false"); + assertEquals(0, ElbV2StickyCookie.durationSeconds(group)); + group.getAttributes().remove("load_balancing.cross_zone.enabled"); + group.setProtocol("TCP"); + assertEquals(0, ElbV2StickyCookie.durationSeconds(group)); + } + + @Test + void crossZoneOnlyUsesTheTargetGroupSetting() { + assertEquals(86400, ElbV2StickyCookie.durationSeconds(group)); + for (String enabled : List.of("true", "use_load_balancer_configuration")) { + group.getAttributes().put("load_balancing.cross_zone.enabled", enabled); + assertEquals(86400, ElbV2StickyCookie.durationSeconds(group)); + } + group.getAttributes().put("load_balancing.cross_zone.enabled", "false"); + assertEquals(0, ElbV2StickyCookie.durationSeconds(group)); + } + + private String value(TargetDescription target) { + String header = cookies.headers(SCOPE, group, target).getFirst(); + return header.substring("AWSALB=".length(), header.indexOf(';')); + } + + private TargetDescription select(String header, List candidates, long duration) { + return cookies.target(List.of(header), SCOPE, group, candidates, duration); + } + + private static TargetDescription target(int port) { + TargetDescription target = new TargetDescription(); + target.setId("127.0.0.1"); + target.setPort(port); + return target; + } +}