mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudfront): tunnel WebSocket upgrades to custom origins as AWS does (#7148)
* fix(cloudfront): tunnel WebSocket upgrades to custom origins as AWS does CloudFront forwards WebSocket handshakes to the origin on every distribution, but Floci's serving path is a JAX-RS resource that strips Upgrade and Connection and fetches the origin with a blocking client, so a socket.io client behind a distribution never left long-polling. A Vert.x route ahead of JAX-RS now catches an HTTP/1.1 WebSocket handshake to a distribution host, resolves the behavior and custom origin as the GET path does (allowed methods, signed requests, origin request policy, origin custom headers, private-address guard), sends the handshake with its upgrade fields and splices the two connections once the origin answers 101. Any other answer is relayed as an ordinary response, and handshakes the distribution would not tunnel fall through to the existing GET handling. Handshake detection and the byte relay are shared with the ALB data plane. * fix(cloudfront): honor disabled service and origin timeouts on WebSocket refusals The WebSocket route runs ahead of ServiceEnabledFilter, so it now checks that CloudFront is enabled before taking a handshake and otherwise falls through to the disabled-service answer. An origin answer that refuses the upgrade is no longer piped without limits: its body is streamed within the origin's response timeout between packets and its response completion timeout in all, counting only the origin's time, and an origin that stalls past them ends the viewer connection. * test: share the ALB fixture between the WebSocket integration tests CloudFrontWebSocketIntegrationTest repeated ElbV2WebSocketIntegrationTest's load balancer, target group, listener and WebSocket exchange helpers. Both now use AlbFixtures. * refactor(cloudfront): have the WebSocket origin clock spend a shared CompletionBudget
This commit is contained in:
1 parent
f489a6f1f3
commit
d2d9ed6ca2
9 files changed
+1000
-227
No files matched your search
+284
@@ -0,0 +1,284 @@
|
||||
package io.github.hectorvent.floci.services.cloudfront;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.quarkus.test.junit.mockito.InjectSpy;
|
||||
import io.restassured.RestAssured;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.UpgradeRejectedException;
|
||||
import io.vertx.core.http.WebSocket;
|
||||
import io.vertx.core.http.WebSocketConnectOptions;
|
||||
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.extension.RegisterExtension;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.createListener;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.createLoadBalancer;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.createTargetGroup;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.deleteListener;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.deleteLoadBalancer;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.deleteTargetGroup;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.exchange;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.registerTarget;
|
||||
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.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
|
||||
/**
|
||||
* Tunnels WebSocket connections through a distribution whose custom origin is an ALB listener, as
|
||||
* CloudFront does on every distribution: viewer, distribution, load balancer and an echo target.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(CloudFrontWebSocketIntegrationTest.AlbOriginProfile.class)
|
||||
class CloudFrontWebSocketIntegrationTest {
|
||||
|
||||
/** The real ELBv2 data plane, and an origin at 127.0.0.1 that CloudFront would otherwise refuse. */
|
||||
public static class AlbOriginProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.services.elbv2.mock", "false",
|
||||
"floci.services.cloudfront.allowed-private-origin-hosts", "127.0.0.1");
|
||||
}
|
||||
}
|
||||
|
||||
private static final int LISTENER_PORT = 7797;
|
||||
private static final String CACHING_DISABLED = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad";
|
||||
private static final String ALL_VIEWER = "216adef6-5c7f-47e4-b989-5492eafa07d3";
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
|
||||
@Inject
|
||||
CloudFrontService cloudFrontService;
|
||||
|
||||
@InjectSpy
|
||||
ServiceConfigAccess serviceConfigAccess;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
private final AtomicReference<String> originCustomHeader = new AtomicReference<>();
|
||||
private final AtomicInteger originUpgrades = new AtomicInteger();
|
||||
private HttpServer backend;
|
||||
private HttpClient client;
|
||||
private String loadBalancerArn;
|
||||
private String targetGroupArn;
|
||||
private String listenerArn;
|
||||
|
||||
@BeforeEach
|
||||
void startAlbOrigin() throws Exception {
|
||||
backend = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
originCustomHeader.set(request.getHeader("X-Origin-Verify"));
|
||||
if (!"websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) {
|
||||
request.response().setStatusCode(400).end("not an upgrade");
|
||||
return;
|
||||
}
|
||||
originUpgrades.incrementAndGet();
|
||||
if (request.path().startsWith("/stall/")) {
|
||||
// Refuses the upgrade, then never finishes the body.
|
||||
request.response().setChunked(true).setStatusCode(503).write("partial");
|
||||
} else if (!request.path().startsWith("/socket.io/")) {
|
||||
request.response().headers().add("X-Multi", "one").add("X-Multi", "two");
|
||||
request.response().setStatusCode(404).end("upgrade refused");
|
||||
} else {
|
||||
String query = request.query();
|
||||
// A handshake without Sec-WebSocket-Key is answered 400 by Vert.x itself.
|
||||
request.toWebSocket().onSuccess(socket -> socket.textMessageHandler(
|
||||
text -> socket.writeTextMessage(query + ":" + text)));
|
||||
}
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage()
|
||||
.toCompletableFuture()
|
||||
.get(2, TimeUnit.SECONDS);
|
||||
client = vertx.createHttpClient();
|
||||
loadBalancerArn = createLoadBalancer("cloudfront-websocket-lb");
|
||||
targetGroupArn = createTargetGroup("cloudfront-websocket-tg", "ip", backend.actualPort());
|
||||
registerTarget(targetGroupArn, "127.0.0.1", backend.actualPort());
|
||||
listenerArn = createListener(loadBalancerArn, targetGroupArn, LISTENER_PORT);
|
||||
await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> given()
|
||||
.baseUri("http://127.0.0.1")
|
||||
.port(LISTENER_PORT)
|
||||
.when()
|
||||
.get("/")
|
||||
.then()
|
||||
.statusCode(400));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopAlbOrigin() throws Exception {
|
||||
deleteListener(listenerArn);
|
||||
deleteTargetGroup(targetGroupArn);
|
||||
deleteLoadBalancer(loadBalancerArn);
|
||||
client.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
backend.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tunnelsWebSocketThroughDistributionToAlbOrigin() throws Exception {
|
||||
Distribution distribution = createDistribution(policyBehavior(ALL_VIEWER));
|
||||
|
||||
WebSocket socket = connect(distribution, "/socket.io/?EIO=4&transport=websocket");
|
||||
try {
|
||||
assertEquals("EIO=4&transport=websocket:hello", exchange(socket, "hello"));
|
||||
assertEquals("EIO=4&transport=websocket:again", exchange(socket, "again"));
|
||||
} finally {
|
||||
socket.close();
|
||||
}
|
||||
assertEquals("shared-secret", originCustomHeader.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tunnelsWebSocketWithLegacyCacheSettings() throws Exception {
|
||||
Distribution distribution = createDistribution(legacyBehavior());
|
||||
|
||||
WebSocket socket = connect(distribution, "/socket.io/?transport=websocket");
|
||||
try {
|
||||
// Legacy cache settings forward no query string unless ForwardedValues asks for it.
|
||||
assertEquals("null:hello", exchange(socket, "hello"));
|
||||
} finally {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void handshakeFailsWhenPolicyDoesNotForwardWebSocketKey() {
|
||||
// AWS requires the origin request policy to forward Sec-WebSocket-Key and -Version.
|
||||
Distribution distribution = createDistribution(policyBehavior(null));
|
||||
|
||||
ExecutionException failure = assertThrows(ExecutionException.class,
|
||||
() -> connect(distribution, "/socket.io/?transport=websocket"));
|
||||
|
||||
UpgradeRejectedException rejected = assertInstanceOf(UpgradeRejectedException.class, failure.getCause());
|
||||
assertEquals(400, rejected.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void relaysOriginRefusalOfUpgrade() {
|
||||
Distribution distribution = createDistribution(policyBehavior(ALL_VIEWER));
|
||||
|
||||
ExecutionException failure = assertThrows(ExecutionException.class,
|
||||
() -> connect(distribution, "/elsewhere/?transport=websocket"));
|
||||
|
||||
UpgradeRejectedException rejected = assertInstanceOf(UpgradeRejectedException.class, failure.getCause());
|
||||
assertEquals(404, rejected.getStatus());
|
||||
assertEquals(List.of("one", "two"), rejected.getHeaders().getAll("X-Multi"));
|
||||
assertEquals("upgrade refused", rejected.getBody().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainRequestThroughDistributionCarriesNoUpgrade() {
|
||||
Distribution distribution = createDistribution(policyBehavior(ALL_VIEWER));
|
||||
|
||||
given()
|
||||
.header("Host", distribution.getDomainName())
|
||||
.when()
|
||||
.get("/socket.io/?transport=polling")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(equalTo("not an upgrade"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void endsRefusalWhoseBodyStallsPastOriginReadTimeout() {
|
||||
Distribution distribution = createDistribution(policyBehavior(ALL_VIEWER), 1);
|
||||
|
||||
// A refusal that never ends would leave connect() waiting past its 5 s limit (a TimeoutException).
|
||||
assertThrows(ExecutionException.class, () -> connect(distribution, "/stall/?transport=websocket"));
|
||||
assertEquals(1, originUpgrades.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledCloudFrontDoesNotTunnel() {
|
||||
Distribution distribution = createDistribution(policyBehavior(ALL_VIEWER));
|
||||
doReturn(false).when(serviceConfigAccess).isEnabled("cloudfront");
|
||||
|
||||
ExecutionException failure = assertThrows(ExecutionException.class,
|
||||
() -> connect(distribution, "/socket.io/?transport=websocket"));
|
||||
|
||||
assertInstanceOf(UpgradeRejectedException.class, failure.getCause());
|
||||
assertEquals(0, originUpgrades.get());
|
||||
}
|
||||
|
||||
private Distribution createDistribution(DefaultCacheBehavior behavior) {
|
||||
return createDistribution(behavior, null);
|
||||
}
|
||||
|
||||
private Distribution createDistribution(DefaultCacheBehavior behavior, Integer originReadTimeoutSeconds) {
|
||||
Origin origin = new Origin();
|
||||
origin.setId("alb");
|
||||
origin.setDomainName("127.0.0.1");
|
||||
Map<String, Object> customOriginConfig = new LinkedHashMap<>();
|
||||
customOriginConfig.put("HTTPPort", String.valueOf(LISTENER_PORT));
|
||||
customOriginConfig.put("HTTPSPort", "443");
|
||||
customOriginConfig.put("OriginProtocolPolicy", "http-only");
|
||||
if (originReadTimeoutSeconds != null) {
|
||||
customOriginConfig.put("OriginReadTimeout", String.valueOf(originReadTimeoutSeconds));
|
||||
}
|
||||
origin.setCustomOriginConfig(customOriginConfig);
|
||||
origin.setCustomHeaders(List.of(new LinkedHashMap<>(Map.of(
|
||||
"HeaderName", "X-Origin-Verify", "HeaderValue", "shared-secret"))));
|
||||
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(true);
|
||||
config.setOrigins(List.of(origin));
|
||||
config.setDefaultCacheBehavior(behavior);
|
||||
Distribution distribution = new Distribution();
|
||||
distribution.setConfig(config);
|
||||
Distribution created = cloudFrontService.createDistribution(distribution, Map.of());
|
||||
cleanup.register(() -> cloudFrontService.removeDistribution(created.getId()));
|
||||
return created;
|
||||
}
|
||||
|
||||
private static DefaultCacheBehavior legacyBehavior() {
|
||||
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
|
||||
behavior.setTargetOriginId("alb");
|
||||
behavior.setViewerProtocolPolicy("allow-all");
|
||||
return behavior;
|
||||
}
|
||||
|
||||
private static DefaultCacheBehavior policyBehavior(String originRequestPolicyId) {
|
||||
DefaultCacheBehavior behavior = legacyBehavior();
|
||||
behavior.setCachePolicyId(CACHING_DISABLED);
|
||||
behavior.setOriginRequestPolicyId(originRequestPolicyId);
|
||||
return behavior;
|
||||
}
|
||||
|
||||
private WebSocket connect(Distribution distribution, String uri) throws Exception {
|
||||
return client.webSocket(new WebSocketConnectOptions()
|
||||
.setHost("127.0.0.1")
|
||||
.setPort(RestAssured.port)
|
||||
.setURI(uri)
|
||||
.putHeader("Host", distribution.getDomainName()))
|
||||
.toCompletionStage()
|
||||
.toCompletableFuture()
|
||||
.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
}
|
||||
+11
-123
@@ -23,6 +23,15 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.createListener;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.createLoadBalancer;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.createTargetGroup;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.deleteListener;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.deleteLoadBalancer;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.deleteTargetGroup;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.exchange;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.forwardDefaultActionTo;
|
||||
import static io.github.hectorvent.floci.testing.AlbFixtures.registerTarget;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
@@ -81,10 +90,10 @@ class ElbV2WebSocketIntegrationTest {
|
||||
.toCompletableFuture()
|
||||
.get(2, TimeUnit.SECONDS);
|
||||
client = vertx.createHttpClient();
|
||||
loadBalancerArn = createLoadBalancer();
|
||||
loadBalancerArn = createLoadBalancer("websocket-lb");
|
||||
targetGroupArn = createTargetGroup("websocket-tg", "ip", backend.actualPort());
|
||||
registerTarget(targetGroupArn, "127.0.0.1", backend.actualPort());
|
||||
listenerArn = createListener(loadBalancerArn, targetGroupArn);
|
||||
listenerArn = createListener(loadBalancerArn, targetGroupArn, LISTENER_PORT);
|
||||
await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> given()
|
||||
.baseUri("http://127.0.0.1")
|
||||
.port(LISTENER_PORT)
|
||||
@@ -241,19 +250,6 @@ class ElbV2WebSocketIntegrationTest {
|
||||
return targetGroupArn;
|
||||
}
|
||||
|
||||
private static void forwardDefaultActionTo(String listenerArn, String targetGroupArn) {
|
||||
given()
|
||||
.formParam("Action", "ModifyListener")
|
||||
.formParam("ListenerArn", listenerArn)
|
||||
.formParam("DefaultActions.member.1.Type", "forward")
|
||||
.formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn)
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private WebSocket connect(String uri) throws Exception {
|
||||
return client.webSocket(new WebSocketConnectOptions()
|
||||
.setHost("127.0.0.1")
|
||||
@@ -264,76 +260,6 @@ class ElbV2WebSocketIntegrationTest {
|
||||
.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static String exchange(WebSocket socket, String text) throws Exception {
|
||||
CompletableFuture<String> reply = new CompletableFuture<>();
|
||||
socket.textMessageHandler(reply::complete);
|
||||
socket.writeTextMessage(text);
|
||||
return reply.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static String createLoadBalancer() {
|
||||
return given()
|
||||
.formParam("Action", "CreateLoadBalancer")
|
||||
.formParam("Name", "websocket-lb")
|
||||
.formParam("Type", "application")
|
||||
.formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a"))
|
||||
.formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b"))
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
|
||||
}
|
||||
|
||||
private static String createTargetGroup(String name, String targetType, int backendPort) {
|
||||
return given()
|
||||
.formParam("Action", "CreateTargetGroup")
|
||||
.formParam("Name", name)
|
||||
.formParam("Protocol", "HTTP")
|
||||
.formParam("Port", backendPort)
|
||||
.formParam("TargetType", targetType)
|
||||
.formParam("HealthCheckEnabled", "false")
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
|
||||
}
|
||||
|
||||
private static void registerTarget(String targetGroupArn, String targetId, int backendPort) {
|
||||
given()
|
||||
.formParam("Action", "RegisterTargets")
|
||||
.formParam("TargetGroupArn", targetGroupArn)
|
||||
.formParam("Targets.member.1.Id", targetId)
|
||||
.formParam("Targets.member.1.Port", backendPort)
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static String createListener(String loadBalancerArn, String targetGroupArn) {
|
||||
return given()
|
||||
.formParam("Action", "CreateListener")
|
||||
.formParam("LoadBalancerArn", loadBalancerArn)
|
||||
.formParam("Protocol", "HTTP")
|
||||
.formParam("Port", LISTENER_PORT)
|
||||
.formParam("DefaultActions.member.1.Type", "forward")
|
||||
.formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn)
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn");
|
||||
}
|
||||
|
||||
private static void setIdleTimeout(String loadBalancerArn, int seconds) {
|
||||
given()
|
||||
.formParam("Action", "ModifyLoadBalancerAttributes")
|
||||
@@ -347,42 +273,4 @@ class ElbV2WebSocketIntegrationTest {
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static void deleteListener(String listenerArn) {
|
||||
if (listenerArn != null) {
|
||||
given()
|
||||
.formParam("Action", "DeleteListener")
|
||||
.formParam("ListenerArn", listenerArn)
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(anyOf(equalTo(200), equalTo(204)));
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteTargetGroup(String targetGroupArn) {
|
||||
if (targetGroupArn != null) {
|
||||
given()
|
||||
.formParam("Action", "DeleteTargetGroup")
|
||||
.formParam("TargetGroupArn", targetGroupArn)
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(anyOf(equalTo(200), equalTo(204)));
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteLoadBalancer(String loadBalancerArn) {
|
||||
if (loadBalancerArn != null) {
|
||||
given()
|
||||
.formParam("Action", "DeleteLoadBalancer")
|
||||
.formParam("LoadBalancerArn", loadBalancerArn)
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(anyOf(equalTo(200), equalTo(204)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.vertx.core.http.WebSocket;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/**
|
||||
* An application load balancer in front of a test's own target, for the classes that send traffic
|
||||
* through the real ELBv2 data plane, and the WebSocket exchange they check it with.
|
||||
*/
|
||||
public final class AlbFixtures {
|
||||
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261101/us-east-1/elasticloadbalancing/aws4_request";
|
||||
|
||||
private AlbFixtures() {
|
||||
}
|
||||
|
||||
public static String createLoadBalancer(String name) {
|
||||
return given()
|
||||
.formParam("Action", "CreateLoadBalancer")
|
||||
.formParam("Name", name)
|
||||
.formParam("Type", "application")
|
||||
.formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a"))
|
||||
.formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b"))
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
|
||||
}
|
||||
|
||||
/** An HTTP target group with health checks off, so a target serves as soon as it is registered. */
|
||||
public static String createTargetGroup(String name, String targetType, int targetPort) {
|
||||
return given()
|
||||
.formParam("Action", "CreateTargetGroup")
|
||||
.formParam("Name", name)
|
||||
.formParam("Protocol", "HTTP")
|
||||
.formParam("Port", targetPort)
|
||||
.formParam("TargetType", targetType)
|
||||
.formParam("HealthCheckEnabled", "false")
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
|
||||
}
|
||||
|
||||
public static void registerTarget(String targetGroupArn, String targetId, int targetPort) {
|
||||
given()
|
||||
.formParam("Action", "RegisterTargets")
|
||||
.formParam("TargetGroupArn", targetGroupArn)
|
||||
.formParam("Targets.member.1.Id", targetId)
|
||||
.formParam("Targets.member.1.Port", targetPort)
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
/** An HTTP listener on {@code port} that forwards every request to {@code targetGroupArn}. */
|
||||
public static String createListener(String loadBalancerArn, String targetGroupArn, int port) {
|
||||
return given()
|
||||
.formParam("Action", "CreateListener")
|
||||
.formParam("LoadBalancerArn", loadBalancerArn)
|
||||
.formParam("Protocol", "HTTP")
|
||||
.formParam("Port", port)
|
||||
.formParam("DefaultActions.member.1.Type", "forward")
|
||||
.formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn)
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn");
|
||||
}
|
||||
|
||||
public static void forwardDefaultActionTo(String listenerArn, String targetGroupArn) {
|
||||
given()
|
||||
.formParam("Action", "ModifyListener")
|
||||
.formParam("ListenerArn", listenerArn)
|
||||
.formParam("DefaultActions.member.1.Type", "forward")
|
||||
.formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn)
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
public static void deleteListener(String listenerArn) {
|
||||
delete("DeleteListener", "ListenerArn", listenerArn);
|
||||
}
|
||||
|
||||
public static void deleteTargetGroup(String targetGroupArn) {
|
||||
delete("DeleteTargetGroup", "TargetGroupArn", targetGroupArn);
|
||||
}
|
||||
|
||||
public static void deleteLoadBalancer(String loadBalancerArn) {
|
||||
delete("DeleteLoadBalancer", "LoadBalancerArn", loadBalancerArn);
|
||||
}
|
||||
|
||||
/** Sends {@code text} on the socket and returns the next text message it receives. */
|
||||
public static String exchange(WebSocket socket, String text) throws Exception {
|
||||
CompletableFuture<String> reply = new CompletableFuture<>();
|
||||
socket.textMessageHandler(reply::complete);
|
||||
socket.writeTextMessage(text);
|
||||
return reply.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static void delete(String action, String arnParameter, String arn) {
|
||||
if (arn == null) {
|
||||
return;
|
||||
}
|
||||
given()
|
||||
.formParam("Action", action)
|
||||
.formParam(arnParameter, arn)
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(anyOf(equalTo(200), equalTo(204)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user