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

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

- Add ApiDestination, ApiDestinationState, and HttpParameters models

- Implement CRUD operations for API destinations in EventBridgeService

- Add CreateApiDestination, DescribeApiDestination, UpdateApiDestination, DeleteApiDestination, ListApiDestinations actions in EventBridgeHandler

- Support HttpParameters on targets in PutTargets and ListTargetsByRule

- Implement HTTP delivery to API destinations in EventBridgeInvoker with connection auth and SSRF protection

- Add CloudFormation provisioning for AWS::Events::ApiDestination in EventsCfnProvisioner

- Update docs and tests

* fix(eventbridge): harden ApiDestination delivery and CloudFormation lifecycle

- Throw on delivery failure so TargetDispatcher retries 429/5xx and connection
  errors and dead-letters permanent failures
- Enforce InvocationRateLimitPerSecond per destination
- Run the OAuth client-credentials exchange for OAUTH_CLIENT_CREDENTIALS connections
- Reject non-http(s) endpoints and wildcard hosts, encode path parameter values,
  keep the query before any fragment, and stop logging URLs that may carry secrets
- Resolve destination and connection ARNs only when they match the stored ARN
- Validate every UpdateApiDestination field before applying any of them
- Paginate ListApiDestinations with Limit and NextToken
- Keep HttpParameters on AWS::Events::Rule targets and roll back
  AWS::Events::ApiDestination updates from a snapshot

* fix(eventbridge): keep connection credentials authoritative and require a valid endpoint host

- Apply target headers and query parameters before the connection's so a target
  cannot override its credentials, and replace header names that differ only by case
- Reject endpoints without a parsed host (for example https://:8080/path)
- Sweep stale rate-limit windows once the map grows

* fix(eventbridge): make the ApiDestination rate limit check atomic

Count permits inside ConcurrentHashMap.compute on an immutable window so the
stale-window sweep can no longer remove a window another delivery is using,
which let concurrent deliveries exceed InvocationRateLimitPerSecond.

* refactor(eventbridge): drop the in-service InMemoryStorage constructor and tidy tests

- Remove the compatibility constructor that instantiated InMemoryStorage inside
  EventBridgeService; tests pass the ApiDestination store explicitly
- Import classes instead of qualifying them inline in the ApiDestination integration test
- Surface worker failures in the concurrent rate limit test by checking each Future

* docs: correct the EventBridge and IAM operation counts in the service matrix
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-04 18:03:31 -04:00
1 parent fabcd6baf8
commit 108f2b54bf
19 files changed
+2413 -5

No files matched your search

@@ -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
@@ -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<>();
@@ -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) {
@@ -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;
}
}
@@ -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);
@@ -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;
}
}
@@ -0,0 +1,9 @@
package io.github.hectorvent.floci.services.eventbridge.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public enum ApiDestinationState {
ACTIVE,
INACTIVE
}
@@ -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;
}
}
@@ -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)