Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(eventbridge): add ApiDestination target support (#4702) (#5009)

Vũ Thế Huy108f2b54bf31
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 4768eceec6..4ea88af307 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -154,7 +154,7 @@ cross-resource references.
| Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` |
| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolUser`, `UserPoolUserToGroupAttachment` |
| ACM | `Certificate` |
-| EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `Archive` (`KmsKeyIdentifier` is ignored) |
+| EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `ApiDestination`, `Archive` (`KmsKeyIdentifier` is ignored) |
| EventBridge Scheduler | `ScheduleGroup` |
| Transfer Family | `Server` (management plane only; Ref returns the server ARN; Arn, ServerId and State attributes supported; AS2 managed egress IPs are not modeled; Domain replacement and IdentityProviderType changes are not supported) |
| Backup | `BackupVault` |
diff --git a/docs/services/eventbridge.md b/docs/services/eventbridge.md
index 8249bfd8b6..79b53eed8a 100644
--- a/docs/services/eventbridge.md
+++ b/docs/services/eventbridge.md
@@ -39,6 +39,11 @@
| `UpdateConnection` | Update connection description, auth type, or auth parameters |
| `DeleteConnection` | Delete a connection |
| `ListConnections` | List connections, optionally filtered by name prefix or state |
+| `CreateApiDestination` | Create an HTTP or HTTPS API destination for EventBridge targets |
+| `DescribeApiDestination` | Get API destination details including endpoint, HTTP method, and rate limit |
+| `UpdateApiDestination` | Update API destination endpoint, HTTP method, connection, or rate limit |
+| `DeleteApiDestination` | Delete an API destination |
+| `ListApiDestinations` | List API destinations, optionally filtered by name prefix or connection ARN |
| `StartReplay` | - |
| `DescribeReplay` | - |
| `CancelReplay` | - |
@@ -139,6 +144,54 @@ The value must be between 1 and 1600 characters when supplied. Floci stores
the role as configuration; target delivery does not assume it or enforce its
IAM policies.
+## API Destination Targets
+
+A matching rule can send events directly to HTTP or HTTPS endpoints via API destinations. An API destination pairs an HTTP endpoint URL and HTTP method with an EventBridge Connection for authentication (API key, basic auth, or OAuth client credentials).
+
+```bash
+# 1. Create a connection with API key auth
+aws events create-connection \
+ --name webhook-auth \
+ --authorization-type API_KEY \
+ --auth-parameters '{"ApiKeyAuthParameters":{"ApiKeyName":"x-api-key","ApiKeyValue":"secret123"}}' \
+ --endpoint-url $AWS_ENDPOINT_URL
+
+# 2. Create an API destination
+aws events create-api-destination \
+ --name webhook-dest \
+ --connection-arn "arn:aws:events:us-east-1:000000000000:connection/webhook-auth" \
+ --invocation-endpoint "https://api.example.com/events/*" \
+ --http-method POST \
+ --invocation-rate-limit-per-second 10 \
+ --endpoint-url $AWS_ENDPOINT_URL
+
+# 3. Add the API destination as a target with path and query parameters
+aws events put-targets \
+ --rule order-placed-rule \
+ --event-bus-name my-bus \
+ --targets '[{
+ "Id": "post-to-webhook",
+ "Arn": "arn:aws:events:us-east-1:000000000000:api-destination/webhook-dest",
+ "HttpParameters": {
+ "PathParameterValues": ["orders"],
+ "QueryStringParameters": {"version": "v1"},
+ "HeaderParameters": {"X-Custom-Header": "eventbridge"}
+ }
+ }]' \
+ --endpoint-url $AWS_ENDPOINT_URL
+```
+
+- `InvocationEndpoint` must be an `http` or `https` URL.
+- Path parameter wildcards (`*`) in the path of `InvocationEndpoint` are substituted in order by `PathParameterValues`. Each value is percent-encoded as a single path segment, and a `*` in the host or query is never substituted.
+- Query string and header parameters from both the Connection and the Target are merged and forwarded on the outgoing HTTP request. Connection `BodyParameters` are merged into the event body when it is a JSON object.
+- `OAUTH_CLIENT_CREDENTIALS` connections run the RFC 6749 client-credentials exchange against `AuthorizationEndpoint` for each delivery: the client ID and secret go in a `Basic` `Authorization` header, the body is form-encoded `grant_type=client_credentials` plus any `BodyParameters`, and the returned `access_token` is sent as `Authorization: <token_type> <access_token>`. Tokens are not cached.
+- If the connection is missing, or its authorization cannot be obtained, the delivery is dropped instead of being sent unauthenticated.
+- Requests to link-local and AWS metadata endpoints (such as `169.254.0.0/16`) are blocked for SSRF protection, including for the OAuth endpoint. The host is resolved once for the check and again when the request is sent, so DNS rebinding is not fully prevented.
+- A delivery that fails with a connection error, HTTP 429 or HTTP 5xx is retried and dead-lettered like any other target (see Target Retry and Dead-Letter Queues). Any other failure is permanent and goes straight to the dead-letter queue: another non-2xx response, an invalid or blocked URL, a missing connection, or an OAuth token request that fails.
+- `InvocationRateLimitPerSecond` is enforced per destination with a one-second window. An event over the limit is treated as throttled and retried with backoff.
+- A destination or connection ARN taken before the resource was deleted and recreated under the same name no longer resolves.
+- `ListApiDestinations` supports `Limit` (1 to 100) and `NextToken`.
+
## Target Retry and Dead-Letter Queues
A target's `RetryPolicy` and `DeadLetterConfig` are validated by `PutTargets`, stored with the target, returned by `ListTargetsByRule`, and applied to delivery from `PutEvents` and scheduled rules.
diff --git a/docs/services/index.md b/docs/services/index.md
index 559a355ebc..30cde70ff3 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -22,7 +22,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 22 |
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 79 |
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane |
-| [IAM](iam.md) | `POST /` with `Action=` param | Query | 148 |
+| [IAM](iam.md) | `POST /` with `Action=` param | Query | 153 |
| [STS](sts.md) | `POST /` with `Action=` param | Query | 7 |
| [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 |
| [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 |
@@ -38,7 +38,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [SWF](swf.md) | `POST /` + `X-Amz-Target: SimpleWorkflowService.*` | JSON 1.0 | 39 |
| [CloudFormation](cloudformation.md) | `POST /` with `Action=` param | Query | 35 |
| [Cloud Control API](cloudcontrol.md) | `POST /` + `X-Amz-Target: CloudApiService.*` | JSON 1.1 | 5 |
-| [EventBridge](eventbridge.md) | `POST /` + `X-Amz-Target: AmazonEventBridge.*` | JSON 1.1 | 35 |
+| [EventBridge](eventbridge.md) | `POST /` + `X-Amz-Target: AmazonEventBridge.*` | JSON 1.1 | 40 |
| [EventBridge Scheduler](scheduler.md) | `/schedules/*`, `/schedule-groups/*`, `/tags/*` | REST JSON | 12 |
| [EventBridge Pipes](pipes.md) | `/v1/pipes/*` | REST JSON | 7 |
| [CloudWatch OAM](oam.md) | REST paths such as `POST /CreateSink` and `POST /CreateLink` | REST JSON | 15 |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
index a9389fda17..d0db3d3f7e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
@@ -86,6 +86,14 @@ public final class CfnRollback {
*/
public static final String ARCHIVE_UPDATE_SNAPSHOT_ATTR = "__FlociArchiveUpdateSnapshot";
+ /**
+ * Holds the connection, endpoint, method, description and rate limit an EventBridge API
+ * destination carried before an in-place update changed them, so a failed stack update can put
+ * them back. Written by {@code EventsCfnProvisioner} before its update call and spent by its
+ * {@code rollbackUpdate}.
+ */
+ public static final String API_DESTINATION_UPDATE_SNAPSHOT_ATTR = "__FlociApiDestinationUpdateSnapshot";
+
/**
* Holds the name, description and endpoint configuration a REST API had before an in-place
* update patched them, and whether the update also re-applied an OpenAPI document, so a failed
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java
index 63f3f76d46..fafe9e64bd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java
@@ -10,8 +10,10 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
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.BatchParameters;
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
+import io.github.hectorvent.floci.services.eventbridge.model.HttpParameters;
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
import io.github.hectorvent.floci.services.eventbridge.model.Rule;
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
@@ -68,7 +70,8 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
@Override
public Set<String> resourceTypes() {
- return Set.of("AWS::Events::Rule", "AWS::Events::EventBus", "AWS::Events::EventBusPolicy");
+ return Set.of("AWS::Events::Rule", "AWS::Events::EventBus", "AWS::Events::EventBusPolicy",
+ "AWS::Events::ApiDestination");
}
@Override
@@ -77,6 +80,7 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
case "AWS::Events::Rule" -> provisionRule(r, props, ctx);
case "AWS::Events::EventBus" -> provisionEventBus(r, props, ctx);
case "AWS::Events::EventBusPolicy" -> provisionEventBusPolicy(r, props, ctx);
+ case "AWS::Events::ApiDestination" -> provisionApiDestination(r, props, ctx);
default -> throw new IllegalStateException(
"EventsCfnProvisioner cannot handle " + r.getResourceType());
}
@@ -107,6 +111,7 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(physicalId, null, region);
case "AWS::Events::EventBus" -> deleteEventBusSafe(physicalId, region);
case "AWS::Events::EventBusPolicy" -> removeEventBusPolicySafe(physicalId, region);
+ case "AWS::Events::ApiDestination" -> deleteApiDestinationSafe(physicalId, region);
default -> {
// no other type reaches this provisioner
}
@@ -161,6 +166,10 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
if (targetId != null && targetArn != null) {
Target target = new Target(targetId, targetArn, input, inputPath);
target.setInputTransformer(InputTransformer.fromJson(resolved.path("InputTransformer")));
+ JsonNode httpParamsNode = resolved.path("HttpParameters");
+ if (httpParamsNode.isObject()) {
+ target.setHttpParameters(MAPPER.convertValue(httpParamsNode, HttpParameters.class));
+ }
JsonNode sqsParamsNode = resolved.path("SqsParameters");
if (!sqsParamsNode.isMissingNode() && sqsParamsNode.isObject()) {
String messageGroupId = sqsParamsNode.path("MessageGroupId").asText(null);
@@ -269,6 +278,9 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
+ if ("AWS::Events::ApiDestination".equals(resource.getResourceType())) {
+ return rollbackApiDestinationUpdate(resource);
+ }
String rawSnapshot = resource.getAttributes().get(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR);
if (rawSnapshot == null) {
return false;
@@ -731,6 +743,94 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
"ResourceNotFoundException");
}
+ private void provisionApiDestination(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String name = ctx.stablePhysicalName(
+ ctx.resolveOptional(props, "Name"), r.getLogicalId(), 64, false);
+ if (ctx.isUpdate() && ctx.priorPhysicalId() != null && !ctx.priorPhysicalId().equals(name)) {
+ throw new AwsException("ValidationError",
+ "Updating ApiDestination Name requires resource replacement, which is not supported.", 400);
+ }
+
+ String connectionArn = ctx.resolveOptional(props, "ConnectionArn");
+ String invocationEndpoint = ctx.resolveOptional(props, "InvocationEndpoint");
+ String httpMethod = ctx.resolveOptional(props, "HttpMethod");
+ String description = ctx.resolveOptional(props, "Description");
+ Integer rateLimit = null;
+ if (props != null && props.has("InvocationRateLimitPerSecond") && !props.get("InvocationRateLimitPerSecond").isNull()) {
+ rateLimit = props.get("InvocationRateLimitPerSecond").asInt();
+ }
+
+ // A snapshot describes the update in flight; one an earlier update left behind is stale
+ r.getAttributes().remove(CfnRollback.API_DESTINATION_UPDATE_SNAPSHOT_ATTR);
+ ApiDestination destination;
+ if (ctx.reusesPriorEntity(name)) {
+ snapshotApiDestinationBeforeUpdate(r, eventBridgeService.describeApiDestination(name, ctx.region()),
+ ctx.region());
+ destination = eventBridgeService.updateApiDestination(
+ name, description, connectionArn, invocationEndpoint, httpMethod, rateLimit, ctx.region());
+ } else {
+ destination = eventBridgeService.createApiDestination(
+ name, description, connectionArn, invocationEndpoint, httpMethod, rateLimit, ctx.region());
+ }
+
+ r.setPhysicalId(name);
+ String arn = destination.getArn();
+ r.getAttributes().put("Arn", arn);
+ String arnForPolicy = arn;
+ int lastSlash = arn.lastIndexOf('/');
+ int secondLastSlash = arn.lastIndexOf('/', lastSlash - 1);
+ if (secondLastSlash >= 0 && lastSlash > secondLastSlash) {
+ arnForPolicy = arn.substring(0, lastSlash);
+ }
+ r.getAttributes().put("ArnForPolicy", arnForPolicy);
+ r.getAttributes().put("Name", name);
+ }
+
+ private void snapshotApiDestinationBeforeUpdate(StackResource r, ApiDestination current, String region) {
+ ObjectNode snapshot = MAPPER.createObjectNode();
+ snapshot.put("region", region);
+ snapshot.put("name", current.getName());
+ snapshot.put("description", current.getDescription());
+ snapshot.put("connectionArn", current.getConnectionArn());
+ snapshot.put("invocationEndpoint", current.getInvocationEndpoint());
+ snapshot.put("httpMethod", current.getHttpMethod());
+ if (current.getInvocationRateLimitPerSecond() != null) {
+ snapshot.put("invocationRateLimitPerSecond", current.getInvocationRateLimitPerSecond());
+ }
+ r.getAttributes().put(CfnRollback.API_DESTINATION_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
+ }
+
+ // The snapshot is spent only once the restore succeeded: a restore that throws leaves it for the next attempt
+ private boolean rollbackApiDestinationUpdate(StackResource resource) {
+ String raw = resource.getAttributes().get(CfnRollback.API_DESTINATION_UPDATE_SNAPSHOT_ATTR);
+ if (raw == null) {
+ return false;
+ }
+ JsonNode snapshot;
+ try {
+ snapshot = MAPPER.readTree(raw);
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("Could not read the API destination update snapshot for "
+ + resource.getLogicalId(), e);
+ }
+ eventBridgeService.restoreApiDestination(snapshot.path("name").asText(),
+ snapshotText(snapshot, "description"),
+ snapshotText(snapshot, "connectionArn"),
+ snapshotText(snapshot, "invocationEndpoint"),
+ snapshotText(snapshot, "httpMethod"),
+ snapshot.hasNonNull("invocationRateLimitPerSecond")
+ ? snapshot.get("invocationRateLimitPerSecond").asInt() : null,
+ snapshot.path("region").asText());
+ resource.getAttributes().remove(CfnRollback.API_DESTINATION_UPDATE_SNAPSHOT_ATTR);
+ return true;
+ }
+
+ private void deleteApiDestinationSafe(String name, String region) {
+ CfnDeletes.safeDelete("EventBridge API destination", name,
+ () -> eventBridgeService.deleteApiDestination(name, region),
+ "ResourceNotFoundException");
+ }
+
/** Copied from the monolith: the shared original serves six other callers and stays there. */
private Map<String, Object> jsonObjectToMap(JsonNode node) {
Map<String, Object> out = new LinkedHashMap<>();
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java
index 5a8307eef0..645e9c30f8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.eventbridge;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsJson11Controller;
+import io.github.hectorvent.floci.services.eventbridge.model.ApiDestination;
import io.github.hectorvent.floci.services.eventbridge.model.Archive;
import io.github.hectorvent.floci.services.eventbridge.model.ArchiveState;
import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;
@@ -10,6 +11,7 @@ import io.github.hectorvent.floci.services.eventbridge.model.Connection;
import io.github.hectorvent.floci.services.eventbridge.model.ConnectionState;
import io.github.hectorvent.floci.services.eventbridge.model.EcsParameters;
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
+import io.github.hectorvent.floci.services.eventbridge.model.HttpParameters;
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
import io.github.hectorvent.floci.services.eventbridge.model.Replay;
import io.github.hectorvent.floci.services.eventbridge.model.ReplayState;
@@ -85,6 +87,11 @@ public class EventBridgeHandler {
case "UpdateConnection" -> handleUpdateConnection(request, region);
case "DeleteConnection" -> handleDeleteConnection(request, region);
case "ListConnections" -> handleListConnections(request, region);
+ case "CreateApiDestination" -> handleCreateApiDestination(request, region);
+ case "DescribeApiDestination" -> handleDescribeApiDestination(request, region);
+ case "UpdateApiDestination" -> handleUpdateApiDestination(request, region);
+ case "DeleteApiDestination" -> handleDeleteApiDestination(request, region);
+ case "ListApiDestinations" -> handleListApiDestinations(request, region);
case "StartReplay" -> handleStartReplay(request, region);
case "DescribeReplay" -> handleDescribeReplay(request, region);
case "CancelReplay" -> handleCancelReplay(request, region);
@@ -252,6 +259,10 @@ public class EventBridgeHandler {
target.setDeadLetterConfig(
objectMapper.convertValue(deadLetterConfigNode, Target.DeadLetterConfig.class));
}
+ JsonNode httpParamsNode = t.path("HttpParameters");
+ if (!httpParamsNode.isMissingNode() && httpParamsNode.isObject()) {
+ target.setHttpParameters(objectMapper.convertValue(httpParamsNode, HttpParameters.class));
+ }
targets.add(target);
}
}
@@ -324,6 +335,9 @@ public class EventBridgeHandler {
if (t.getDeadLetterConfig() != null) {
node.set("DeadLetterConfig", objectMapper.valueToTree(t.getDeadLetterConfig()));
}
+ if (t.getHttpParameters() != null) {
+ node.set("HttpParameters", objectMapper.valueToTree(t.getHttpParameters()));
+ }
targetsArray.add(node);
}
return Response.ok(response).build();
@@ -558,6 +572,106 @@ public class EventBridgeHandler {
return Response.ok(response).build();
}
+ // ──────────────────────────── Api Destinations ────────────────────────────
+
+ private Response handleCreateApiDestination(JsonNode request, String region) {
+ String name = request.path("Name").asText(null);
+ String description = request.path("Description").asText(null);
+ String connectionArn = request.path("ConnectionArn").asText(null);
+ String invocationEndpoint = request.path("InvocationEndpoint").asText(null);
+ String httpMethod = request.path("HttpMethod").asText(null);
+ Integer invocationRateLimitPerSecond = request.hasNonNull("InvocationRateLimitPerSecond")
+ ? request.path("InvocationRateLimitPerSecond").asInt() : null;
+
+ ApiDestination destination = eventBridgeService.createApiDestination(
+ name, description, connectionArn, invocationEndpoint,
+ httpMethod, invocationRateLimitPerSecond, region);
+ return buildApiDestinationMutationResponse(destination);
+ }
+
+ private Response buildApiDestinationMutationResponse(ApiDestination destination) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("ApiDestinationArn", destination.getArn());
+ response.put("ApiDestinationState", destination.getApiDestinationState().name());
+ response.put("CreationTime", destination.getCreationTime().getEpochSecond());
+ response.put("LastModifiedTime", destination.getLastModifiedTime().getEpochSecond());
+ return Response.ok(response).build();
+ }
+
+ private Response handleDescribeApiDestination(JsonNode request, String region) {
+ String name = request.path("Name").asText(null);
+ ApiDestination destination = eventBridgeService.describeApiDestination(name, region);
+ return Response.ok(buildApiDestinationNode(destination, true)).build();
+ }
+
+ private Response handleUpdateApiDestination(JsonNode request, String region) {
+ String name = request.path("Name").asText(null);
+ String description = request.has("Description") ? request.path("Description").asText(null) : null;
+ String connectionArn = request.has("ConnectionArn") ? request.path("ConnectionArn").asText(null) : null;
+ String invocationEndpoint = request.has("InvocationEndpoint") ? request.path("InvocationEndpoint").asText(null) : null;
+ String httpMethod = request.has("HttpMethod") ? request.path("HttpMethod").asText(null) : null;
+ Integer invocationRateLimitPerSecond = request.hasNonNull("InvocationRateLimitPerSecond")
+ ? request.path("InvocationRateLimitPerSecond").asInt() : null;
+
+ ApiDestination destination = eventBridgeService.updateApiDestination(
+ name, description, connectionArn, invocationEndpoint,
+ httpMethod, invocationRateLimitPerSecond, region);
+ return buildApiDestinationMutationResponse(destination);
+ }
+
+ private Response handleDeleteApiDestination(JsonNode request, String region) {
+ String name = request.path("Name").asText(null);
+ eventBridgeService.deleteApiDestination(name, region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleListApiDestinations(JsonNode request, String region) {
+ String namePrefix = request.path("NamePrefix").asText(null);
+ String connectionArn = request.path("ConnectionArn").asText(null);
+ String nextToken = request.path("NextToken").asText(null);
+ int limit = request.hasNonNull("Limit") ? request.path("Limit").asInt() : 100;
+ if (limit < 1 || limit > 100) {
+ throw new AwsException("ValidationException", "Limit must be between 1 and 100.", 400);
+ }
+ // The list is sorted by name, so NextToken is simply the name of the last item on the previous page
+ List<ApiDestination> destinations = eventBridgeService.listApiDestinations(namePrefix, connectionArn, region)
+ .stream()
+ .filter(dest -> nextToken == null || dest.getName().compareTo(nextToken) > 0)
+ .toList();
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode array = response.putArray("ApiDestinations");
+ for (ApiDestination dest : destinations.subList(0, Math.min(limit, destinations.size()))) {
+ array.add(buildApiDestinationNode(dest, false));
+ }
+ if (destinations.size() > limit) {
+ response.put("NextToken", destinations.get(limit - 1).getName());
+ }
+ return Response.ok(response).build();
+ }
+
+ private ObjectNode buildApiDestinationNode(ApiDestination dest, boolean full) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("ApiDestinationArn", dest.getArn());
+ node.put("Name", dest.getName());
+ node.put("ApiDestinationState", dest.getApiDestinationState().name());
+ node.put("ConnectionArn", dest.getConnectionArn());
+ node.put("InvocationEndpoint", dest.getInvocationEndpoint());
+ node.put("HttpMethod", dest.getHttpMethod());
+ if (dest.getInvocationRateLimitPerSecond() != null) {
+ node.put("InvocationRateLimitPerSecond", dest.getInvocationRateLimitPerSecond());
+ }
+ if (full && dest.getDescription() != null) {
+ node.put("Description", dest.getDescription());
+ }
+ if (dest.getCreationTime() != null) {
+ node.put("CreationTime", dest.getCreationTime().getEpochSecond());
+ }
+ if (dest.getLastModifiedTime() != null) {
+ node.put("LastModifiedTime", dest.getLastModifiedTime().getEpochSecond());
+ }
+ return node;
+ }
+
// ──────────────────────────── Replays ────────────────────────────
private Response handleStartReplay(JsonNode request, String region) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java
index 7a0317d8ce..ce3b20b004 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java
@@ -4,17 +4,22 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
+import io.github.hectorvent.floci.core.common.SsrfProtection;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
+import io.github.hectorvent.floci.services.eventbridge.model.ApiDestination;
+import io.github.hectorvent.floci.services.eventbridge.model.Connection;
import io.github.hectorvent.floci.services.eventbridge.model.EcsParameters;
+import io.github.hectorvent.floci.services.eventbridge.model.HttpParameters;
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
@@ -28,12 +33,25 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.io.IOException;
import java.io.UncheckedIOException;
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.UnknownHostException;
+import java.net.URLEncoder;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
@ApplicationScoped
public class EventBridgeInvoker {
@@ -42,6 +60,10 @@ public class EventBridgeInvoker {
// AWS can't route an event from a sender bus on to a third bus; the second hop is dropped.
private static final int MAX_BUS_TO_BUS_DEPTH = 1;
+ private static final int MAX_IDLE_RATE_WINDOWS = 256;
+ // Headers the JDK HttpClient manages itself; setting them by hand throws IllegalArgumentException.
+ private static final Set<String> RESTRICTED_HEADERS =
+ Set.of("connection", "content-length", "expect", "host", "transfer-encoding", "upgrade");
private static final ThreadLocal<Integer> BUS_TO_BUS_DEPTH = ThreadLocal.withInitial(() -> 0);
private final LambdaService lambdaService;
@@ -56,6 +78,8 @@ public class EventBridgeInvoker {
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final String baseUrl;
+ private final HttpClient httpClient;
+ private final Map<String, RateWindow> rateWindows = new ConcurrentHashMap<>();
@Inject
public EventBridgeInvoker(LambdaService lambdaService,
@@ -70,6 +94,24 @@ public class EventBridgeInvoker {
RegionResolver regionResolver,
ObjectMapper objectMapper,
EmulatorConfig config) {
+ this(lambdaService, sqsService, snsService, batchService, firehoseService, eventBridgeService,
+ ecsService, ecsJsonHandler, stepFunctionsService, regionResolver, objectMapper, config,
+ HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
+ }
+
+ EventBridgeInvoker(LambdaService lambdaService,
+ SqsService sqsService,
+ SnsService snsService,
+ BatchService batchService,
+ FirehoseService firehoseService,
+ EventBridgeService eventBridgeService,
+ EcsService ecsService,
+ EcsJsonHandler ecsJsonHandler,
+ StepFunctionsService stepFunctionsService,
+ RegionResolver regionResolver,
+ ObjectMapper objectMapper,
+ EmulatorConfig config,
+ HttpClient httpClient) {
this.lambdaService = lambdaService;
this.sqsService = sqsService;
this.snsService = snsService;
@@ -82,6 +124,7 @@ public class EventBridgeInvoker {
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.baseUrl = config.baseUrl();
+ this.httpClient = httpClient;
}
EventBridgeInvoker(LambdaService lambdaService,
@@ -247,6 +290,8 @@ public class EventBridgeInvoker {
BUS_TO_BUS_DEPTH.set(depth);
}
}
+ } else if (arn.contains(":events:") && arn.contains(":api-destination/")) {
+ deliverToApiDestination(target, payload, region);
} else {
LOG.warnv("EventBridge: unsupported target ARN type: {0}", arn);
}
@@ -448,4 +493,400 @@ public class EventBridgeInvoker {
String prefix = "stateMachine:";
return resource.startsWith(prefix) && resource.indexOf(':', prefix.length()) < 0;
}
+
+ // Failures are thrown, not just logged, so TargetDispatcher can retry the retryable ones and dead-letter the rest.
+ private void deliverToApiDestination(Target target, String payload, String region) {
+ if (eventBridgeService == null) {
+ LOG.warnv("EventBridge API Destination target missing EventBridge service: {0}", target.getArn());
+ return;
+ }
+ String arn = target.getArn();
+ ApiDestination destination = eventBridgeService.findApiDestinationByArn(arn, region);
+ if (destination == null) {
+ throw new AwsException("ResourceNotFoundException", "API destination " + arn + " does not exist.", 400);
+ }
+ acquireRatePermit(destination);
+
+ Connection connection = eventBridgeService.findConnectionByArn(destination.getConnectionArn(), region);
+
+ String rawUrl = destination.getInvocationEndpoint();
+ if (rawUrl == null || rawUrl.isBlank()) {
+ throw new AwsException("InvalidParameterException",
+ "API destination " + destination.getName() + " has no InvocationEndpoint.", 400);
+ }
+
+ HttpParameters httpParameters = target.getHttpParameters();
+ JsonNode authNode = readAuthParameters(connection);
+ JsonNode invocationHttp = authNode.path("InvocationHttpParameters");
+
+ // The connection's parameters are applied last so a target cannot override what the connection configures
+ Map<String, String> queryParams = new LinkedHashMap<>();
+ if (httpParameters != null && httpParameters.getQueryStringParameters() != null) {
+ queryParams.putAll(httpParameters.getQueryStringParameters());
+ }
+ queryParams.putAll(readKeyValues(invocationHttp.path("QueryStringParameters")));
+ String resolvedUrl = appendQueryParameters(
+ substitutePathParameters(rawUrl,
+ httpParameters != null ? httpParameters.getPathParameterValues() : null),
+ queryParams);
+
+ URI uri = parseDeliveryUri(resolvedUrl);
+
+ Map<String, String> headers = new LinkedHashMap<>();
+ if (httpParameters != null && httpParameters.getHeaderParameters() != null) {
+ httpParameters.getHeaderParameters().forEach((name, value) -> putHeader(headers, name, value));
+ }
+ readKeyValues(invocationHttp.path("HeaderParameters")).forEach((name, value) -> putHeader(headers, name, value));
+ applyConnectionAuth(connection, authNode, headers);
+
+ String method = destination.getHttpMethod() != null ? destination.getHttpMethod().toUpperCase() : "POST";
+ boolean hasBody = "POST".equals(method) || "PUT".equals(method) || "PATCH".equals(method);
+ if (hasBody && !containsHeader(headers, "Content-Type")) {
+ headers.put("Content-Type", "application/json; charset=utf-8");
+ }
+ String body = hasBody
+ ? mergeBodyParameters(payload, readKeyValues(invocationHttp.path("BodyParameters")))
+ : null;
+
+ HttpRequest request;
+ try {
+ HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
+ .uri(uri)
+ .timeout(Duration.ofSeconds(5));
+ applyHeaders(requestBuilder, headers);
+ requestBuilder.method(method, hasBody
+ ? HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)
+ : HttpRequest.BodyPublishers.noBody());
+ request = requestBuilder.build();
+ } catch (IllegalArgumentException e) {
+ throw new AwsException("InvalidParameterException", "The request to " + describe(uri)
+ + " is not valid (" + e.getClass().getSimpleName() + ").", 400);
+ }
+
+ HttpResponse<String> response = send(request, uri);
+ LOG.debugv("API Destination {0} response status: {1}", destination.getName(), response.statusCode());
+ requireSuccess(response.statusCode(), "API destination " + destination.getName(), uri);
+ }
+
+ private HttpResponse<String> send(HttpRequest request, URI uri) {
+ try {
+ return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new AwsException("ServiceUnavailableException", "Interrupted while calling " + describe(uri), 503);
+ } catch (IOException e) {
+ throw new AwsException("ServiceUnavailableException", "Could not reach " + describe(uri) + ": "
+ + e.getClass().getSimpleName(), 503);
+ }
+ }
+
+ // 429 and 5xx are retried by TargetDispatcher (THROTTLING / ERROR_FROM_TARGET); any other non-2xx is permanent
+ private static void requireSuccess(int status, String what, URI uri) {
+ if (status / 100 == 2) {
+ return;
+ }
+ if (status == 429) {
+ throw new AwsException("ThrottlingException", what + " was throttled by " + describe(uri), 429);
+ }
+ if (status >= 500) {
+ throw new AwsException("ServiceUnavailableException",
+ what + " got HTTP " + status + " from " + describe(uri), 502);
+ }
+ throw new AwsException("InvalidParameterException",
+ what + " got HTTP " + status + " from " + describe(uri), 400);
+ }
+
+ // Fixed one-second window per destination; an event over the limit is throttled and retried with backoff
+ void acquireRatePermit(ApiDestination destination) {
+ Integer limit = destination.getInvocationRateLimitPerSecond();
+ if (limit == null) {
+ return;
+ }
+ long nowSecond = Instant.now().getEpochSecond();
+ // Windows of deleted or idle destinations would otherwise pile up, so stale ones are swept once the map grows
+ if (rateWindows.size() > MAX_IDLE_RATE_WINDOWS) {
+ rateWindows.values().removeIf(stale -> nowSecond - stale.second() > 1);
+ }
+ // The whole check-and-count runs inside compute, which is atomic per key and also against the sweep above,
+ // so no delivery can keep counting on a window that was removed from the map
+ boolean[] allowed = new boolean[1];
+ rateWindows.compute(destination.getArn(), (key, current) -> {
+ RateWindow window = current == null || current.second() != nowSecond ? new RateWindow(nowSecond, 0) : current;
+ if (window.used() >= limit) {
+ return window;
+ }
+ allowed[0] = true;
+ return new RateWindow(nowSecond, window.used() + 1);
+ });
+ if (!allowed[0]) {
+ throw new AwsException("ThrottlingException", "API destination " + destination.getName()
+ + " exceeded its InvocationRateLimitPerSecond of " + limit + ".", 429);
+ }
+ }
+
+ private record RateWindow(long second, int used) {
+ }
+
+ // Only substitutes '*' inside the path: a user-supplied value must not be able to change the host, query or fragment.
+ static String substitutePathParameters(String url, List<String> values) {
+ if (values == null || values.isEmpty()) {
+ return url;
+ }
+ int authorityStart = url.indexOf("://");
+ int pathStart = authorityStart < 0 ? -1 : url.indexOf('/', authorityStart + 3);
+ if (pathStart < 0) {
+ return url;
+ }
+ int pathEnd = url.length();
+ for (int i = pathStart; i < url.length(); i++) {
+ char c = url.charAt(i);
+ if (c == '?' || c == '#') {
+ pathEnd = i;
+ break;
+ }
+ }
+ StringBuilder path = new StringBuilder(url.substring(pathStart, pathEnd));
+ int valueIndex = 0;
+ int star = path.indexOf("*");
+ while (star >= 0 && valueIndex < values.size()) {
+ String value = values.get(valueIndex++);
+ String encoded = value == null ? "" : URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
+ path.replace(star, star + 1, encoded);
+ star = path.indexOf("*", star + encoded.length());
+ }
+ return url.substring(0, pathStart) + path + url.substring(pathEnd);
+ }
+
+ static String appendQueryParameters(String url, Map<String, String> queryParams) {
+ if (queryParams.isEmpty()) {
+ return url;
+ }
+ // The query must precede any fragment, otherwise the parameters become part of the fragment and never reach the server
+ int fragmentStart = url.indexOf('#');
+ String base = fragmentStart < 0 ? url : url.substring(0, fragmentStart);
+ String fragment = fragmentStart < 0 ? "" : url.substring(fragmentStart);
+ StringBuilder sb = new StringBuilder(base);
+ if (!base.contains("?")) {
+ sb.append('?');
+ } else if (!base.endsWith("?") && !base.endsWith("&")) {
+ sb.append('&');
+ }
+ boolean first = true;
+ for (Map.Entry<String, String> entry : queryParams.entrySet()) {
+ if (!first) {
+ sb.append('&');
+ }
+ first = false;
+ sb.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8))
+ .append('=')
+ .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
+ }
+ return sb.append(fragment).toString();
+ }
+
+ // Throws a permanent error when the URL is unsafe to call; its message never carries the URL, which may hold secrets
+ private URI parseDeliveryUri(String url) {
+ URI uri;
+ try {
+ uri = URI.create(url);
+ } catch (IllegalArgumentException e) {
+ throw new AwsException("InvalidParameterException", "The resolved URL is not a valid URI.", 400);
+ }
+ String scheme = uri.getScheme();
+ if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
+ throw new AwsException("InvalidParameterException", "Unsupported URL scheme " + scheme + ".", 400);
+ }
+ String host = uri.getHost();
+ if (host == null) {
+ throw new AwsException("InvalidParameterException", "The resolved URL has no valid host.", 400);
+ }
+ try {
+ SsrfProtection.rejectMetadataAddresses(InetAddress.getAllByName(host), host);
+ } catch (UnknownHostException expected) {
+ // httpClient.send reports the resolution failure itself. DNS is resolved again at send time,
+ // so rebinding remains a residual risk: the JDK HttpClient cannot pin the address that was checked
+ } catch (IOException e) {
+ throw new AwsException("InvalidParameterException",
+ "Refusing to call " + describe(uri) + ": " + e.getMessage(), 400);
+ }
+ return uri;
+ }
+
+ private static String describe(URI uri) {
+ String port = uri.getPort() >= 0 ? ":" + uri.getPort() : "";
+ return uri.getScheme() + "://" + uri.getHost() + port + (uri.getRawPath() != null ? uri.getRawPath() : "");
+ }
+
+ private JsonNode readAuthParameters(Connection connection) {
+ if (connection.getAuthParameters() == null) {
+ return MissingNode.getInstance();
+ }
+ try {
+ return objectMapper.readTree(connection.getAuthParameters());
+ } catch (JsonProcessingException e) {
+ LOG.warnv("Failed to parse authParameters of connection {0}: {1}",
+ connection.getName(), e.getOriginalMessage());
+ return MissingNode.getInstance();
+ }
+ }
+
+ private static Map<String, String> readKeyValues(JsonNode params) {
+ Map<String, String> result = new LinkedHashMap<>();
+ for (JsonNode param : params) {
+ String key = param.path("Key").asText(null);
+ String value = param.path("Value").asText(null);
+ if (key != null && value != null) {
+ result.put(key, value);
+ }
+ }
+ return result;
+ }
+
+ // Header names are case-insensitive: a later value replaces an earlier one that differs only by case
+ private static void putHeader(Map<String, String> headers, String name, String value) {
+ headers.keySet().removeIf(existing -> existing.equalsIgnoreCase(name));
+ headers.put(name, value);
+ }
+
+ private static boolean containsHeader(Map<String, String> headers, String name) {
+ return headers.keySet().stream().anyMatch(name::equalsIgnoreCase);
+ }
+
+ private static void applyHeaders(HttpRequest.Builder requestBuilder, Map<String, String> headers) {
+ for (Map.Entry<String, String> header : headers.entrySet()) {
+ String name = header.getKey();
+ if (RESTRICTED_HEADERS.contains(name.toLowerCase())) {
+ LOG.debugv("API Destination header {0} is managed by the HTTP client; skipping", name);
+ continue;
+ }
+ try {
+ requestBuilder.header(name, header.getValue());
+ } catch (IllegalArgumentException e) {
+ LOG.warnv("API Destination header {0} is not valid; skipping", name);
+ }
+ }
+ }
+
+ private String mergeBodyParameters(String payload, Map<String, String> bodyParams) {
+ String body = payload != null ? payload : "";
+ if (bodyParams.isEmpty()) {
+ return body;
+ }
+ try {
+ JsonNode parsed = body.isBlank() ? objectMapper.createObjectNode() : objectMapper.readTree(body);
+ if (!(parsed instanceof ObjectNode objectNode)) {
+ LOG.debug("API Destination body is not a JSON object; connection BodyParameters not applied");
+ return body;
+ }
+ bodyParams.forEach(objectNode::put);
+ return objectMapper.writeValueAsString(objectNode);
+ } catch (JsonProcessingException e) {
+ LOG.debugv("API Destination body is not JSON; connection BodyParameters not applied: {0}",
+ e.getOriginalMessage());
+ return body;
+ }
+ }
+
+ // Throws when the Connection needs an Authorization that cannot be obtained, so the event is never sent unauthenticated
+ private void applyConnectionAuth(Connection connection, JsonNode authNode, Map<String, String> headers) {
+ String authType = connection.getAuthorizationType();
+ if (authType == null) {
+ return;
+ }
+ switch (authType) {
+ case "BASIC" -> {
+ JsonNode basic = authNode.path("BasicAuthParameters");
+ if (!basic.isMissingNode()) {
+ putHeader(headers, "Authorization", basicAuthorization(
+ basic.path("Username").asText(""), basic.path("Password").asText("")));
+ }
+ }
+ case "API_KEY" -> {
+ JsonNode apiKey = authNode.path("ApiKeyAuthParameters");
+ String name = apiKey.path("ApiKeyName").asText(null);
+ String value = apiKey.path("ApiKeyValue").asText(null);
+ if (name != null && value != null) {
+ putHeader(headers, name, value);
+ }
+ }
+ case "OAUTH_CLIENT_CREDENTIALS" ->
+ putHeader(headers, "Authorization", fetchOAuthAuthorization(authNode.path("OAuthParameters")));
+ default -> LOG.warnv("Unsupported connection authorization type: {0}", authType);
+ }
+ }
+
+ private static String basicAuthorization(String user, String password) {
+ return "Basic " + Base64.getEncoder().encodeToString(
+ (user + ":" + password).getBytes(StandardCharsets.UTF_8));
+ }
+
+ // RFC 6749 client-credentials exchange; returns "<token_type> <access_token>" and throws when no token is obtained
+ private String fetchOAuthAuthorization(JsonNode oauth) {
+ String endpoint = oauth.path("AuthorizationEndpoint").asText(null);
+ if (endpoint == null || endpoint.isBlank()) {
+ throw new AwsException("InvalidParameterException", "The OAuth connection has no AuthorizationEndpoint.", 400);
+ }
+ JsonNode oauthHttp = oauth.path("OAuthHttpParameters");
+ String method = oauth.path("HttpMethod").asText("POST").toUpperCase();
+ boolean hasBody = !"GET".equals(method);
+
+ URI uri = parseDeliveryUri(appendQueryParameters(endpoint,
+ readKeyValues(oauthHttp.path("QueryStringParameters"))));
+
+ Map<String, String> headers = readKeyValues(oauthHttp.path("HeaderParameters"));
+ if (!containsHeader(headers, "Authorization")) {
+ JsonNode client = oauth.path("ClientParameters");
+ headers.put("Authorization", basicAuthorization(
+ client.path("ClientID").asText(""), client.path("ClientSecret").asText("")));
+ }
+ if (hasBody && !containsHeader(headers, "Content-Type")) {
+ headers.put("Content-Type", "application/x-www-form-urlencoded");
+ }
+
+ Map<String, String> form = new LinkedHashMap<>();
+ form.put("grant_type", "client_credentials");
+ form.putAll(readKeyValues(oauthHttp.path("BodyParameters")));
+ StringBuilder formBody = new StringBuilder();
+ for (Map.Entry<String, String> entry : form.entrySet()) {
+ if (!formBody.isEmpty()) {
+ formBody.append('&');
+ }
+ formBody.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8))
+ .append('=')
+ .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
+ }
+
+ HttpRequest request;
+ try {
+ HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
+ .uri(uri)
+ .timeout(Duration.ofSeconds(5));
+ applyHeaders(requestBuilder, headers);
+ requestBuilder.method(method, hasBody
+ ? HttpRequest.BodyPublishers.ofString(formBody.toString(), StandardCharsets.UTF_8)
+ : HttpRequest.BodyPublishers.noBody());
+ request = requestBuilder.build();
+ } catch (IllegalArgumentException e) {
+ throw new AwsException("InvalidParameterException", "The OAuth token request to " + describe(uri)
+ + " is not valid (" + e.getClass().getSimpleName() + ").", 400);
+ }
+
+ HttpResponse<String> response = send(request, uri);
+ requireSuccess(response.statusCode(), "The OAuth token request", uri);
+ String accessToken;
+ String tokenType;
+ try {
+ JsonNode token = objectMapper.readTree(response.body());
+ accessToken = token.path("access_token").asText(null);
+ tokenType = token.path("token_type").asText("Bearer");
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidParameterException",
+ "The OAuth token response from " + describe(uri) + " is not JSON.", 400);
+ }
+ if (accessToken == null || accessToken.isBlank()) {
+ throw new AwsException("InvalidParameterException",
+ "The OAuth token response from " + describe(uri) + " has no access_token.", 400);
+ }
+ return tokenType + " " + accessToken;
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
index 11c857e5cc..d62a49d4cd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
@@ -8,6 +8,8 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
+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.ArchiveState;
import io.github.hectorvent.floci.services.eventbridge.model.ArchivedEvent;
@@ -32,8 +34,11 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.net.URI;
+import java.net.URISyntaxException;
import java.time.Instant;
import java.util.ArrayList;
+import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -42,6 +47,7 @@ import java.util.regex.Pattern;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
+import java.util.Optional;
import java.util.Set;
@ApplicationScoped
@@ -56,6 +62,7 @@ public class EventBridgeService implements ResourceProvider {
private final StorageBackend<String, List<ArchivedEvent>> archivedEventStore;
private final StorageBackend<String, Replay> replayStore;
private final StorageBackend<String, Connection> connectionStore;
+ private final StorageBackend<String, ApiDestination> apiDestinationStore;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final RuleScheduler ruleScheduler;
@@ -87,6 +94,8 @@ public class EventBridgeService implements ResourceProvider {
new TypeReference<Map<String, Replay>>() {}),
storageFactory.create("eventbridge", "eventbridge-connections.json",
new TypeReference<Map<String, Connection>>() {}),
+ storageFactory.create("eventbridge", "eventbridge-api-destinations.json",
+ new TypeReference<Map<String, ApiDestination>>() {}),
regionResolver, objectMapper, ruleScheduler, dispatcher, replayDispatcher,
resourceGroupsTaggingService
);
@@ -99,6 +108,7 @@ public class EventBridgeService implements ResourceProvider {
StorageBackend<String, List<ArchivedEvent>> archivedEventStore,
StorageBackend<String, Replay> replayStore,
StorageBackend<String, Connection> connectionStore,
+ StorageBackend<String, ApiDestination> apiDestinationStore,
RegionResolver regionResolver,
ObjectMapper objectMapper,
RuleScheduler ruleScheduler,
@@ -112,6 +122,7 @@ public class EventBridgeService implements ResourceProvider {
this.archivedEventStore = archivedEventStore;
this.replayStore = replayStore;
this.connectionStore = connectionStore;
+ this.apiDestinationStore = apiDestinationStore;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.ruleScheduler = ruleScheduler;
@@ -1477,6 +1488,255 @@ public class EventBridgeService implements ResourceProvider {
}
}
+ // ──────────────────────────── Api Destinations ────────────────────────────
+
+ private static final Pattern API_DESTINATION_NAME_PATTERN =
+ Pattern.compile("[\\.\\-_A-Za-z0-9]+");
+ private static final Set<String> ALLOWED_HTTP_METHODS =
+ Set.of("GET", "HEAD", "POST", "OPTIONS", "PUT", "DELETE", "PATCH");
+
+ public synchronized ApiDestination createApiDestination(String name, String description, String connectionArn,
+ String invocationEndpoint, String httpMethod,
+ Integer invocationRateLimitPerSecond, String region) {
+ validateApiDestinationName(name);
+ if (connectionArn == null || connectionArn.isBlank()) {
+ throw new AwsException("ValidationException", "ConnectionArn is required.", 400);
+ }
+ findConnectionByArn(connectionArn, region);
+ if (invocationEndpoint == null || invocationEndpoint.isBlank()) {
+ throw new AwsException("ValidationException", "InvocationEndpoint is required.", 400);
+ }
+ validateInvocationEndpoint(invocationEndpoint);
+ validateHttpMethod(httpMethod);
+ if (invocationRateLimitPerSecond != null && invocationRateLimitPerSecond < 1) {
+ throw new AwsException("ValidationException",
+ "InvocationRateLimitPerSecond must be at least 1.", 400);
+ }
+
+ String key = apiDestinationKey(region, name);
+ if (apiDestinationStore.get(key).isPresent()) {
+ throw new AwsException("ResourceAlreadyExistsException",
+ "ApiDestination " + name + " already exists.", 400);
+ }
+
+ String destinationId = UUID.randomUUID().toString();
+ Instant now = Instant.now();
+ ApiDestination destination = new ApiDestination();
+ destination.setName(name);
+ destination.setArn(regionResolver.buildArn("events", region,
+ "api-destination/" + name + "/" + destinationId));
+ destination.setDescription(description);
+ destination.setConnectionArn(connectionArn);
+ destination.setInvocationEndpoint(invocationEndpoint);
+ destination.setHttpMethod(httpMethod);
+ destination.setInvocationRateLimitPerSecond(invocationRateLimitPerSecond);
+ destination.setApiDestinationState(ApiDestinationState.ACTIVE);
+ destination.setCreationTime(now);
+ destination.setLastModifiedTime(now);
+
+ apiDestinationStore.put(key, destination);
+ LOG.infov("Created API Destination: {0} with endpoint {1}", name, invocationEndpoint);
+ return destination;
+ }
+
+ public ApiDestination describeApiDestination(String name, String region) {
+ return apiDestinationStore.get(apiDestinationKey(region, name))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",
+ "ApiDestination " + name + " does not exist.", 400));
+ }
+
+ public synchronized ApiDestination updateApiDestination(String name, String description, String connectionArn,
+ String invocationEndpoint, String httpMethod,
+ Integer invocationRateLimitPerSecond, String region) {
+ String key = apiDestinationKey(region, name);
+ ApiDestination destination = apiDestinationStore.get(key)
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",
+ "ApiDestination " + name + " does not exist.", 400));
+
+ // Validate everything before assigning: the in-memory store returns the same instance, so a rejected update must not leave partial changes
+ if (connectionArn != null) {
+ findConnectionByArn(connectionArn, region);
+ }
+ if (invocationEndpoint != null) {
+ validateInvocationEndpoint(invocationEndpoint);
+ }
+ if (httpMethod != null) {
+ validateHttpMethod(httpMethod);
+ }
+ if (invocationRateLimitPerSecond != null && invocationRateLimitPerSecond < 1) {
+ throw new AwsException("ValidationException",
+ "InvocationRateLimitPerSecond must be at least 1.", 400);
+ }
+
+ if (connectionArn != null) {
+ destination.setConnectionArn(connectionArn);
+ }
+ if (description != null) {
+ destination.setDescription(description);
+ }
+ if (invocationEndpoint != null) {
+ destination.setInvocationEndpoint(invocationEndpoint);
+ }
+ if (httpMethod != null) {
+ destination.setHttpMethod(httpMethod);
+ }
+ if (invocationRateLimitPerSecond != null) {
+ destination.setInvocationRateLimitPerSecond(invocationRateLimitPerSecond);
+ }
+ Instant now = Instant.now();
+ destination.setLastModifiedTime(now);
+ apiDestinationStore.put(key, destination);
+ LOG.infov("Updated API Destination: {0}", name);
+ return destination;
+ }
+
+ // Puts back a prior configuration verbatim, including unset fields that updateApiDestination cannot clear
+ public synchronized ApiDestination restoreApiDestination(String name, String description, String connectionArn,
+ String invocationEndpoint, String httpMethod,
+ Integer invocationRateLimitPerSecond, String region) {
+ String key = apiDestinationKey(region, name);
+ ApiDestination destination = apiDestinationStore.get(key)
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",
+ "ApiDestination " + name + " does not exist.", 400));
+ destination.setDescription(description);
+ destination.setConnectionArn(connectionArn);
+ destination.setInvocationEndpoint(invocationEndpoint);
+ destination.setHttpMethod(httpMethod);
+ destination.setInvocationRateLimitPerSecond(invocationRateLimitPerSecond);
+ destination.setLastModifiedTime(Instant.now());
+ apiDestinationStore.put(key, destination);
+ LOG.infov("Restored API Destination: {0}", name);
+ return destination;
+ }
+
+ public synchronized ApiDestination deleteApiDestination(String name, String region) {
+ String key = apiDestinationKey(region, name);
+ ApiDestination destination = apiDestinationStore.get(key)
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",
+ "ApiDestination " + name + " does not exist.", 400));
+ apiDestinationStore.delete(key);
+ LOG.infov("Deleted API Destination: {0}", name);
+ return destination;
+ }
+
+ public List<ApiDestination> listApiDestinations(String namePrefix, String connectionArn, String region) {
+ String prefix = "api-destination:" + region + ":";
+ List<ApiDestination> destinations = new ArrayList<>(apiDestinationStore.scan(k -> {
+ if (!k.startsWith(prefix)) {
+ return false;
+ }
+ ApiDestination dest = apiDestinationStore.get(k).orElse(null);
+ if (dest == null) {
+ return false;
+ }
+ if (namePrefix != null && !namePrefix.isBlank()
+ && !dest.getName().startsWith(namePrefix)) {
+ return false;
+ }
+ if (connectionArn != null && !connectionArn.isBlank()
+ && !connectionArn.equals(dest.getConnectionArn())) {
+ return false;
+ }
+ return true;
+ }));
+ destinations.sort(Comparator.comparing(ApiDestination::getName));
+ return destinations;
+ }
+
+ public Connection findConnectionByArn(String connectionArn, String region) {
+ if (connectionArn == null || connectionArn.isBlank()) {
+ throw new AwsException("ResourceNotFoundException", "Connection ARN is required.", 400);
+ }
+ if (AwsArnUtils.isArn(connectionArn)) {
+ AwsArnUtils.Arn parsed = AwsArnUtils.parse(connectionArn);
+ String resource = parsed.resource();
+ if (resource.startsWith("connection/")) {
+ String remainder = resource.substring("connection/".length());
+ int slash = remainder.indexOf('/');
+ String name = slash > 0 ? remainder.substring(0, slash) : remainder;
+ String connRegion = parsed.region().isEmpty() ? region : parsed.region();
+ Optional<Connection> opt = connectionStore.get(connectionKey(connRegion, name));
+ // The ARN carries a generated id: one for a connection deleted and recreated under the same name must not match
+ if (opt.isPresent() && connectionArn.equals(opt.get().getConnectionArn())) {
+ return opt.get();
+ }
+ }
+ }
+ return connectionStore.scan(k -> {
+ Connection c = connectionStore.get(k).orElse(null);
+ return c != null && connectionArn.equals(c.getConnectionArn());
+ }).stream().findFirst().orElseThrow(() -> new AwsException("ResourceNotFoundException",
+ "Connection " + connectionArn + " does not exist.", 400));
+ }
+
+ public ApiDestination findApiDestinationByArn(String arn, String region) {
+ if (arn == null || arn.isBlank()) {
+ return null;
+ }
+ if (AwsArnUtils.isArn(arn)) {
+ AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
+ String resource = parsed.resource();
+ if (resource.startsWith("api-destination/")) {
+ String remainder = resource.substring("api-destination/".length());
+ int slash = remainder.indexOf('/');
+ String name = slash > 0 ? remainder.substring(0, slash) : remainder;
+ String destRegion = parsed.region().isEmpty() ? region : parsed.region();
+ Optional<ApiDestination> opt = apiDestinationStore.get(apiDestinationKey(destRegion, name));
+ // Same as connections: an ARN for a destination deleted and recreated under the same name is stale
+ if (opt.isPresent() && arn.equals(opt.get().getArn())) {
+ return opt.get();
+ }
+ }
+ }
+ return apiDestinationStore.scan(k -> {
+ ApiDestination d = apiDestinationStore.get(k).orElse(null);
+ return d != null && arn.equals(d.getArn());
+ }).stream().findFirst().orElse(null);
+ }
+
+ private static String apiDestinationKey(String region, String name) {
+ return "api-destination:" + region + ":" + name;
+ }
+
+ private static void validateApiDestinationName(String name) {
+ if (name == null || name.isBlank()) {
+ throw new AwsException("ValidationException", "Name is required.", 400);
+ }
+ if (name.length() > 64 || !API_DESTINATION_NAME_PATTERN.matcher(name).matches()) {
+ throw new AwsException("ValidationException",
+ "Name must match [\\.\\-_A-Za-z0-9]+ and be at most 64 characters.", 400);
+ }
+ }
+
+ private static void validateInvocationEndpoint(String invocationEndpoint) {
+ URI uri;
+ try {
+ uri = new URI(invocationEndpoint);
+ } catch (URISyntaxException e) {
+ throw new AwsException("ValidationException", "InvocationEndpoint is not a valid URL.", 400);
+ }
+ String scheme = uri.getScheme();
+ if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
+ throw new AwsException("ValidationException",
+ "InvocationEndpoint must be an HTTP or HTTPS URL.", 400);
+ }
+ // getHost() is null for a missing host (https://:8080), and for a '*' in the host, which AWS only allows in the path
+ if (uri.getHost() == null) {
+ throw new AwsException("ValidationException",
+ "InvocationEndpoint must include a valid host, and a '*' wildcard is only allowed in the path.", 400);
+ }
+ }
+
+ private static void validateHttpMethod(String httpMethod) {
+ if (httpMethod == null || httpMethod.isBlank()) {
+ throw new AwsException("ValidationException", "HttpMethod is required.", 400);
+ }
+ if (!ALLOWED_HTTP_METHODS.contains(httpMethod)) {
+ throw new AwsException("ValidationException",
+ "HttpMethod must be one of GET, HEAD, POST, OPTIONS, PUT, DELETE, PATCH.", 400);
+ }
+ }
+
private void captureToArchives(Map<String, Object> entry, String busStoreKey,
String eventId, String region, String accountId) {
EventBus bus = accountGet(busStore, accountId, busStoreKey).orElse(null);
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/ApiDestination.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/ApiDestination.java
new file mode 100644
index 0000000000..0130786d98
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/ApiDestination.java
@@ -0,0 +1,115 @@
+package io.github.hectorvent.floci.services.eventbridge.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+@RegisterForReflection
+public class ApiDestination {
+
+ private String name;
+ private String arn;
+ private String description;
+ private String connectionArn;
+ private String invocationEndpoint;
+ private String httpMethod;
+ private Integer invocationRateLimitPerSecond;
+ private ApiDestinationState apiDestinationState;
+ private Instant creationTime;
+ private Instant lastModifiedTime;
+
+ public ApiDestination() {
+ }
+
+ public ApiDestination(String name, String arn, String connectionArn, String invocationEndpoint,
+ String httpMethod, Integer invocationRateLimitPerSecond, String description) {
+ this.name = name;
+ this.arn = arn;
+ this.connectionArn = connectionArn;
+ this.invocationEndpoint = invocationEndpoint;
+ this.httpMethod = httpMethod;
+ this.invocationRateLimitPerSecond = invocationRateLimitPerSecond;
+ this.description = description;
+ this.apiDestinationState = ApiDestinationState.ACTIVE;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getArn() {
+ return arn;
+ }
+
+ public void setArn(String arn) {
+ this.arn = arn;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getConnectionArn() {
+ return connectionArn;
+ }
+
+ public void setConnectionArn(String connectionArn) {
+ this.connectionArn = connectionArn;
+ }
+
+ public String getInvocationEndpoint() {
+ return invocationEndpoint;
+ }
+
+ public void setInvocationEndpoint(String invocationEndpoint) {
+ this.invocationEndpoint = invocationEndpoint;
+ }
+
+ public String getHttpMethod() {
+ return httpMethod;
+ }
+
+ public void setHttpMethod(String httpMethod) {
+ this.httpMethod = httpMethod;
+ }
+
+ public Integer getInvocationRateLimitPerSecond() {
+ return invocationRateLimitPerSecond;
+ }
+
+ public void setInvocationRateLimitPerSecond(Integer invocationRateLimitPerSecond) {
+ this.invocationRateLimitPerSecond = invocationRateLimitPerSecond;
+ }
+
+ public ApiDestinationState getApiDestinationState() {
+ return apiDestinationState;
+ }
+
+ public void setApiDestinationState(ApiDestinationState apiDestinationState) {
+ this.apiDestinationState = apiDestinationState;
+ }
+
+ public Instant getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(Instant creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public Instant getLastModifiedTime() {
+ return lastModifiedTime;
+ }
+
+ public void setLastModifiedTime(Instant lastModifiedTime) {
+ this.lastModifiedTime = lastModifiedTime;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/ApiDestinationState.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/ApiDestinationState.java
new file mode 100644
index 0000000000..0f08329be5
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/ApiDestinationState.java
@@ -0,0 +1,9 @@
+package io.github.hectorvent.floci.services.eventbridge.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+public enum ApiDestinationState {
+ ACTIVE,
+ INACTIVE
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/HttpParameters.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/HttpParameters.java
new file mode 100644
index 0000000000..57bd127ade
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/HttpParameters.java
@@ -0,0 +1,49 @@
+package io.github.hectorvent.floci.services.eventbridge.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.List;
+import java.util.Map;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class HttpParameters {
+
+ @JsonProperty("PathParameterValues")
+ private List<String> pathParameterValues;
+
+ @JsonProperty("HeaderParameters")
+ private Map<String, String> headerParameters;
+
+ @JsonProperty("QueryStringParameters")
+ private Map<String, String> queryStringParameters;
+
+ public HttpParameters() {
+ }
+
+ public List<String> getPathParameterValues() {
+ return pathParameterValues;
+ }
+
+ public void setPathParameterValues(List<String> pathParameterValues) {
+ this.pathParameterValues = pathParameterValues;
+ }
+
+ public Map<String, String> getHeaderParameters() {
+ return headerParameters;
+ }
+
+ public void setHeaderParameters(Map<String, String> headerParameters) {
+ this.headerParameters = headerParameters;
+ }
+
+ public Map<String, String> getQueryStringParameters() {
+ return queryStringParameters;
+ }
+
+ public void setQueryStringParameters(Map<String, String> queryStringParameters) {
+ this.queryStringParameters = queryStringParameters;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Target.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Target.java
index 0a869caf82..5f157d1a14 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Target.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Target.java
@@ -20,6 +20,7 @@ public class Target {
private EcsParameters ecsParameters;
private RetryPolicy retryPolicy;
private DeadLetterConfig deadLetterConfig;
+ private HttpParameters httpParameters;
public Target() {}
@@ -63,6 +64,9 @@ public class Target {
public DeadLetterConfig getDeadLetterConfig() { return deadLetterConfig; }
public void setDeadLetterConfig(DeadLetterConfig deadLetterConfig) { this.deadLetterConfig = deadLetterConfig; }
+ public HttpParameters getHttpParameters() { return httpParameters; }
+ public void setHttpParameters(HttpParameters httpParameters) { this.httpParameters = httpParameters; }
+
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisionerTest.java
index c0401c9d79..922b0233a8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisionerTest.java
@@ -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);
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeApiDestinationDeliveryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeApiDestinationDeliveryIntegrationTest.java
new file mode 100644
index 0000000000..be6569130f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeApiDestinationDeliveryIntegrationTest.java
@@ -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);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeApiDestinationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeApiDestinationIntegrationTest.java
new file mode 100644
index 0000000000..640560a67f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeApiDestinationIntegrationTest.java
@@ -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);
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvokerApiDestinationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvokerApiDestinationTest.java
new file mode 100644
index 0000000000..0fa3e0c442
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvokerApiDestinationTest.java
@@ -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);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
index 577e290073..04c5b2dd83 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
@@ -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));
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
index 5fde6d09a0..348bcb6e24 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
@@ -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());
+ }
}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index b238297192..e55ec516a7 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -87,6 +87,7 @@ AWS::ElasticLoadBalancingV2::Listener ElbV2CfnProvisioner
AWS::ElasticLoadBalancingV2::ListenerRule ElbV2CfnProvisioner
AWS::ElasticLoadBalancingV2::LoadBalancer ElbV2CfnProvisioner
AWS::ElasticLoadBalancingV2::TargetGroup ElbV2CfnProvisioner
+AWS::Events::ApiDestination EventsCfnProvisioner
AWS::Events::Archive EventsArchiveCfnProvisioner
AWS::Events::EventBus EventsCfnProvisioner
AWS::Events::EventBusPolicy EventsCfnProvisioner