mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
* feat(eventbridge): add ApiDestination target support (#4702) - Add ApiDestination, ApiDestinationState, and HttpParameters models - Implement CRUD operations for API destinations in EventBridgeService - Add CreateApiDestination, DescribeApiDestination, UpdateApiDestination, DeleteApiDestination, ListApiDestinations actions in EventBridgeHandler - Support HttpParameters on targets in PutTargets and ListTargetsByRule - Implement HTTP delivery to API destinations in EventBridgeInvoker with connection auth and SSRF protection - Add CloudFormation provisioning for AWS::Events::ApiDestination in EventsCfnProvisioner - Update docs and tests * fix(eventbridge): harden ApiDestination delivery and CloudFormation lifecycle - Throw on delivery failure so TargetDispatcher retries 429/5xx and connection errors and dead-letters permanent failures - Enforce InvocationRateLimitPerSecond per destination - Run the OAuth client-credentials exchange for OAUTH_CLIENT_CREDENTIALS connections - Reject non-http(s) endpoints and wildcard hosts, encode path parameter values, keep the query before any fragment, and stop logging URLs that may carry secrets - Resolve destination and connection ARNs only when they match the stored ARN - Validate every UpdateApiDestination field before applying any of them - Paginate ListApiDestinations with Limit and NextToken - Keep HttpParameters on AWS::Events::Rule targets and roll back AWS::Events::ApiDestination updates from a snapshot * fix(eventbridge): keep connection credentials authoritative and require a valid endpoint host - Apply target headers and query parameters before the connection's so a target cannot override its credentials, and replace header names that differ only by case - Reject endpoints without a parsed host (for example https://:8080/path) - Sweep stale rate-limit windows once the map grows * fix(eventbridge): make the ApiDestination rate limit check atomic Count permits inside ConcurrentHashMap.compute on an immutable window so the stale-window sweep can no longer remove a window another delivery is using, which let concurrent deliveries exceed InvocationRateLimitPerSecond. * refactor(eventbridge): drop the in-service InMemoryStorage constructor and tidy tests - Remove the compatibility constructor that instantiated InMemoryStorage inside EventBridgeService; tests pass the ApiDestination store explicitly - Import classes instead of qualifying them inline in the ApiDestination integration test - Surface worker failures in the concurrent rate limit test by checking each Future * docs: correct the EventBridge and IAM operation counts in the service matrix
This commit is contained in:
1 parent
fabcd6baf8
commit
108f2b54bf
19 files changed
+2413
-5
No files matched your search
+177
@@ -8,6 +8,8 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.ApiDestination;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.HttpParameters;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Rule;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -356,4 +358,179 @@ class EventsCfnProvisionerTest {
|
||||
verify(events, times(n)).putTargets(eq("orders"), any(), put.capture(), anyString());
|
||||
return put.getAllValues().stream().map(call -> call.stream().map(Target::getId).toList()).toList();
|
||||
}
|
||||
|
||||
// ── ApiDestination provisioning and deleting ──────────────────────────────
|
||||
|
||||
@Test
|
||||
void provisionApiDestinationCreatesResource() {
|
||||
ApiDestination destination = new ApiDestination(
|
||||
"orders-dest",
|
||||
"arn:aws:events:us-east-1:000000000000:api-destination/orders-dest/12345678",
|
||||
"arn:aws:events:us-east-1:000000000000:connection/conn/111",
|
||||
"https://api.example.com/orders",
|
||||
"POST",
|
||||
10,
|
||||
"Orders destination");
|
||||
when(events.createApiDestination(eq("orders-dest"), eq("Orders destination"),
|
||||
eq("arn:aws:events:us-east-1:000000000000:connection/conn/111"),
|
||||
eq("https://api.example.com/orders"), eq("POST"), eq(10), eq(REGION)))
|
||||
.thenReturn(destination);
|
||||
|
||||
StackResource r = resource("AWS::Events::ApiDestination", "MyDestination");
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("Name", "orders-dest")
|
||||
.put("ConnectionArn", "arn:aws:events:us-east-1:000000000000:connection/conn/111")
|
||||
.put("InvocationEndpoint", "https://api.example.com/orders")
|
||||
.put("HttpMethod", "POST")
|
||||
.put("InvocationRateLimitPerSecond", 10)
|
||||
.put("Description", "Orders destination");
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
assertEquals("orders-dest", r.getPhysicalId());
|
||||
assertEquals("arn:aws:events:us-east-1:000000000000:api-destination/orders-dest/12345678",
|
||||
r.getAttributes().get("Arn"));
|
||||
assertEquals("arn:aws:events:us-east-1:000000000000:api-destination/orders-dest",
|
||||
r.getAttributes().get("ArnForPolicy"));
|
||||
assertEquals("orders-dest", r.getAttributes().get("Name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionApiDestinationUpdatesResource() {
|
||||
ApiDestination destination = new ApiDestination(
|
||||
"orders-dest",
|
||||
"arn:aws:events:us-east-1:000000000000:api-destination/orders-dest/12345678",
|
||||
"arn:aws:events:us-east-1:000000000000:connection/conn/222",
|
||||
"https://api.example.com/v2/orders",
|
||||
"PUT",
|
||||
20,
|
||||
"Updated destination");
|
||||
when(events.updateApiDestination(eq("orders-dest"), eq("Updated destination"),
|
||||
eq("arn:aws:events:us-east-1:000000000000:connection/conn/222"),
|
||||
eq("https://api.example.com/v2/orders"), eq("PUT"), eq(20), eq(REGION)))
|
||||
.thenReturn(destination);
|
||||
when(events.describeApiDestination("orders-dest", REGION)).thenReturn(priorApiDestination());
|
||||
|
||||
StackResource r = resource("AWS::Events::ApiDestination", "MyDestination");
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("Name", "orders-dest")
|
||||
.put("ConnectionArn", "arn:aws:events:us-east-1:000000000000:connection/conn/222")
|
||||
.put("InvocationEndpoint", "https://api.example.com/v2/orders")
|
||||
.put("HttpMethod", "PUT")
|
||||
.put("InvocationRateLimitPerSecond", 20)
|
||||
.put("Description", "Updated destination");
|
||||
|
||||
provisioner.provision(r, props, ctx("orders-dest"));
|
||||
|
||||
verify(events).updateApiDestination(eq("orders-dest"), any(), any(), any(), any(), any(), eq(REGION));
|
||||
assertEquals("orders-dest", r.getPhysicalId());
|
||||
}
|
||||
|
||||
private static ApiDestination priorApiDestination() {
|
||||
return new ApiDestination(
|
||||
"orders-dest",
|
||||
"arn:aws:events:us-east-1:000000000000:api-destination/orders-dest/12345678",
|
||||
"arn:aws:events:us-east-1:000000000000:connection/conn/111",
|
||||
"https://api.example.com/v1/orders",
|
||||
"POST",
|
||||
null,
|
||||
"Original destination");
|
||||
}
|
||||
|
||||
private StackResource updatedApiDestination() {
|
||||
when(events.describeApiDestination("orders-dest", REGION)).thenReturn(priorApiDestination());
|
||||
when(events.updateApiDestination(any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(priorApiDestination());
|
||||
StackResource r = resource("AWS::Events::ApiDestination", "MyDestination");
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("Name", "orders-dest")
|
||||
.put("ConnectionArn", "arn:aws:events:us-east-1:000000000000:connection/conn/222")
|
||||
.put("InvocationEndpoint", "https://api.example.com/v2/orders")
|
||||
.put("HttpMethod", "PUT")
|
||||
.put("InvocationRateLimitPerSecond", 20);
|
||||
provisioner.provision(r, props, ctx("orders-dest"));
|
||||
return r;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRollbackPutsBackTheApiDestinationTheUpdateChanged() {
|
||||
StackResource r = updatedApiDestination();
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(events).restoreApiDestination("orders-dest", "Original destination",
|
||||
"arn:aws:events:us-east-1:000000000000:connection/conn/111",
|
||||
"https://api.example.com/v1/orders", "POST", null, REGION);
|
||||
assertFalse(provisioner.rollbackUpdate(r), "the snapshot is spent once restored");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anApiDestinationCreateTakesNoSnapshotToRollBack() {
|
||||
StackResource r = resource("AWS::Events::ApiDestination", "MyDestination");
|
||||
when(events.createApiDestination(any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(priorApiDestination());
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("Name", "orders-dest")
|
||||
.put("ConnectionArn", "arn:aws:events:us-east-1:000000000000:connection/conn/111")
|
||||
.put("InvocationEndpoint", "https://api.example.com/v1/orders")
|
||||
.put("HttpMethod", "POST");
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
assertFalse(provisioner.rollbackUpdate(r));
|
||||
verify(events, never()).restoreApiDestination(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuleTargetKeepsItsHttpParameters() {
|
||||
stubPutRule();
|
||||
when(events.listTargetsByRule(anyString(), any(), anyString())).thenReturn(List.of());
|
||||
ObjectNode destinationTarget = target("dest",
|
||||
"arn:aws:events:us-east-1:000000000000:api-destination/orders-dest/12345678");
|
||||
ObjectNode httpParameters = destinationTarget.putObject("HttpParameters");
|
||||
httpParameters.putArray("PathParameterValues").add("orders");
|
||||
httpParameters.putObject("HeaderParameters").put("x-tenant", "alpha");
|
||||
httpParameters.putObject("QueryStringParameters").put("version", "v1");
|
||||
ObjectNode props = mapper.createObjectNode().put("Name", "orders");
|
||||
props.putArray("Targets").add(destinationTarget);
|
||||
|
||||
provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, ctx("orders"));
|
||||
|
||||
ArgumentCaptor<List<Target>> put = ArgumentCaptor.forClass(List.class);
|
||||
verify(events).putTargets(eq("orders"), any(), put.capture(), anyString());
|
||||
HttpParameters stored = put.getValue().get(0).getHttpParameters();
|
||||
assertEquals(List.of("orders"), stored.getPathParameterValues());
|
||||
assertEquals("alpha", stored.getHeaderParameters().get("x-tenant"));
|
||||
assertEquals("v1", stored.getQueryStringParameters().get("version"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionApiDestinationRejectsNameChangeOnUpdate() {
|
||||
StackResource r = resource("AWS::Events::ApiDestination", "MyDestination");
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("Name", "new-name")
|
||||
.put("ConnectionArn", "arn:aws:events:us-east-1:000000000000:connection/conn/111")
|
||||
.put("InvocationEndpoint", "https://api.example.com/orders")
|
||||
.put("HttpMethod", "POST");
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, props, ctx("old-name")));
|
||||
|
||||
assertEquals("ValidationError", thrown.getErrorCode());
|
||||
assertTrue(thrown.getMessage().contains("requires resource replacement"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteApiDestinationCallsService() {
|
||||
provisioner.delete("AWS::Events::ApiDestination", "orders-dest", REGION);
|
||||
verify(events).deleteApiDestination("orders-dest", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteApiDestinationIgnoresAlreadyDeleted() {
|
||||
doThrow(new AwsException("ResourceNotFoundException", "Not found", 400))
|
||||
.when(events).deleteApiDestination("orders-dest", REGION);
|
||||
|
||||
provisioner.delete("AWS::Events::ApiDestination", "orders-dest", REGION);
|
||||
verify(events).deleteApiDestination("orders-dest", REGION);
|
||||
}
|
||||
}
|
||||
+396
@@ -0,0 +1,396 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class EventBridgeApiDestinationDeliveryIntegrationTest {
|
||||
|
||||
@Inject
|
||||
MutableClock clock;
|
||||
|
||||
private static final String EB_CT = "application/x-amz-json-1.1";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void oauthConnectionFetchesTokenAndMergesBodyParameters() throws Exception {
|
||||
CountDownLatch delivered = new CountDownLatch(1);
|
||||
AtomicReference<String> tokenAuthorization = new AtomicReference<>();
|
||||
AtomicReference<String> tokenBody = new AtomicReference<>();
|
||||
AtomicReference<String> hookAuthorization = new AtomicReference<>();
|
||||
AtomicReference<String> hookBody = new AtomicReference<>();
|
||||
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/token", exchange -> {
|
||||
tokenAuthorization.set(exchange.getRequestHeaders().getFirst("Authorization"));
|
||||
tokenBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
|
||||
reply(exchange, "{\"access_token\":\"tok-123\",\"token_type\":\"Bearer\"}");
|
||||
});
|
||||
server.createContext("/hook", exchange -> {
|
||||
try {
|
||||
hookAuthorization.set(exchange.getRequestHeaders().getFirst("Authorization"));
|
||||
hookBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
|
||||
reply(exchange, "{}");
|
||||
} finally {
|
||||
delivered.countDown();
|
||||
}
|
||||
});
|
||||
server.start();
|
||||
|
||||
try {
|
||||
int port = server.getAddress().getPort();
|
||||
String connectionArn = createConnection("oauth-conn", String.format("""
|
||||
{
|
||||
"OAuthParameters": {
|
||||
"AuthorizationEndpoint": "http://127.0.0.1:%d/token",
|
||||
"HttpMethod": "POST",
|
||||
"ClientParameters": {"ClientID": "cid", "ClientSecret": "csecret"}
|
||||
},
|
||||
"InvocationHttpParameters": {
|
||||
"BodyParameters": [{"Key": "tenant", "Value": "alpha", "IsValueSecret": false}]
|
||||
}
|
||||
}
|
||||
""", port), "OAUTH_CLIENT_CREDENTIALS");
|
||||
String destinationArn = createDestination("oauth-dest", connectionArn,
|
||||
"http://127.0.0.1:" + port + "/hook");
|
||||
routeEventsTo("oauth-rule", "oauth.test", destinationArn);
|
||||
|
||||
putEvent("oauth.test");
|
||||
|
||||
assertTrue(delivered.await(5, TimeUnit.SECONDS), "webhook should receive the delivery");
|
||||
assertEquals("Basic Y2lkOmNzZWNyZXQ=", tokenAuthorization.get());
|
||||
assertTrue(tokenBody.get().contains("grant_type=client_credentials"), tokenBody.get());
|
||||
assertEquals("Bearer tok-123", hookAuthorization.get());
|
||||
assertTrue(hookBody.get().contains("\"tenant\":\"alpha\""), hookBody.get());
|
||||
assertTrue(hookBody.get().contains("\"source\":\"oauth.test\""), hookBody.get());
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deliveryIsDroppedWhenOauthTokenRequestFails() throws Exception {
|
||||
CountDownLatch delivered = new CountDownLatch(1);
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/token", exchange -> {
|
||||
exchange.sendResponseHeaders(401, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.createContext("/hook", exchange -> {
|
||||
delivered.countDown();
|
||||
reply(exchange, "{}");
|
||||
});
|
||||
server.start();
|
||||
|
||||
try {
|
||||
int port = server.getAddress().getPort();
|
||||
String connectionArn = createConnection("oauth-fail-conn", String.format("""
|
||||
{
|
||||
"OAuthParameters": {
|
||||
"AuthorizationEndpoint": "http://127.0.0.1:%d/token",
|
||||
"HttpMethod": "POST",
|
||||
"ClientParameters": {"ClientID": "cid", "ClientSecret": "wrong"}
|
||||
}
|
||||
}
|
||||
""", port), "OAUTH_CLIENT_CREDENTIALS");
|
||||
String destinationArn = createDestination("oauth-fail-dest", connectionArn,
|
||||
"http://127.0.0.1:" + port + "/hook");
|
||||
routeEventsTo("oauth-fail-rule", "oauth.fail", destinationArn);
|
||||
|
||||
putEvent("oauth.fail");
|
||||
|
||||
assertFalse(delivered.await(2, TimeUnit.SECONDS),
|
||||
"an event must not be sent unauthenticated when the token request fails");
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTargetCannotOverrideTheConnectionCredentials() throws Exception {
|
||||
CountDownLatch delivered = new CountDownLatch(1);
|
||||
AtomicReference<List<String>> apiKeyValues = new AtomicReference<>();
|
||||
AtomicReference<List<String>> tenantValues = new AtomicReference<>();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/hook", exchange -> {
|
||||
apiKeyValues.set(exchange.getRequestHeaders().get("X-Api-Key"));
|
||||
tenantValues.set(exchange.getRequestHeaders().get("x-tenant"));
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
reply(exchange, "{}");
|
||||
delivered.countDown();
|
||||
});
|
||||
server.start();
|
||||
|
||||
try {
|
||||
String connectionArn = createConnection("override-conn", """
|
||||
{"ApiKeyAuthParameters": {"ApiKeyName": "X-Api-Key", "ApiKeyValue": "from-connection"}}
|
||||
""", "API_KEY");
|
||||
String destinationArn = createDestination("override-dest", connectionArn,
|
||||
"http://127.0.0.1:" + server.getAddress().getPort() + "/hook");
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutRule")
|
||||
.body("{\"Name\": \"override-rule\", \"EventPattern\": \"{\\\"source\\\":[\\\"override.test\\\"]}\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.body(String.format("""
|
||||
{"Rule": "override-rule", "Targets": [{"Id": "t1", "Arn": "%s",
|
||||
"HttpParameters": {"HeaderParameters": {"x-api-key": "from-target", "x-tenant": "alpha"}}}]}
|
||||
""", destinationArn))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
putEvent("override.test");
|
||||
|
||||
assertTrue(delivered.await(5, TimeUnit.SECONDS), "webhook should receive the delivery");
|
||||
assertEquals(List.of("from-connection"), apiKeyValues.get());
|
||||
assertEquals(List.of("alpha"), tenantValues.get());
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerErrorIsRetriedUntilTheEndpointSucceeds() throws Exception {
|
||||
CountDownLatch delivered = new CountDownLatch(1);
|
||||
AtomicInteger requests = new AtomicInteger();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/hook", exchange -> {
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
if (requests.incrementAndGet() == 1) {
|
||||
exchange.sendResponseHeaders(500, -1);
|
||||
exchange.close();
|
||||
return;
|
||||
}
|
||||
reply(exchange, "{}");
|
||||
delivered.countDown();
|
||||
});
|
||||
server.start();
|
||||
|
||||
try {
|
||||
String connectionArn = createConnection("retry-conn", """
|
||||
{"ApiKeyAuthParameters": {"ApiKeyName": "k", "ApiKeyValue": "v"}}
|
||||
""", "API_KEY");
|
||||
String destinationArn = createDestination("retry-dest", connectionArn,
|
||||
"http://127.0.0.1:" + server.getAddress().getPort() + "/hook");
|
||||
routeEventsTo("retry-rule", "retry.test", destinationArn);
|
||||
|
||||
putEvent("retry.test");
|
||||
|
||||
assertTrue(awaitAdvancingClock(delivered), "the failed delivery should be retried");
|
||||
assertEquals(2, requests.get());
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDestinationOverItsRateLimitIsThrottledAndRetriedLater() throws Exception {
|
||||
CountDownLatch delivered = new CountDownLatch(2);
|
||||
List<Long> secondsOfDelivery = new CopyOnWriteArrayList<>();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/hook", exchange -> {
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
secondsOfDelivery.add(Instant.now().getEpochSecond());
|
||||
reply(exchange, "{}");
|
||||
delivered.countDown();
|
||||
});
|
||||
server.start();
|
||||
|
||||
try {
|
||||
String connectionArn = createConnection("rate-conn", """
|
||||
{"ApiKeyAuthParameters": {"ApiKeyName": "k", "ApiKeyValue": "v"}}
|
||||
""", "API_KEY");
|
||||
String destinationArn = given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.CreateApiDestination")
|
||||
.body(String.format("""
|
||||
{"Name": "rate-dest", "ConnectionArn": "%s", "HttpMethod": "POST",
|
||||
"InvocationRateLimitPerSecond": 1, "InvocationEndpoint": "http://127.0.0.1:%d/hook"}
|
||||
""", connectionArn, server.getAddress().getPort()))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("ApiDestinationArn");
|
||||
routeEventsTo("rate-rule", "rate.test", destinationArn);
|
||||
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutEvents")
|
||||
.body("""
|
||||
{"Entries": [
|
||||
{"Source": "rate.test", "DetailType": "Test", "Detail": "{}"},
|
||||
{"Source": "rate.test", "DetailType": "Test", "Detail": "{}"}
|
||||
]}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
assertTrue(awaitAdvancingClock(delivered), "both events should be delivered eventually");
|
||||
assertEquals(2, secondsOfDelivery.size());
|
||||
assertNotEquals(secondsOfDelivery.get(0), secondsOfDelivery.get(1),
|
||||
"a limit of one request per second must spread the deliveries over different seconds");
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createApiDestinationRejectsNonHttpEndpoint() {
|
||||
String connectionArn = createConnection("scheme-conn", """
|
||||
{"ApiKeyAuthParameters": {"ApiKeyName": "k", "ApiKeyValue": "v"}}
|
||||
""", "API_KEY");
|
||||
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.CreateApiDestination")
|
||||
.body(String.format("""
|
||||
{
|
||||
"Name": "scheme-dest",
|
||||
"ConnectionArn": "%s",
|
||||
"InvocationEndpoint": "file:///etc/passwd",
|
||||
"HttpMethod": "POST"
|
||||
}
|
||||
""", connectionArn))
|
||||
.when().post("/")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listApiDestinationsPaginatesWithLimitAndNextToken() {
|
||||
String connectionArn = createConnection("page-conn", """
|
||||
{"ApiKeyAuthParameters": {"ApiKeyName": "k", "ApiKeyValue": "v"}}
|
||||
""", "API_KEY");
|
||||
for (String name : new String[] {"page-c", "page-a", "page-b"}) {
|
||||
createDestination(name, connectionArn, "https://api.example.com/hook");
|
||||
}
|
||||
|
||||
String token = given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.ListApiDestinations")
|
||||
.body("{\"NamePrefix\": \"page-\", \"Limit\": 2}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("ApiDestinations.size()", equalTo(2))
|
||||
.body("ApiDestinations[0].Name", equalTo("page-a"))
|
||||
.body("ApiDestinations[1].Name", equalTo("page-b"))
|
||||
.body("NextToken", equalTo("page-b"))
|
||||
.extract().jsonPath().getString("NextToken");
|
||||
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.ListApiDestinations")
|
||||
.body(String.format("{\"NamePrefix\": \"page-\", \"Limit\": 2, \"NextToken\": \"%s\"}", token))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("ApiDestinations.size()", equalTo(1))
|
||||
.body("ApiDestinations[0].Name", equalTo("page-c"))
|
||||
.body("NextToken", nullValue());
|
||||
}
|
||||
|
||||
// The test profile freezes the clock, so TargetDispatcher's retry backoff only elapses when the test advances it
|
||||
private boolean awaitAdvancingClock(CountDownLatch latch) throws InterruptedException {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15);
|
||||
while (System.nanoTime() < deadline) {
|
||||
if (latch.await(200, TimeUnit.MILLISECONDS)) {
|
||||
return true;
|
||||
}
|
||||
clock.advance(Duration.ofSeconds(5));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void reply(HttpExchange exchange, String body) throws IOException {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, bytes.length);
|
||||
try (OutputStream os = exchange.getResponseBody()) {
|
||||
os.write(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private static String createConnection(String name, String authParameters, String authorizationType) {
|
||||
return given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.CreateConnection")
|
||||
.body(String.format("""
|
||||
{"Name": "%s", "AuthorizationType": "%s", "AuthParameters": %s}
|
||||
""", name, authorizationType, authParameters))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("ConnectionArn");
|
||||
}
|
||||
|
||||
private static String createDestination(String name, String connectionArn, String endpoint) {
|
||||
return given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.CreateApiDestination")
|
||||
.body(String.format("""
|
||||
{"Name": "%s", "ConnectionArn": "%s", "InvocationEndpoint": "%s", "HttpMethod": "POST"}
|
||||
""", name, connectionArn, endpoint))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("ApiDestinationArn");
|
||||
}
|
||||
|
||||
private static void routeEventsTo(String rule, String source, String destinationArn) {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutRule")
|
||||
.body(String.format("{\"Name\": \"%s\", \"EventPattern\": \"{\\\"source\\\":[\\\"%s\\\"]}\"}",
|
||||
rule, source))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.body(String.format("{\"Rule\": \"%s\", \"Targets\": [{\"Id\": \"t1\", \"Arn\": \"%s\"}]}",
|
||||
rule, destinationArn))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void putEvent(String source) {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutEvents")
|
||||
.body(String.format("""
|
||||
{"Entries": [{"Source": "%s", "DetailType": "Test", "Detail": "{\\"k\\":\\"v\\"}"}]}
|
||||
""", source))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
}
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class EventBridgeApiDestinationIntegrationTest {
|
||||
|
||||
private static final String EB_CT = "application/x-amz-json-1.1";
|
||||
|
||||
private static String connectionArn;
|
||||
private static String apiDestinationArn;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void setupConnection() {
|
||||
connectionArn = given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.CreateConnection")
|
||||
.body("""
|
||||
{
|
||||
"Name": "apidest-conn",
|
||||
"Description": "Connection for ApiDestination test",
|
||||
"AuthorizationType": "API_KEY",
|
||||
"AuthParameters": {
|
||||
"ApiKeyAuthParameters": {
|
||||
"ApiKeyName": "x-api-key",
|
||||
"ApiKeyValue": "test-key"
|
||||
}
|
||||
}
|
||||
}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("ConnectionArn");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void createApiDestination() {
|
||||
apiDestinationArn = given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.CreateApiDestination")
|
||||
.body(String.format("""
|
||||
{
|
||||
"Name": "my-test-api-dest",
|
||||
"Description": "Test Api Destination",
|
||||
"ConnectionArn": "%s",
|
||||
"InvocationEndpoint": "https://api.example.com/webhook",
|
||||
"HttpMethod": "POST",
|
||||
"InvocationRateLimitPerSecond": 10
|
||||
}
|
||||
""", connectionArn))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("ApiDestinationArn", startsWith("arn:aws:events:us-east-1:000000000000:api-destination/my-test-api-dest/"))
|
||||
.body("ApiDestinationState", equalTo("ACTIVE"))
|
||||
.body("CreationTime", notNullValue())
|
||||
.body("LastModifiedTime", notNullValue())
|
||||
.extract().jsonPath().getString("ApiDestinationArn");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void createDuplicateApiDestinationFails() {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.CreateApiDestination")
|
||||
.body(String.format("""
|
||||
{
|
||||
"Name": "my-test-api-dest",
|
||||
"ConnectionArn": "%s",
|
||||
"InvocationEndpoint": "https://api.example.com/webhook",
|
||||
"HttpMethod": "POST"
|
||||
}
|
||||
""", connectionArn))
|
||||
.when().post("/")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ResourceAlreadyExistsException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void describeApiDestination() {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.DescribeApiDestination")
|
||||
.body("""
|
||||
{
|
||||
"Name": "my-test-api-dest"
|
||||
}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("ApiDestinationArn", equalTo(apiDestinationArn))
|
||||
.body("Name", equalTo("my-test-api-dest"))
|
||||
.body("Description", equalTo("Test Api Destination"))
|
||||
.body("ConnectionArn", equalTo(connectionArn))
|
||||
.body("InvocationEndpoint", equalTo("https://api.example.com/webhook"))
|
||||
.body("HttpMethod", equalTo("POST"))
|
||||
.body("InvocationRateLimitPerSecond", equalTo(10))
|
||||
.body("ApiDestinationState", equalTo("ACTIVE"))
|
||||
.body("CreationTime", notNullValue())
|
||||
.body("LastModifiedTime", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void updateApiDestination() {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.UpdateApiDestination")
|
||||
.body("""
|
||||
{
|
||||
"Name": "my-test-api-dest",
|
||||
"Description": "Updated description",
|
||||
"InvocationEndpoint": "https://api.example.com/v2/webhook",
|
||||
"HttpMethod": "PUT",
|
||||
"InvocationRateLimitPerSecond": 25
|
||||
}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("ApiDestinationArn", equalTo(apiDestinationArn))
|
||||
.body("ApiDestinationState", equalTo("ACTIVE"))
|
||||
.body("CreationTime", notNullValue())
|
||||
.body("LastModifiedTime", notNullValue());
|
||||
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.DescribeApiDestination")
|
||||
.body("""
|
||||
{
|
||||
"Name": "my-test-api-dest"
|
||||
}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("Description", equalTo("Updated description"))
|
||||
.body("InvocationEndpoint", equalTo("https://api.example.com/v2/webhook"))
|
||||
.body("HttpMethod", equalTo("PUT"))
|
||||
.body("InvocationRateLimitPerSecond", equalTo(25));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void listApiDestinations() {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.ListApiDestinations")
|
||||
.body("""
|
||||
{
|
||||
"NamePrefix": "my-test"
|
||||
}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("ApiDestinations.size()", greaterThanOrEqualTo(1))
|
||||
.body("ApiDestinations[0].Name", equalTo("my-test-api-dest"))
|
||||
.body("ApiDestinations[0].ApiDestinationArn", equalTo(apiDestinationArn));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void deleteApiDestination() {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.DeleteApiDestination")
|
||||
.body("""
|
||||
{
|
||||
"Name": "my-test-api-dest"
|
||||
}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.DescribeApiDestination")
|
||||
.body("""
|
||||
{
|
||||
"Name": "my-test-api-dest"
|
||||
}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void eventDeliveryToApiDestination() throws Exception {
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
AtomicReference<String> receivedUri = new AtomicReference<>();
|
||||
AtomicReference<String> receivedBody = new AtomicReference<>();
|
||||
AtomicReference<String> receivedApiKey = new AtomicReference<>();
|
||||
AtomicReference<String> receivedConnHeader = new AtomicReference<>();
|
||||
AtomicReference<String> receivedTargetHeader = new AtomicReference<>();
|
||||
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/webhook", exchange -> {
|
||||
try {
|
||||
receivedUri.set(exchange.getRequestURI().toString());
|
||||
receivedApiKey.set(exchange.getRequestHeaders().getFirst("x-api-key"));
|
||||
receivedConnHeader.set(exchange.getRequestHeaders().getFirst("x-conn-hdr"));
|
||||
receivedTargetHeader.set(exchange.getRequestHeaders().getFirst("x-target-hdr"));
|
||||
receivedBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
|
||||
byte[] response = "{\"status\":\"ok\"}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, response.length);
|
||||
try (OutputStream os = exchange.getResponseBody()) {
|
||||
os.write(response);
|
||||
}
|
||||
} finally {
|
||||
latch.countDown();
|
||||
}
|
||||
});
|
||||
server.start();
|
||||
|
||||
try {
|
||||
int port = server.getAddress().getPort();
|
||||
|
||||
// 1. Create connection with API Key and InvocationHttpParameters
|
||||
String connArn = given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.CreateConnection")
|
||||
.body("""
|
||||
{
|
||||
"Name": "delivery-conn",
|
||||
"AuthorizationType": "API_KEY",
|
||||
"AuthParameters": {
|
||||
"ApiKeyAuthParameters": {
|
||||
"ApiKeyName": "x-api-key",
|
||||
"ApiKeyValue": "my-secret-key"
|
||||
},
|
||||
"InvocationHttpParameters": {
|
||||
"HeaderParameters": [
|
||||
{"Key": "x-conn-hdr", "Value": "conn-val", "IsValueSecret": false}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("ConnectionArn");
|
||||
|
||||
// 2. Create ApiDestination pointing to local server with wildcard path
|
||||
String destArn = given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.CreateApiDestination")
|
||||
.body(String.format("""
|
||||
{
|
||||
"Name": "delivery-dest",
|
||||
"ConnectionArn": "%s",
|
||||
"InvocationEndpoint": "http://127.0.0.1:%d/webhook/*",
|
||||
"HttpMethod": "POST"
|
||||
}
|
||||
""", connArn, port))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("ApiDestinationArn");
|
||||
|
||||
// 3. Put Rule
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutRule")
|
||||
.body("""
|
||||
{
|
||||
"Name": "delivery-rule",
|
||||
"EventPattern": "{\\"source\\":[\\"delivery.test\\"]}"
|
||||
}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
// 4. Put Target with HttpParameters
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.body(String.format("""
|
||||
{
|
||||
"Rule": "delivery-rule",
|
||||
"Targets": [
|
||||
{
|
||||
"Id": "target-dest",
|
||||
"Arn": "%s",
|
||||
"HttpParameters": {
|
||||
"PathParameterValues": ["user-123"],
|
||||
"HeaderParameters": {
|
||||
"x-target-hdr": "target-val"
|
||||
},
|
||||
"QueryStringParameters": {
|
||||
"tenant": "alpha"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
""", destArn))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
// 5. Put Event
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutEvents")
|
||||
.body("""
|
||||
{
|
||||
"Entries": [
|
||||
{
|
||||
"Source": "delivery.test",
|
||||
"DetailType": "OrderCreated",
|
||||
"Detail": "{\\"orderId\\":\\"12345\\"}"
|
||||
}
|
||||
]
|
||||
}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
boolean received = latch.await(5, TimeUnit.SECONDS);
|
||||
assertTrue(received, "HTTP server should receive request from EventBridge delivery");
|
||||
assertEquals("/webhook/user-123?tenant=alpha", receivedUri.get());
|
||||
assertEquals("my-secret-key", receivedApiKey.get());
|
||||
assertEquals("conn-val", receivedConnHeader.get());
|
||||
assertEquals("target-val", receivedTargetHeader.get());
|
||||
assertTrue(receivedBody.get().contains("\"orderId\":\"12345\""));
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.ApiDestination;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
class EventBridgeInvokerApiDestinationTest {
|
||||
|
||||
@Test
|
||||
void substitutePathParameters_replacesWildcardsInOrder() {
|
||||
assertEquals("https://api.example.com/a/one/b/two",
|
||||
EventBridgeInvoker.substitutePathParameters(
|
||||
"https://api.example.com/a/*/b/*", List.of("one", "two")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void substitutePathParameters_encodesValuesAsSingleSegment() {
|
||||
assertEquals("https://api.example.com/x/a%2Fb%3Fc%23d%40e%20f",
|
||||
EventBridgeInvoker.substitutePathParameters(
|
||||
"https://api.example.com/x/*", List.of("a/b?c#d@e f")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void substitutePathParameters_neverTouchesHostOrQuery() {
|
||||
assertEquals("https://*.example.com/p/v?q=*",
|
||||
EventBridgeInvoker.substitutePathParameters(
|
||||
"https://*.example.com/p/*?q=*", List.of("v", "ignored")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void substitutePathParameters_withoutPathLeavesUrlUntouched() {
|
||||
assertEquals("https://*.example.com",
|
||||
EventBridgeInvoker.substitutePathParameters("https://*.example.com", List.of("v")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void substitutePathParameters_keepsExtraWildcardsWhenValuesRunOut() {
|
||||
assertEquals("https://api.example.com/one/*",
|
||||
EventBridgeInvoker.substitutePathParameters("https://api.example.com/*/*", List.of("one")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendQueryParameters_encodesAndJoinsExistingQuery() {
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
params.put("a b", "c&d");
|
||||
assertEquals("https://x.test/p?k=v&a+b=c%26d",
|
||||
EventBridgeInvoker.appendQueryParameters("https://x.test/p?k=v", params));
|
||||
assertEquals("https://x.test/p?a+b=c%26d",
|
||||
EventBridgeInvoker.appendQueryParameters("https://x.test/p", params));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendQueryParameters_insertsTheQueryBeforeAFragment() {
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
params.put("a", "b");
|
||||
assertEquals("https://x.test/p?a=b#frag",
|
||||
EventBridgeInvoker.appendQueryParameters("https://x.test/p#frag", params));
|
||||
assertEquals("https://x.test/p?k=v&a=b#frag?x",
|
||||
EventBridgeInvoker.appendQueryParameters("https://x.test/p?k=v#frag?x", params));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendQueryParameters_withoutParamsReturnsUrl() {
|
||||
assertEquals("https://x.test/p", EventBridgeInvoker.appendQueryParameters("https://x.test/p", Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void acquireRatePermit_neverGrantsMoreThanTheLimitToConcurrentDeliveries() throws Exception {
|
||||
EventBridgeInvoker invoker = new EventBridgeInvoker(mock(LambdaService.class), mock(SqsService.class),
|
||||
mock(SnsService.class), new ObjectMapper(), mock(EmulatorConfig.class));
|
||||
// More than the sweep threshold, so the sweep runs while the deliveries below are counting
|
||||
for (int i = 0; i < 300; i++) {
|
||||
invoker.acquireRatePermit(rateLimited("filler-" + i, 1));
|
||||
}
|
||||
ApiDestination destination = rateLimited("busy", 5);
|
||||
|
||||
int threads = 64;
|
||||
ExecutorService pool = Executors.newFixedThreadPool(threads);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
AtomicInteger granted = new AtomicInteger();
|
||||
List<Future<?>> workers = new ArrayList<>();
|
||||
try {
|
||||
for (int i = 0; i < threads; i++) {
|
||||
workers.add(pool.submit(() -> {
|
||||
start.await();
|
||||
try {
|
||||
invoker.acquireRatePermit(destination);
|
||||
granted.incrementAndGet();
|
||||
} catch (AwsException throttled) {
|
||||
assertEquals("ThrottlingException", throttled.getErrorCode());
|
||||
}
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
start.countDown();
|
||||
// get() rethrows a worker's failure, which awaiting the pool alone would not surface
|
||||
for (Future<?> worker : workers) {
|
||||
worker.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
|
||||
// Two permits' worth of slack covers the one-second window rolling over mid-test
|
||||
assertTrue(granted.get() >= 5 && granted.get() <= 10, "granted " + granted.get());
|
||||
}
|
||||
|
||||
private static ApiDestination rateLimited(String name, int limit) {
|
||||
return new ApiDestination(name, "arn:aws:events:us-east-1:000000000000:api-destination/" + name + "/1",
|
||||
"arn:aws:events:us-east-1:000000000000:connection/c/1", "https://api.example.com", "POST",
|
||||
limit, null);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -50,7 +50,7 @@ class EventBridgeSchedulerIntegrationTest {
|
||||
eventBridgeService = new EventBridgeService(
|
||||
busStore, ruleStore, targetStore,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, ACCOUNT),
|
||||
new ObjectMapper(), scheduler, dispatcher, replayDispatcher,
|
||||
new ResourceGroupsTaggingService(null));
|
||||
|
||||
+189
@@ -7,7 +7,10 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.ApiDestination;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.ApiDestinationState;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Archive;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Connection;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Replay;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.ReplayState;
|
||||
@@ -60,6 +63,7 @@ class EventBridgeServiceTest {
|
||||
new InMemoryStorage<>(),
|
||||
replayStore,
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
new ObjectMapper(),
|
||||
null,
|
||||
@@ -1171,4 +1175,189 @@ class EventBridgeServiceTest {
|
||||
assertEquals(REGION, envelope.path("region").asText());
|
||||
assertEquals("000000000000", envelope.path("account").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAndDescribeApiDestination() {
|
||||
Connection conn = service.createConnection("my-conn", "test conn", "API_KEY",
|
||||
"{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"x-api-key\",\"ApiKeyValue\":\"secret\"}}",
|
||||
null, null, REGION);
|
||||
|
||||
ApiDestination dest = service.createApiDestination(
|
||||
"my-dest", "description", conn.getConnectionArn(),
|
||||
"https://api.example.com/events", "POST", 10, REGION);
|
||||
|
||||
assertNotNull(dest.getArn());
|
||||
assertEquals("my-dest", dest.getName());
|
||||
assertEquals("description", dest.getDescription());
|
||||
assertEquals(conn.getConnectionArn(), dest.getConnectionArn());
|
||||
assertEquals("https://api.example.com/events", dest.getInvocationEndpoint());
|
||||
assertEquals("POST", dest.getHttpMethod());
|
||||
assertEquals(10, dest.getInvocationRateLimitPerSecond());
|
||||
assertEquals(ApiDestinationState.ACTIVE, dest.getApiDestinationState());
|
||||
|
||||
ApiDestination described = service.describeApiDestination("my-dest", REGION);
|
||||
assertEquals(dest.getArn(), described.getArn());
|
||||
assertEquals("my-dest", described.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createApiDestination_validations() {
|
||||
Connection conn = service.createConnection("conn-val", null, "API_KEY",
|
||||
"{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"x-key\",\"ApiKeyValue\":\"val\"}}",
|
||||
null, null, REGION);
|
||||
|
||||
// Name missing
|
||||
assertThrows(AwsException.class, () -> service.createApiDestination(
|
||||
null, "desc", conn.getConnectionArn(), "https://api.com", "POST", 5, REGION));
|
||||
|
||||
// Invalid method
|
||||
assertThrows(AwsException.class, () -> service.createApiDestination(
|
||||
"dest-1", "desc", conn.getConnectionArn(), "https://api.com", "INVALID_METHOD", 5, REGION));
|
||||
|
||||
// Non-existent connection
|
||||
assertThrows(AwsException.class, () -> service.createApiDestination(
|
||||
"dest-2", "desc", "arn:aws:events:us-east-1:000000000000:connection/unknown/123",
|
||||
"https://api.com", "POST", 5, REGION));
|
||||
|
||||
// Duplicate name
|
||||
service.createApiDestination("dup-dest", "desc", conn.getConnectionArn(), "https://api.com", "POST", 5, REGION);
|
||||
assertThrows(AwsException.class, () -> service.createApiDestination(
|
||||
"dup-dest", "desc2", conn.getConnectionArn(), "https://api.com", "GET", 5, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createApiDestination_rejectsNonHttpEndpoint() {
|
||||
Connection conn = service.createConnection("conn-endpoint", null, "API_KEY",
|
||||
"{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"x-key\",\"ApiKeyValue\":\"val\"}}",
|
||||
null, null, REGION);
|
||||
|
||||
for (String endpoint : List.of("ftp://example.com/x", "file:///etc/passwd", "https:///no-host",
|
||||
"https://:8080/path", "https://*.example.com/hook", "not a url")) {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> service.createApiDestination(
|
||||
"bad-endpoint", null, conn.getConnectionArn(), endpoint, "POST", null, REGION));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
}
|
||||
assertThrows(AwsException.class, () -> service.describeApiDestination("bad-endpoint", REGION));
|
||||
|
||||
ApiDestination wildcardPath = service.createApiDestination("wildcard-path", null, conn.getConnectionArn(),
|
||||
"https://api.example.com/hook/*", "POST", null, REGION);
|
||||
assertEquals("https://api.example.com/hook/*", wildcardPath.getInvocationEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateApiDestination_leavesDestinationUntouchedWhenAnyFieldIsInvalid() {
|
||||
Connection conn = service.createConnection("conn-atomic", null, "API_KEY",
|
||||
"{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"x-key\",\"ApiKeyValue\":\"val\"}}",
|
||||
null, null, REGION);
|
||||
service.createApiDestination("atomic-upd", "original", conn.getConnectionArn(),
|
||||
"https://api.com/v1", "POST", null, REGION);
|
||||
|
||||
assertThrows(AwsException.class, () -> service.updateApiDestination(
|
||||
"atomic-upd", "changed", null, null, "INVALID_METHOD", null, REGION));
|
||||
|
||||
ApiDestination described = service.describeApiDestination("atomic-upd", REGION);
|
||||
assertEquals("original", described.getDescription());
|
||||
assertEquals("POST", described.getHttpMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateApiDestination_rejectsNonHttpEndpoint() {
|
||||
Connection conn = service.createConnection("conn-endpoint-upd", null, "API_KEY",
|
||||
"{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"x-key\",\"ApiKeyValue\":\"val\"}}",
|
||||
null, null, REGION);
|
||||
service.createApiDestination("endpoint-upd", null, conn.getConnectionArn(),
|
||||
"https://api.com/v1", "POST", null, REGION);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> service.updateApiDestination(
|
||||
"endpoint-upd", null, null, "file:///etc/passwd", null, null, REGION));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("https://api.com/v1",
|
||||
service.describeApiDestination("endpoint-upd", REGION).getInvocationEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findApiDestinationByArn_ignoresAnArnFromBeforeTheDestinationWasRecreated() {
|
||||
Connection conn = service.createConnection("conn-recreate", null, "API_KEY",
|
||||
"{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"x-key\",\"ApiKeyValue\":\"val\"}}",
|
||||
null, null, REGION);
|
||||
ApiDestination first = service.createApiDestination("recreated", null, conn.getConnectionArn(),
|
||||
"https://api.com/v1", "POST", null, REGION);
|
||||
service.deleteApiDestination("recreated", REGION);
|
||||
ApiDestination second = service.createApiDestination("recreated", null, conn.getConnectionArn(),
|
||||
"https://api.com/v2", "POST", null, REGION);
|
||||
|
||||
assertNull(service.findApiDestinationByArn(first.getArn(), REGION));
|
||||
assertEquals("https://api.com/v2",
|
||||
service.findApiDestinationByArn(second.getArn(), REGION).getInvocationEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreApiDestination_putsBackUnsetFieldsToo() {
|
||||
Connection conn = service.createConnection("conn-restore", null, "API_KEY",
|
||||
"{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"x-key\",\"ApiKeyValue\":\"val\"}}",
|
||||
null, null, REGION);
|
||||
service.createApiDestination("restored", "changed", conn.getConnectionArn(),
|
||||
"https://api.com/v2", "PUT", 5, REGION);
|
||||
|
||||
service.restoreApiDestination("restored", null, conn.getConnectionArn(),
|
||||
"https://api.com/v1", "POST", null, REGION);
|
||||
|
||||
ApiDestination restored = service.describeApiDestination("restored", REGION);
|
||||
assertNull(restored.getDescription());
|
||||
assertNull(restored.getInvocationRateLimitPerSecond());
|
||||
assertEquals("https://api.com/v1", restored.getInvocationEndpoint());
|
||||
assertEquals("POST", restored.getHttpMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listApiDestinations_isSortedByName() {
|
||||
Connection conn = service.createConnection("conn-sorted", null, "API_KEY",
|
||||
"{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"x-key\",\"ApiKeyValue\":\"val\"}}",
|
||||
null, null, REGION);
|
||||
for (String name : List.of("sorted-c", "sorted-a", "sorted-b")) {
|
||||
service.createApiDestination(name, null, conn.getConnectionArn(), "https://api.com", "GET", null, REGION);
|
||||
}
|
||||
|
||||
List<String> names = service.listApiDestinations("sorted-", null, REGION).stream()
|
||||
.map(ApiDestination::getName).toList();
|
||||
assertEquals(List.of("sorted-a", "sorted-b", "sorted-c"), names);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateAndDeleteApiDestination() {
|
||||
Connection conn1 = service.createConnection("conn-upd1", null, "API_KEY",
|
||||
"{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"k\",\"ApiKeyValue\":\"v\"}}", null, null, REGION);
|
||||
Connection conn2 = service.createConnection("conn-upd2", null, "API_KEY",
|
||||
"{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"k\",\"ApiKeyValue\":\"v\"}}", null, null, REGION);
|
||||
|
||||
service.createApiDestination("upd-dest", "initial", conn1.getConnectionArn(), "https://api.com/v1", "POST", 5, REGION);
|
||||
|
||||
ApiDestination updated = service.updateApiDestination("upd-dest", "updated desc", conn2.getConnectionArn(),
|
||||
"https://api.com/v2", "PUT", 20, REGION);
|
||||
|
||||
assertEquals("updated desc", updated.getDescription());
|
||||
assertEquals(conn2.getConnectionArn(), updated.getConnectionArn());
|
||||
assertEquals("https://api.com/v2", updated.getInvocationEndpoint());
|
||||
assertEquals("PUT", updated.getHttpMethod());
|
||||
assertEquals(20, updated.getInvocationRateLimitPerSecond());
|
||||
|
||||
service.deleteApiDestination("upd-dest", REGION);
|
||||
assertThrows(AwsException.class, () -> service.describeApiDestination("upd-dest", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listApiDestinations() {
|
||||
Connection conn = service.createConnection("conn-list", null, "API_KEY",
|
||||
"{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"k\",\"ApiKeyValue\":\"v\"}}", null, null, REGION);
|
||||
|
||||
service.createApiDestination("prefix-dest-1", null, conn.getConnectionArn(), "https://api.com", "GET", null, REGION);
|
||||
service.createApiDestination("prefix-dest-2", null, conn.getConnectionArn(), "https://api.com", "GET", null, REGION);
|
||||
service.createApiDestination("other-dest", null, conn.getConnectionArn(), "https://api.com", "GET", null, REGION);
|
||||
|
||||
List<ApiDestination> all = service.listApiDestinations(null, null, REGION);
|
||||
assertTrue(all.size() >= 3);
|
||||
|
||||
List<ApiDestination> prefixed = service.listApiDestinations("prefix-", null, REGION);
|
||||
assertEquals(2, prefixed.size());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user