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

@@ -96,6 +96,7 @@ public class ElbV2DataPlane {
private final Map<String, AtomicReference<List<CompiledRule>>> ruleChains = new ConcurrentHashMap<>();
private final Map<String, AtomicInteger> rrCounters = new ConcurrentHashMap<>();
private final Map<String, String> 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<String> 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<String> 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.<String>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<String> 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<String> 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.<String>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<String> 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) {
@@ -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<String, String> 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<String> headers, String scope, TargetGroup group,
List<TargetDescription> 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<String> 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<String> 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;
}
}