fix(elbv2): apply duration-based target stickiness (#5978)

* fix(elbv2): apply duration-based target stickiness

* fix(elbv2): honor inherited cross-zone stickiness

* fix(elbv2): simplify target-group stickiness eligibility
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-10-19 10:23:45 -04:00
1 parent 6e5b1569fe
commit 4c9deed379
5 files changed
+528 -13

No files matched your search

@@ -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<String> 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<String> 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();
}
}
@@ -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<String> 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<TargetDescription> 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;
}
}