Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(lambda): support self-managed Apache Kafka event source mappings (#3062) (#3082)

Vũ Thế Huyee5c87d6d696
diff --git a/docs/services/lambda.md b/docs/services/lambda.md
index 9510842dd6..368cd602ce 100644
--- a/docs/services/lambda.md
+++ b/docs/services/lambda.md
@@ -720,7 +720,7 @@ aws lambda update-function-code \
## Event Source Mappings
-Connect Lambda to SQS, Kinesis, or DynamoDB Streams:
+Connect Lambda to SQS, Kinesis, or DynamoDB Streams. Self-managed Apache Kafka event source mappings are accepted, validated, persisted, and returned on the wire, but Floci does not run an active Kafka consumer poller:
```bash
# SQS trigger
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index 79663040d9..e824424983 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -256,7 +256,6 @@ public class CloudFormationResourceProvisioner {
"AWS::IAM::ManagedPolicy",
"AWS::IAM::Policy",
"AWS::IAM::User",
- "AWS::Lambda::EventSourceMapping",
"AWS::Lambda::Function",
"AWS::Lambda::LayerVersion",
"AWS::RDS::DBCluster",
@@ -452,8 +451,6 @@ public class CloudFormationResourceProvisioner {
region,
accountId,
stackName);
- case "AWS::Lambda::EventSourceMapping" ->
- provisionLambdaEventSourceMapping(resource, properties, engine, region);
case "AWS::Cognito::UserPool" ->
provisionCognitoUserPool(resource, properties, engine, region, accountId, stackName);
case "AWS::Cognito::UserPoolClient" ->
@@ -744,7 +741,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::ApiGateway::RestApi" -> apiGatewayService.deleteRestApi(region, physicalId);
case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);
case "AWS::StepFunctions::StateMachine" -> stepFunctionsService.deleteStateMachine(physicalId);
- case "AWS::Lambda::EventSourceMapping" -> lambdaService.deleteEventSourceMapping(physicalId);
case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);
case "AWS::Cognito::UserPool" -> cognitoService.deleteUserPool(physicalId);
case "AWS::Cognito::UserPoolClient" -> cognitoService.deleteUserPoolClient(physicalId);
@@ -4115,58 +4111,6 @@ public class CloudFormationResourceProvisioner {
}
}
- // ── Lambda EventSourceMapping ─────────────────────────────────────────────
-
- private void provisionLambdaEventSourceMapping(StackResource r, JsonNode props,
- CloudFormationTemplateEngine engine, String region) {
- Map<String, Object> req = new HashMap<>();
- req.put("FunctionName", resolveOptional(props, "FunctionName", engine));
- req.put("EventSourceArn", resolveOptional(props, "EventSourceArn", engine));
-
- String enabledStr = resolveOptional(props, "Enabled", engine);
- if (enabledStr != null) {
- req.put("Enabled", Boolean.parseBoolean(enabledStr));
- }
-
- String batchSize = resolveOptional(props, "BatchSize", engine);
- if (batchSize != null) {
- try { req.put("BatchSize", Integer.parseInt(batchSize)); } catch (NumberFormatException ignored) {}
- }
-
- String startingPosition = resolveOptional(props, "StartingPosition", engine);
- if (startingPosition != null) {
- req.put("StartingPosition", startingPosition);
- }
-
- String startingPositionTimestamp = resolveOptional(props, "StartingPositionTimestamp", engine);
- if (startingPositionTimestamp != null) {
- try {
- double timestamp = Double.parseDouble(startingPositionTimestamp);
- if (!Double.isFinite(timestamp)) {
- throw new NumberFormatException("Non-finite timestamp");
- }
- req.put("StartingPositionTimestamp", timestamp);
- } catch (NumberFormatException e) {
- // Not swallowed the way BatchSize above is: dropping this one degrades into the
- // "StartingPositionTimestamp is required" error from the service, which points at
- // the wrong problem and hides the value that actually failed to parse. Double.parseDouble
- // accepts "NaN"/"Infinity"/"-Infinity" without throwing, so isFinite is checked explicitly
- // to keep those from silently becoming epoch-zero or long-extremum timestamps downstream.
- throw new AwsException("ValidationError",
- "Value of property StartingPositionTimestamp must be a number.", 400);
- }
- }
-
- List<String> functionResponseTypes = resolveStringList(props, "FunctionResponseTypes", engine);
- if (!functionResponseTypes.isEmpty()) {
- req.put("FunctionResponseTypes", functionResponseTypes);
- }
-
- var esm = lambdaService.createEventSourceMapping(region, req);
- r.setPhysicalId(esm.getUuid());
- r.getAttributes().put("Id", esm.getUuid());
- }
-
// ── Pipes ──────────────────────────────────────────────────────────────────
private void provisionStepFunctionsStateMachine(StackResource r, JsonNode props,
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisioner.java
new file mode 100644
index 0000000000..e7279b2966
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisioner.java
@@ -0,0 +1,183 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for {@code AWS::Lambda::EventSourceMapping}.
+ */
+@ApplicationScoped
+public class LambdaEventSourceMappingCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private final LambdaService lambdaService;
+
+ @Inject
+ public LambdaEventSourceMappingCfnProvisioner(LambdaService lambdaService) {
+ this.lambdaService = lambdaService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of("AWS::Lambda::EventSourceMapping");
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ if (!"AWS::Lambda::EventSourceMapping".equals(r.getResourceType())) {
+ throw new IllegalStateException(
+ "LambdaEventSourceMappingCfnProvisioner cannot handle " + r.getResourceType());
+ }
+
+ Map<String, Object> req = new HashMap<>();
+ String functionName = ctx.resolveOptional(props, "FunctionName");
+ if (functionName == null || functionName.isBlank()) {
+ throw new AwsException("ValidationError",
+ "Property FunctionName is required for AWS::Lambda::EventSourceMapping", 400);
+ }
+ req.put("FunctionName", functionName);
+
+ String eventSourceArn = ctx.resolveOptional(props, "EventSourceArn");
+ if (eventSourceArn != null) {
+ req.put("EventSourceArn", eventSourceArn);
+ }
+
+ String enabledStr = ctx.resolveOptional(props, "Enabled");
+ if (enabledStr != null) {
+ req.put("Enabled", Boolean.parseBoolean(enabledStr));
+ }
+
+ String batchSize = ctx.resolveOptional(props, "BatchSize");
+ if (batchSize != null) {
+ try {
+ req.put("BatchSize", Integer.parseInt(batchSize));
+ } catch (NumberFormatException e) {
+ throw new AwsException("ValidationError",
+ "Value of property BatchSize must be an integer.", 400);
+ }
+ }
+
+ String startingPosition = ctx.resolveOptional(props, "StartingPosition");
+ if (startingPosition != null) {
+ req.put("StartingPosition", startingPosition);
+ }
+
+ String startingPositionTimestamp = ctx.resolveOptional(props, "StartingPositionTimestamp");
+ if (startingPositionTimestamp != null) {
+ try {
+ double timestamp = Double.parseDouble(startingPositionTimestamp);
+ if (!Double.isFinite(timestamp)) {
+ throw new NumberFormatException("Non-finite timestamp");
+ }
+ req.put("StartingPositionTimestamp", timestamp);
+ } catch (NumberFormatException e) {
+ throw new AwsException("ValidationError",
+ "Value of property StartingPositionTimestamp must be a number.", 400);
+ }
+ }
+
+ List<String> functionResponseTypes = ctx.resolveStringList(props, "FunctionResponseTypes");
+ if (!functionResponseTypes.isEmpty()) {
+ req.put("FunctionResponseTypes", functionResponseTypes);
+ }
+
+ if (props != null && props.has("SelfManagedEventSource")) {
+ JsonNode resolvedSource = ctx.engine().resolveNode(props.get("SelfManagedEventSource"));
+ if (resolvedSource != null && !resolvedSource.isNull()) {
+ req.put("SelfManagedEventSource", MAPPER.convertValue(resolvedSource, Map.class));
+ }
+ }
+
+ List<String> topics = ctx.resolveStringList(props, "Topics");
+ if (!topics.isEmpty()) {
+ req.put("Topics", topics);
+ }
+
+ if (props != null && props.has("SourceAccessConfigurations") && !props.get("SourceAccessConfigurations").isNull()) {
+ JsonNode resolvedAccess = ctx.engine().resolveNode(props.get("SourceAccessConfigurations"));
+ if (resolvedAccess != null && !resolvedAccess.isNull()) {
+ req.put("SourceAccessConfigurations", MAPPER.convertValue(resolvedAccess, List.class));
+ }
+ } else if (ctx.isUpdate()) {
+ req.put("SourceAccessConfigurations", null);
+ }
+
+ if (ctx.isUpdate() && ctx.priorPhysicalId() != null) {
+ String uuid = ctx.priorPhysicalId();
+ EventSourceMapping existing = findExisting(uuid);
+ if (existing != null) {
+ rejectIfChanged("EventSourceArn", existing.getEventSourceArn(), (String) req.get("EventSourceArn"));
+ rejectIfChanged("StartingPosition", existing.getStartingPosition(), (String) req.get("StartingPosition"));
+
+ Long existingTs = existing.getStartingPositionTimestamp();
+ Long requestedTs = req.get("StartingPositionTimestamp") instanceof Number num
+ ? Math.round(num.doubleValue() * 1000.0)
+ : null;
+ if (!Objects.equals(existingTs, requestedTs)) {
+ throw new AwsException("ValidationError",
+ "Updating StartingPositionTimestamp requires resource replacement, which is not supported.", 400);
+ }
+
+ if (!Objects.equals(existing.getSelfManagedEventSource(), req.get("SelfManagedEventSource"))) {
+ throw new AwsException("ValidationError",
+ "Updating SelfManagedEventSource requires resource replacement, which is not supported.", 400);
+ }
+ }
+ lambdaService.updateEventSourceMapping(uuid, req);
+ String esmArn = AwsArnUtils.Arn.of("lambda", ctx.region(), ctx.accountId(), "event-source-mapping:" + uuid).toString();
+ r.setPhysicalId(uuid);
+ r.getAttributes().put("Id", uuid);
+ r.getAttributes().put("EventSourceMappingArn", esmArn);
+ } else {
+ var esm = lambdaService.createEventSourceMapping(ctx.region(), req);
+ String esmArn = AwsArnUtils.Arn.of("lambda", ctx.region(), ctx.accountId(), "event-source-mapping:" + esm.getUuid()).toString();
+ r.setPhysicalId(esm.getUuid());
+ r.getAttributes().put("Id", esm.getUuid());
+ r.getAttributes().put("EventSourceMappingArn", esmArn);
+ }
+ }
+
+ private EventSourceMapping findExisting(String uuid) {
+ try {
+ return lambdaService.getEventSourceMapping(uuid);
+ } catch (AwsException e) {
+ if ("ResourceNotFoundException".equals(e.getErrorCode())) {
+ return null;
+ }
+ throw e;
+ }
+ }
+
+ private void rejectIfChanged(String property, String existing, String requested) {
+ String a = existing == null || existing.isBlank() ? null : existing;
+ String b = requested == null || requested.isBlank() ? null : requested;
+ if (Objects.equals(a, b)) {
+ return;
+ }
+ throw new AwsException("ValidationError",
+ "Updating " + property + " requires resource replacement, which is not supported.", 400);
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (!"AWS::Lambda::EventSourceMapping".equals(resourceType) || physicalId == null) {
+ return;
+ }
+ CfnDeletes.safeDelete("event source mapping", physicalId,
+ () -> lambdaService.deleteEventSourceMapping(physicalId), "ResourceNotFoundException");
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
index f60d02be7b..9a06dbdd8f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
@@ -341,11 +341,13 @@ public class LambdaController {
return Response.status(202).entity(buildEsmResponse(esm)).build();
}
- private Map<String, Object> buildEsmResponse(EventSourceMapping esm) {
+ Map<String, Object> buildEsmResponse(EventSourceMapping esm) {
ObjectNode node = objectMapper.createObjectNode();
node.put("UUID", esm.getUuid());
node.put("FunctionArn", esm.getFunctionArn());
- node.put("EventSourceArn", esm.getEventSourceArn());
+ if (esm.getEventSourceArn() != null) {
+ node.put("EventSourceArn", esm.getEventSourceArn());
+ }
node.put("BatchSize", esm.getBatchSize());
node.put("State", esm.getState());
node.put("LastModified", (double) esm.getLastModified() / 1000.0);
@@ -370,6 +372,19 @@ public class LambdaController {
onFailure.put("Destination", esm.getDestinationConfig().getOnFailure().getDestination());
}
+ if (esm.getSelfManagedEventSource() != null) {
+ node.set("SelfManagedEventSource", objectMapper.valueToTree(esm.getSelfManagedEventSource()));
+ }
+
+ if (esm.getTopics() != null && !esm.getTopics().isEmpty()) {
+ ArrayNode topicsNode = node.putArray("Topics");
+ esm.getTopics().forEach(topicsNode::add);
+ }
+
+ if (esm.getSourceAccessConfigurations() != null && !esm.getSourceAccessConfigurations().isEmpty()) {
+ node.set("SourceAccessConfigurations", objectMapper.valueToTree(esm.getSourceAccessConfigurations()));
+ }
+
if (esm.getFunctionResponseTypes() != null) {
esm.getFunctionResponseTypes().forEach(responseTypes::add);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
index 40f8a3f848..2c0422804b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
@@ -162,8 +162,8 @@ public class LambdaService implements ResourceProvider {
this.zipExtractor = zipExtractor;
this.config = config;
this.regionResolver = regionResolver;
- this.esmStore = null;
- this.aliasStore = null;
+ this.esmStore = storageFactory != null ? new EsmStore(storageFactory) : null;
+ this.aliasStore = storageFactory != null ? new LambdaAliasStore(storageFactory) : null;
this.s3Service = null;
this.sqsService = null;
this.poller = null;
@@ -555,6 +555,28 @@ public class LambdaService implements ResourceProvider {
}
}
+ private record ResolvedFunctionTarget(String functionArn, String functionName) {}
+
+ private ResolvedFunctionTarget resolveFunctionTarget(String region, LambdaArnUtils.ResolvedFunctionRef fnRef) {
+ String name = fnRef.name();
+ LambdaFunction fn = getFunction(region, name);
+ String qualifier = fnRef.qualifier();
+ if (qualifier == null) {
+ return new ResolvedFunctionTarget(fn.getFunctionArn(), name);
+ }
+ if ("$LATEST".equals(qualifier)) {
+ return new ResolvedFunctionTarget(fn.getFunctionArn() + ":$LATEST", name);
+ }
+ if (qualifier.chars().allMatch(Character::isDigit)) {
+ LambdaFunction versionFn = functionStore.get(region, name, qualifier)
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",
+ "Function version not found: " + name + ":" + qualifier, 404));
+ return new ResolvedFunctionTarget(versionFn.getFunctionArn(), name);
+ }
+ LambdaAlias alias = getAlias(region, name, qualifier);
+ return new ResolvedFunctionTarget(alias.getAliasArn(), name);
+ }
+
public List<LambdaFunction> listFunctions(String region) {
return functionStore.list(region);
}
@@ -1047,42 +1069,132 @@ public class LambdaService implements ResourceProvider {
validateEventSourceMappingStructures(request);
String functionName = (String) request.get("FunctionName");
- String eventSourceArn = (String) request.get("EventSourceArn");
-
if (functionName == null || functionName.isBlank()) {
throw new AwsException("InvalidParameterValueException", "FunctionName is required", 400);
}
- if (eventSourceArn == null || eventSourceArn.isBlank()) {
- throw new AwsException("InvalidParameterValueException", "EventSourceArn is required", 400);
- }
- if (!eventSourceArn.contains(":sqs:") && !eventSourceArn.contains(":kinesis:")
- && !eventSourceArn.contains(":dynamodb:")) {
- throw new AwsException("InvalidParameterValueException",
- "Only SQS, Kinesis, and DynamoDB Streams event sources are supported.", 400);
- }
// Resolve function — supports bare name, partial ARN, or full ARN
LambdaArnUtils.ResolvedFunctionRef fnRef = LambdaArnUtils.resolve(functionName);
String resolvedName = fnRef.name();
- // Extract region from the event source ARN (parts[3] for all supported ARN formats)
+ boolean hasKafkaSource = request.containsKey("SelfManagedEventSource") && request.get("SelfManagedEventSource") != null;
+ boolean hasTopics = request.containsKey("Topics") && request.get("Topics") != null;
+ boolean hasEventSourceArn = request.containsKey("EventSourceArn") && request.get("EventSourceArn") != null;
+ boolean isSelfManagedKafka = hasKafkaSource || hasTopics;
+
+ String eventSourceArn;
String resolvedRegion;
- if (eventSourceArn.contains(":sqs:")) {
- resolvedRegion = SqsEventSourcePoller.regionFromArn(eventSourceArn);
+ Map<String, Object> selfManagedEventSource = null;
+ List<String> topics = null;
+ List<Map<String, Object>> sourceAccessConfigurations = null;
+
+ if (isSelfManagedKafka) {
+ if (hasEventSourceArn) {
+ throw new AwsException("InvalidParameterValueException",
+ "Cannot specify both EventSourceArn and SelfManagedEventSource/Topics", 400);
+ }
+ if (!hasKafkaSource) {
+ throw new AwsException("InvalidParameterValueException",
+ "SelfManagedEventSource is required for self-managed Apache Kafka event sources", 400);
+ }
+ if (!hasTopics) {
+ throw new AwsException("InvalidParameterValueException",
+ "Topics is required for self-managed Apache Kafka event sources", 400);
+ }
+ eventSourceArn = null;
+
+ enforceRegion(region, fnRef);
+ resolvedRegion = region;
+
+ Object rawSource = request.get("SelfManagedEventSource");
+ if (!(rawSource instanceof Map<?, ?> sourceMap)) {
+ throw new AwsException("InvalidParameterValueException",
+ "SelfManagedEventSource must be a JSON object", 400);
+ }
+ Object rawEndpoints = sourceMap.get("Endpoints");
+ if (!(rawEndpoints instanceof Map<?, ?> endpointsMap)) {
+ throw new AwsException("InvalidParameterValueException",
+ "SelfManagedEventSource must contain Endpoints", 400);
+ }
+ Object rawServers = endpointsMap.get("KAFKA_BOOTSTRAP_SERVERS");
+ if (!(rawServers instanceof List<?> serverList) || serverList.isEmpty()) {
+ throw new AwsException("InvalidParameterValueException",
+ "SelfManagedEventSource must contain KAFKA_BOOTSTRAP_SERVERS", 400);
+ }
+ for (Object server : serverList) {
+ if (!(server instanceof String s) || s.isBlank()) {
+ throw new AwsException("InvalidParameterValueException",
+ "KAFKA_BOOTSTRAP_SERVERS elements must be non-blank strings", 400);
+ }
+ }
+ @SuppressWarnings("unchecked")
+ Map<String, Object> typedSource = (Map<String, Object>) rawSource;
+ selfManagedEventSource = typedSource;
+
+ Object rawTopics = request.get("Topics");
+ if (!(rawTopics instanceof List<?> topicList) || topicList.isEmpty()) {
+ throw new AwsException("InvalidParameterValueException",
+ "Topics must be a non-empty list of strings", 400);
+ }
+ List<String> validatedTopics = new ArrayList<>();
+ for (Object item : topicList) {
+ if (!(item instanceof String s) || s.isBlank()) {
+ throw new AwsException("InvalidParameterValueException",
+ "Topics elements must be non-blank strings", 400);
+ }
+ validatedTopics.add(s);
+ }
+ topics = validatedTopics;
+
+ if (request.containsKey("SourceAccessConfigurations")) {
+ Object rawAccess = request.get("SourceAccessConfigurations");
+ if (rawAccess != null) {
+ if (!(rawAccess instanceof List<?> accessList)) {
+ throw new AwsException("InvalidParameterValueException",
+ "SourceAccessConfigurations must be a list", 400);
+ }
+ List<Map<String, Object>> typedAccess = new ArrayList<>();
+ for (Object item : accessList) {
+ if (!(item instanceof Map<?, ?> m)) {
+ throw new AwsException("InvalidParameterValueException",
+ "SourceAccessConfiguration entries must be JSON objects", 400);
+ }
+ @SuppressWarnings("unchecked")
+ Map<String, Object> typedMap = (Map<String, Object>) m;
+ typedAccess.add(typedMap);
+ }
+ sourceAccessConfigurations = typedAccess;
+ }
+ }
} else {
- // arn:aws:kinesis:region:... or arn:aws:dynamodb:region:...
- resolvedRegion = AwsArnUtils.regionOrDefault(eventSourceArn, region);
- }
+ eventSourceArn = (String) request.get("EventSourceArn");
+ if (eventSourceArn == null || eventSourceArn.isBlank()) {
+ throw new AwsException("InvalidParameterValueException", "EventSourceArn is required", 400);
+ }
+ if (!eventSourceArn.contains(":sqs:") && !eventSourceArn.contains(":kinesis:")
+ && !eventSourceArn.contains(":dynamodb:")) {
+ throw new AwsException("InvalidParameterValueException",
+ "Only SQS, Kinesis, and DynamoDB Streams event sources are supported.", 400);
+ }
- // If the caller supplied a full function ARN, its region must agree
- // with the region derived from the event source ARN. Otherwise we'd
- // silently bind a different-region function of the same name.
- if (fnRef.region() != null && !fnRef.region().equals(resolvedRegion)) {
- throw new AwsException("InvalidParameterValueException",
- "Function ARN region '" + fnRef.region() + "' does not match event source region '" + resolvedRegion + "'", 400);
+ // Extract region from the event source ARN (parts[3] for all supported ARN formats)
+ if (eventSourceArn.contains(":sqs:")) {
+ resolvedRegion = SqsEventSourcePoller.regionFromArn(eventSourceArn);
+ } else {
+ // arn:aws:kinesis:region:... or arn:aws:dynamodb:region:...
+ resolvedRegion = AwsArnUtils.regionOrDefault(eventSourceArn, region);
+ }
+
+ // If the caller supplied a full function ARN, its region must agree
+ // with the region derived from the event source ARN. Otherwise we'd
+ // silently bind a different-region function of the same name.
+ if (fnRef.region() != null && !fnRef.region().equals(resolvedRegion)) {
+ throw new AwsException("InvalidParameterValueException",
+ "Function ARN region '" + fnRef.region() + "' does not match event source region '" + resolvedRegion + "'", 400);
+ }
}
- LambdaFunction fn = getFunction(resolvedRegion, resolvedName);
+ ResolvedFunctionTarget target = resolveFunctionTarget(resolvedRegion, fnRef);
int batchSize = toInt(request.get("BatchSize"), 10);
boolean enabled = !Boolean.FALSE.equals(request.get("Enabled"));
@@ -1102,15 +1214,17 @@ public class LambdaService implements ResourceProvider {
EventSourceMapping.FilterCriteria filterCriteria = parseFilterCriteria(request, objectMapper);
- StartingPositionSpec startingPosition = parseStartingPosition(request, eventSourceArn);
+ StartingPositionSpec startingPosition = parseStartingPosition(request, eventSourceArn, isSelfManagedKafka);
- String queueUrl = eventSourceArn.contains(":sqs:") ? AwsArnUtils.arnToQueueUrl(eventSourceArn, config.effectiveBaseUrl()) : null;
+ String queueUrl = (eventSourceArn != null && eventSourceArn.contains(":sqs:"))
+ ? AwsArnUtils.arnToQueueUrl(eventSourceArn, config != null ? config.effectiveBaseUrl() : null)
+ : null;
EventSourceMapping esm = new EventSourceMapping();
esm.setUuid(UUID.randomUUID().toString());
esm.setAccountId(regionResolver.getAccountId());
- esm.setFunctionArn(fn.getFunctionArn());
- esm.setFunctionName(resolvedName);
+ esm.setFunctionArn(target.functionArn());
+ esm.setFunctionName(target.functionName());
esm.setEventSourceArn(eventSourceArn);
esm.setQueueUrl(queueUrl);
esm.setRegion(resolvedRegion);
@@ -1124,6 +1238,9 @@ public class LambdaService implements ResourceProvider {
esm.setFilterCriteria(filterCriteria);
esm.setStartingPosition(startingPosition.position());
esm.setStartingPositionTimestamp(startingPosition.timestampMillis());
+ esm.setSelfManagedEventSource(selfManagedEventSource);
+ esm.setTopics(topics);
+ esm.setSourceAccessConfigurations(sourceAccessConfigurations);
esm.setLastModified(System.currentTimeMillis());
esmStore.save(esm);
@@ -1393,7 +1510,7 @@ public class LambdaService implements ResourceProvider {
* requests that used to succeed. There is no update counterpart because AWS's
* UpdateEventSourceMapping does not accept the field at all - it is replace-only.
*/
- private StartingPositionSpec parseStartingPosition(Map<String, Object> request, String eventSourceArn) {
+ private StartingPositionSpec parseStartingPosition(Map<String, Object> request, String eventSourceArn, boolean isSelfManagedKafka) {
Object raw = request.get("StartingPosition");
if (raw == null) {
return new StartingPositionSpec(null, null);
@@ -1409,12 +1526,13 @@ public class LambdaService implements ResourceProvider {
if (!"AT_TIMESTAMP".equals(position)) {
return new StartingPositionSpec(position, null);
}
- // AT_TIMESTAMP is Kinesis-only among the event sources Floci supports - DynamoDB Streams
- // shard iterators have no timestamp form at all, so silently accepting it there would
- // promise a starting point that can never be honoured.
- if (eventSourceArn != null && !eventSourceArn.contains(":kinesis:")) {
+ // AT_TIMESTAMP is supported for Amazon Kinesis and self-managed Apache Kafka event sources -
+ // DynamoDB Streams shard iterators have no timestamp form at all, so silently accepting it there
+ // would promise a starting point that can never be honoured.
+ boolean isKinesis = eventSourceArn != null && eventSourceArn.contains(":kinesis:");
+ if (!isKinesis && !isSelfManagedKafka) {
throw new AwsException("InvalidParameterValueException",
- "AT_TIMESTAMP is only supported for Amazon Kinesis event sources", 400);
+ "AT_TIMESTAMP is only supported for Amazon Kinesis and self-managed Apache Kafka event sources", 400);
}
Object rawTimestamp = request.get("StartingPositionTimestamp");
if (rawTimestamp == null) {
@@ -1473,6 +1591,9 @@ public class LambdaService implements ResourceProvider {
}
private void startPollingHelper(EventSourceMapping esm) {
+ if (esm.getEventSourceArn() == null) {
+ return;
+ }
if (esm.getEventSourceArn().contains(":sqs:")) {
poller.startPolling(esm);
} else if (esm.getEventSourceArn().contains(":kinesis:")) {
@@ -1483,6 +1604,9 @@ public class LambdaService implements ResourceProvider {
}
private void stopPollingHelper(EventSourceMapping esm) {
+ if (esm.getEventSourceArn() == null) {
+ return;
+ }
if (esm.getEventSourceArn().contains(":sqs:")) {
poller.stopPolling(esm.getUuid());
} else if (esm.getEventSourceArn().contains(":kinesis:")) {
@@ -1544,6 +1668,60 @@ public class LambdaService implements ResourceProvider {
esm.setFilterCriteria(parseFilterCriteria(request, objectMapper));
}
+ if (request.containsKey("FunctionName")) {
+ String fnName = (String) request.get("FunctionName");
+ if (fnName != null && !fnName.isBlank()) {
+ LambdaArnUtils.ResolvedFunctionRef fnRef = LambdaArnUtils.resolve(fnName);
+ if (fnRef.region() != null && !fnRef.region().equals(esm.getRegion())) {
+ throw new AwsException("InvalidParameterValueException",
+ "Function ARN region '" + fnRef.region() + "' does not match event source region '" + esm.getRegion() + "'", 400);
+ }
+ ResolvedFunctionTarget target = resolveFunctionTarget(esm.getRegion(), fnRef);
+ esm.setFunctionArn(target.functionArn());
+ esm.setFunctionName(target.functionName());
+ }
+ }
+
+ if (request.containsKey("Topics")) {
+ Object rawTopics = request.get("Topics");
+ if (!(rawTopics instanceof List<?> topicList) || topicList.isEmpty()) {
+ throw new AwsException("InvalidParameterValueException",
+ "Topics must be a non-empty list of strings", 400);
+ }
+ List<String> validatedTopics = new ArrayList<>();
+ for (Object item : topicList) {
+ if (!(item instanceof String s) || s.isBlank()) {
+ throw new AwsException("InvalidParameterValueException",
+ "Topics elements must be non-blank strings", 400);
+ }
+ validatedTopics.add(s);
+ }
+ esm.setTopics(validatedTopics);
+ }
+
+ if (request.containsKey("SourceAccessConfigurations")) {
+ Object rawAccess = request.get("SourceAccessConfigurations");
+ if (rawAccess != null) {
+ if (!(rawAccess instanceof List<?> accessList)) {
+ throw new AwsException("InvalidParameterValueException",
+ "SourceAccessConfigurations must be a list", 400);
+ }
+ List<Map<String, Object>> typedAccess = new ArrayList<>();
+ for (Object item : accessList) {
+ if (!(item instanceof Map<?, ?> m)) {
+ throw new AwsException("InvalidParameterValueException",
+ "SourceAccessConfiguration entries must be JSON objects", 400);
+ }
+ @SuppressWarnings("unchecked")
+ Map<String, Object> typedMap = (Map<String, Object>) m;
+ typedAccess.add(typedMap);
+ }
+ esm.setSourceAccessConfigurations(typedAccess);
+ } else {
+ esm.setSourceAccessConfigurations(null);
+ }
+ }
+
esm.setLastModified(System.currentTimeMillis());
esmStore.save(esm);
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java
index a2946bf109..915ffc6512 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java
@@ -32,6 +32,9 @@ public class EventSourceMapping {
private Boolean bisectBatchOnFunctionError;
private DestinationConfig destinationConfig;
private FilterCriteria filterCriteria;
+ private Map<String, Object> selfManagedEventSource;
+ private List<String> topics = new ArrayList<>();
+ private List<Map<String, Object>> sourceAccessConfigurations = new ArrayList<>();
public EventSourceMapping() {
}
@@ -124,6 +127,30 @@ public class EventSourceMapping {
this.filterCriteria = filterCriteria;
}
+ public Map<String, Object> getSelfManagedEventSource() {
+ return selfManagedEventSource;
+ }
+
+ public void setSelfManagedEventSource(Map<String, Object> selfManagedEventSource) {
+ this.selfManagedEventSource = selfManagedEventSource;
+ }
+
+ public List<String> getTopics() {
+ return topics;
+ }
+
+ public void setTopics(List<String> topics) {
+ this.topics = topics != null ? topics : new ArrayList<>();
+ }
+
+ public List<Map<String, Object>> getSourceAccessConfigurations() {
+ return sourceAccessConfigurations;
+ }
+
+ public void setSourceAccessConfigurations(List<Map<String, Object>> sourceAccessConfigurations) {
+ this.sourceAccessConfigurations = sourceAccessConfigurations != null ? sourceAccessConfigurations : new ArrayList<>();
+ }
+
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class DestinationConfig {
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index 3a78aac487..959cb77fa8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -42,6 +42,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.IotDomain
import io.github.hectorvent.floci.services.cloudformation.provisioners.KinesisCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.KmsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaAddressingCfnProvisioner;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEventSourceMappingCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaVersionAliasCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.PipesCfnProvisioner;
@@ -245,6 +246,7 @@ final class CfnProvisionerFixture {
if (lambdaService != null) {
discovered.add(new LambdaAddressingCfnProvisioner(lambdaService));
discovered.add(new LambdaVersionAliasCfnProvisioner(lambdaService));
+ discovered.add(new LambdaEventSourceMappingCfnProvisioner(lambdaService));
}
if (flowLogService != null) {
discovered.add(new Ec2FlowLogCfnProvisioner(flowLogService));
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
index 3b28b9f270..fcc888ced5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
@@ -4790,6 +4790,160 @@ class CloudFormationIntegrationTest {
.statusCode(404);
}
+ @Test
+ void createStack_lambdaEventSourceMappingKafka() throws Exception {
+ String stackName = "cfn-esm-kafka-stack";
+ String funcName = "cfn-esm-kafka-func";
+
+ String template = """
+ {
+ "Resources": {
+ "MyFunction": {
+ "Type": "AWS::Lambda::Function",
+ "Properties": {
+ "FunctionName": "%s",
+ "Runtime": "nodejs20.x",
+ "Handler": "index.handler",
+ "Role": "arn:aws:iam::000000000000:role/lambda-role",
+ "Code": {
+ "ZipFile": "exports.handler = async (e) => ({ statusCode: 200 });"
+ }
+ }
+ },
+ "MyKafkaESM": {
+ "Type": "AWS::Lambda::EventSourceMapping",
+ "Properties": {
+ "FunctionName": { "Ref": "MyFunction" },
+ "Enabled": true,
+ "BatchSize": 100,
+ "Topics": ["orders-topic", "events-topic"],
+ "SelfManagedEventSource": {
+ "Endpoints": {
+ "KAFKA_BOOTSTRAP_SERVERS": ["kafka-broker-1:9092", "kafka-broker-2:9092"]
+ }
+ },
+ "SourceAccessConfigurations": [
+ {
+ "Type": "SASL_SCRAM_512_AUTH",
+ "URI": "arn:aws:secretsmanager:us-east-1:000000000000:secret:kafka-auth"
+ }
+ ]
+ }
+ }
+ },
+ "Outputs": {
+ "EsmId": {
+ "Value": { "Fn::GetAtt": ["MyKafkaESM", "Id"] }
+ },
+ "EsmArn": {
+ "Value": { "Fn::GetAtt": ["MyKafkaESM", "EventSourceMappingArn"] }
+ },
+ "EsmRef": {
+ "Value": { "Ref": "MyKafkaESM" }
+ }
+ }
+ }
+ """.formatted(funcName);
+
+ // 1. Create stack
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackId>"));
+
+ // 2. Stack must reach CREATE_COMPLETE
+ String describeXml = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
+ .extract().body().asString();
+
+ String getAttId = outputValue(describeXml, "EsmId");
+ String getAttArn = outputValue(describeXml, "EsmArn");
+ String getAttRef = outputValue(describeXml, "EsmRef");
+
+ // 3. Lambda list-event-source-mappings must return our ESM with Kafka properties populated
+ String esmJson = given()
+ .when()
+ .get("/2015-03-31/event-source-mappings?FunctionName=" + funcName)
+ .then()
+ .statusCode(200)
+ .body(containsString(funcName))
+ .extract().body().asString();
+
+ JsonNode esmList = OBJECT_MAPPER.readTree(esmJson);
+ assertEquals(1, esmList.path("EventSourceMappings").size());
+ JsonNode esmNode = esmList.path("EventSourceMappings").get(0);
+ String esmUuid = esmNode.path("UUID").asText();
+
+ // Verify Fn::GetAtt attributes and Ref
+ assertEquals(esmUuid, getAttId);
+ assertEquals(esmUuid, getAttRef);
+ assertEquals("arn:aws:lambda:us-east-1:000000000000:event-source-mapping:" + esmUuid, getAttArn);
+
+ // Verify Topics
+ JsonNode topics = esmNode.path("Topics");
+ assertTrue(topics.isArray() && topics.size() == 2);
+ assertEquals("orders-topic", topics.get(0).asText());
+ assertEquals("events-topic", topics.get(1).asText());
+
+ // Verify SelfManagedEventSource
+ JsonNode smes = esmNode.path("SelfManagedEventSource");
+ assertTrue(smes.isObject());
+ JsonNode endpoints = smes.path("Endpoints").path("KAFKA_BOOTSTRAP_SERVERS");
+ assertTrue(endpoints.isArray() && endpoints.size() == 2);
+ assertEquals("kafka-broker-1:9092", endpoints.get(0).asText());
+
+ // Verify SourceAccessConfigurations
+ JsonNode accessConfigs = esmNode.path("SourceAccessConfigurations");
+ assertTrue(accessConfigs.isArray() && accessConfigs.size() == 1);
+ assertEquals("SASL_SCRAM_512_AUTH", accessConfigs.get(0).path("Type").asText());
+ assertEquals("arn:aws:secretsmanager:us-east-1:000000000000:secret:kafka-auth", accessConfigs.get(0).path("URI").asText());
+
+ // 4. Delete stack
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ long deadline = System.currentTimeMillis() + 10_000;
+ while (System.currentTimeMillis() < deadline) {
+ String deleteStatus = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .extract().body().asString();
+ if (deleteStatus.contains("DELETE_COMPLETE") || deleteStatus.contains("does not exist")) {
+ break;
+ }
+ Thread.sleep(200);
+ }
+
+ given()
+ .when()
+ .get("/2015-03-31/event-source-mappings/" + esmUuid)
+ .then()
+ .statusCode(404);
+ }
+
@Test
void createStack_lambdaEventSourceMappingWithStartingPosition() {
String stackName = "cfn-esm-starting-position-stack";
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisionerTest.java
new file mode 100644
index 0000000000..f6fd05fbcb
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisionerTest.java
@@ -0,0 +1,392 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+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.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class LambdaEventSourceMappingCfnProvisionerTest {
+
+ private final LambdaService lambdaService = mock(LambdaService.class);
+ private final LambdaEventSourceMappingCfnProvisioner provisioner =
+ new LambdaEventSourceMappingCfnProvisioner(lambdaService);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ return ctx(false, null);
+ }
+
+ private ProvisionContext ctx(boolean isUpdate, String priorPhysicalId) {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ if (node == null) {
+ return null;
+ }
+ if (node.isObject() && node.has("Ref")) {
+ return "resolved-" + node.get("Ref").asText();
+ }
+ return node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> resolveMockNode((JsonNode) inv.getArgument(0), engine));
+
+ ProvisionContext context = mock(ProvisionContext.class);
+ when(context.engine()).thenReturn(engine);
+ when(context.region()).thenReturn("us-east-1");
+ when(context.accountId()).thenReturn("000000000000");
+ when(context.stackName()).thenReturn("test-stack");
+ when(context.isUpdate()).thenReturn(isUpdate);
+ when(context.priorPhysicalId()).thenReturn(priorPhysicalId);
+
+ when(context.resolveOptional(any(), anyString())).thenAnswer(inv -> {
+ JsonNode props = inv.getArgument(0);
+ String propName = inv.getArgument(1);
+ return (props != null && props.has(propName)) ? engine.resolve(props.get(propName)) : null;
+ });
+ when(context.resolveStringList(any(), anyString())).thenAnswer(inv -> {
+ JsonNode props = inv.getArgument(0);
+ String propName = inv.getArgument(1);
+ if (props == null || !props.has(propName) || !props.get(propName).isArray()) {
+ return List.of();
+ }
+ java.util.List<String> list = new java.util.ArrayList<>();
+ for (JsonNode elem : props.get(propName)) {
+ list.add(elem.isTextual() ? elem.asText() : engine.resolve(elem));
+ }
+ return list;
+ });
+
+ return context;
+ }
+
+ private JsonNode resolveMockNode(JsonNode node, CloudFormationTemplateEngine engine) {
+ if (node == null || node.isNull() || node.isMissingNode() || node.isValueNode()) {
+ return node;
+ }
+ if (node.isObject()) {
+ if (node.has("Ref")) {
+ return mapper.getNodeFactory().textNode(engine.resolve(node));
+ }
+ ObjectNode resolved = mapper.createObjectNode();
+ node.fields().forEachRemaining(e -> resolved.set(e.getKey(), resolveMockNode(e.getValue(), engine)));
+ return resolved;
+ }
+ if (node.isArray()) {
+ var arr = mapper.createArrayNode();
+ for (JsonNode item : node) {
+ arr.add(resolveMockNode(item, engine));
+ }
+ return arr;
+ }
+ return node;
+ }
+
+ @Test
+ void resourceTypesReturnsEventSourceMapping() {
+ assertEquals(Set.of("AWS::Lambda::EventSourceMapping"), provisioner.resourceTypes());
+ }
+
+ @Test
+ void provisionCreatesConventionalEventSourceMapping() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("EventSourceArn", "arn:aws:sqs:us-east-1:000000000000:my-queue");
+ props.put("BatchSize", "5");
+ props.put("Enabled", "true");
+ props.put("StartingPosition", "TRIM_HORIZON");
+
+ EventSourceMapping esm = new EventSourceMapping();
+ esm.setUuid("test-esm-uuid-1234");
+ when(lambdaService.createEventSourceMapping(eq("us-east-1"), any())).thenReturn(esm);
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("test-esm-uuid-1234", r.getPhysicalId());
+ assertEquals("test-esm-uuid-1234", r.getAttributes().get("Id"));
+ assertEquals("arn:aws:lambda:us-east-1:000000000000:event-source-mapping:test-esm-uuid-1234",
+ r.getAttributes().get("EventSourceMappingArn"));
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(lambdaService).createEventSourceMapping(eq("us-east-1"), captor.capture());
+ Map<String, Object> req = captor.getValue();
+ assertEquals("my-function", req.get("FunctionName"));
+ assertEquals("arn:aws:sqs:us-east-1:000000000000:my-queue", req.get("EventSourceArn"));
+ assertEquals(5, req.get("BatchSize"));
+ assertEquals(true, req.get("Enabled"));
+ assertEquals("TRIM_HORIZON", req.get("StartingPosition"));
+ }
+
+ @Test
+ void provisionResolvesNestedIntrinsicsForKafka() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-kafka-function");
+
+ ObjectNode selfManaged = mapper.createObjectNode();
+ ObjectNode endpoints = mapper.createObjectNode();
+ endpoints.putObject("KAFKA_BOOTSTRAP_SERVERS");
+ // Nested Ref in Endpoints
+ ObjectNode refNode = mapper.createObjectNode();
+ refNode.put("Ref", "MyBootstrapParam");
+ endpoints.set("KAFKA_BOOTSTRAP_SERVERS", mapper.createArrayNode().add(refNode));
+ selfManaged.set("Endpoints", endpoints);
+ props.set("SelfManagedEventSource", selfManaged);
+
+ props.set("Topics", mapper.createArrayNode().add("my-topic"));
+
+ EventSourceMapping esm = new EventSourceMapping();
+ esm.setUuid("kafka-esm-uuid");
+ when(lambdaService.createEventSourceMapping(eq("us-east-1"), any())).thenReturn(esm);
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("kafka-esm-uuid", r.getPhysicalId());
+ assertEquals("kafka-esm-uuid", r.getAttributes().get("Id"));
+ assertEquals("arn:aws:lambda:us-east-1:000000000000:event-source-mapping:kafka-esm-uuid",
+ r.getAttributes().get("EventSourceMappingArn"));
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(lambdaService).createEventSourceMapping(eq("us-east-1"), captor.capture());
+ Map<String, Object> req = captor.getValue();
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> source = (Map<String, Object>) req.get("SelfManagedEventSource");
+ assertNotNull(source);
+ @SuppressWarnings("unchecked")
+ Map<String, Object> eps = (Map<String, Object>) source.get("Endpoints");
+ assertNotNull(eps);
+ @SuppressWarnings("unchecked")
+ List<String> servers = (List<String>) eps.get("KAFKA_BOOTSTRAP_SERVERS");
+ assertEquals(List.of("resolved-MyBootstrapParam"), servers);
+ }
+
+ @Test
+ void provisionUpdatesExistingEventSourceMapping() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+ r.setPhysicalId("existing-esm-uuid");
+ r.getAttributes().put("Id", "existing-esm-uuid");
+
+ EventSourceMapping existing = new EventSourceMapping();
+ existing.setUuid("existing-esm-uuid");
+ existing.setFunctionName("my-function");
+ when(lambdaService.getEventSourceMapping("existing-esm-uuid")).thenReturn(existing);
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("BatchSize", "20");
+ props.put("Enabled", "false");
+
+ provisioner.provision(r, props, ctx(true, "existing-esm-uuid"));
+
+ assertEquals("existing-esm-uuid", r.getPhysicalId());
+ assertEquals("existing-esm-uuid", r.getAttributes().get("Id"));
+ assertEquals("arn:aws:lambda:us-east-1:000000000000:event-source-mapping:existing-esm-uuid",
+ r.getAttributes().get("EventSourceMappingArn"));
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(lambdaService).updateEventSourceMapping(eq("existing-esm-uuid"), captor.capture());
+ verify(lambdaService, never()).createEventSourceMapping(anyString(), any());
+ Map<String, Object> req = captor.getValue();
+ assertEquals(20, req.get("BatchSize"));
+ assertEquals(false, req.get("Enabled"));
+ }
+
+ @Test
+ void deleteDeletesEventSourceMapping() {
+ provisioner.delete("AWS::Lambda::EventSourceMapping", "uuid-to-delete", "us-east-1");
+ verify(lambdaService).deleteEventSourceMapping("uuid-to-delete");
+ }
+
+ @Test
+ void deleteToleratesResourceNotFound() {
+ doThrow(new AwsException("ResourceNotFoundException", "ESM not found", 404))
+ .when(lambdaService).deleteEventSourceMapping("absent-uuid");
+
+ provisioner.delete("AWS::Lambda::EventSourceMapping", "absent-uuid", "us-east-1");
+ verify(lambdaService).deleteEventSourceMapping("absent-uuid");
+ }
+
+ @Test
+ void deletePropagatesNonResourceNotFoundExceptions() {
+ doThrow(new AwsException("InternalError", "boom", 500))
+ .when(lambdaService).deleteEventSourceMapping("broken-uuid");
+
+ assertThrows(AwsException.class,
+ () -> provisioner.delete("AWS::Lambda::EventSourceMapping", "broken-uuid", "us-east-1"));
+ }
+
+ @Test
+ void provisionRejectsMissingFunctionName() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> provisioner.provision(r, mapper.createObjectNode(), ctx()));
+ assertEquals("ValidationError", ex.getErrorCode());
+ assertEquals("Property FunctionName is required for AWS::Lambda::EventSourceMapping", ex.getMessage());
+ }
+
+ @Test
+ void provisionRejectsWrongResourceType() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::Function");
+ assertThrows(IllegalStateException.class, () -> provisioner.provision(r, mapper.createObjectNode(), ctx()));
+ }
+
+ @Test
+ void provisionRejectsInvalidBatchSize() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("BatchSize", "not-a-number");
+
+ AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+ assertEquals("ValidationError", ex.getErrorCode());
+ assertEquals("Value of property BatchSize must be an integer.", ex.getMessage());
+ }
+
+ @Test
+ void provisionUpdatesClearsSourceAccessConfigurationsWhenRemoved() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+ r.setPhysicalId("existing-esm-uuid");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+
+ provisioner.provision(r, props, ctx(true, "existing-esm-uuid"));
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(lambdaService).updateEventSourceMapping(eq("existing-esm-uuid"), captor.capture());
+ Map<String, Object> req = captor.getValue();
+ assertTrue(req.containsKey("SourceAccessConfigurations"));
+ assertNull(req.get("SourceAccessConfigurations"));
+ }
+
+ @Test
+ void provisionRejectsUpdatingSelfManagedEventSource() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+ r.setPhysicalId("existing-kafka-esm-uuid");
+
+ EventSourceMapping existing = new EventSourceMapping();
+ existing.setUuid("existing-kafka-esm-uuid");
+ existing.setSelfManagedEventSource(Map.of(
+ "Endpoints", Map.of("KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092"))
+ ));
+ when(lambdaService.getEventSourceMapping("existing-kafka-esm-uuid")).thenReturn(existing);
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-kafka-function");
+ ObjectNode selfManaged = mapper.createObjectNode();
+ ObjectNode endpoints = mapper.createObjectNode();
+ endpoints.set("KAFKA_BOOTSTRAP_SERVERS", mapper.createArrayNode().add("localhost:9093"));
+ selfManaged.set("Endpoints", endpoints);
+ props.set("SelfManagedEventSource", selfManaged);
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> provisioner.provision(r, props, ctx(true, "existing-kafka-esm-uuid")));
+ assertEquals("ValidationError", ex.getErrorCode());
+ assertEquals("Updating SelfManagedEventSource requires resource replacement, which is not supported.", ex.getMessage());
+ }
+
+ @Test
+ void provisionRejectsUpdatingEventSourceArn() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+ r.setPhysicalId("existing-esm-uuid");
+
+ EventSourceMapping existing = new EventSourceMapping();
+ existing.setUuid("existing-esm-uuid");
+ existing.setEventSourceArn("arn:aws:sqs:us-east-1:000000000000:old-queue");
+ when(lambdaService.getEventSourceMapping("existing-esm-uuid")).thenReturn(existing);
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("EventSourceArn", "arn:aws:sqs:us-east-1:000000000000:new-queue");
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> provisioner.provision(r, props, ctx(true, "existing-esm-uuid")));
+ assertEquals("ValidationError", ex.getErrorCode());
+ assertEquals("Updating EventSourceArn requires resource replacement, which is not supported.", ex.getMessage());
+ }
+
+ @Test
+ void provisionRejectsUpdatingStartingPosition() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+ r.setPhysicalId("existing-esm-uuid");
+
+ EventSourceMapping existing = new EventSourceMapping();
+ existing.setUuid("existing-esm-uuid");
+ existing.setStartingPosition("TRIM_HORIZON");
+ when(lambdaService.getEventSourceMapping("existing-esm-uuid")).thenReturn(existing);
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("StartingPosition", "LATEST");
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> provisioner.provision(r, props, ctx(true, "existing-esm-uuid")));
+ assertEquals("ValidationError", ex.getErrorCode());
+ assertEquals("Updating StartingPosition requires resource replacement, which is not supported.", ex.getMessage());
+ }
+
+ @Test
+ void provisionRejectsUpdatingStartingPositionTimestamp() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+ r.setPhysicalId("existing-esm-uuid");
+
+ EventSourceMapping existing = new EventSourceMapping();
+ existing.setUuid("existing-esm-uuid");
+ existing.setStartingPositionTimestamp(1000000000L);
+ when(lambdaService.getEventSourceMapping("existing-esm-uuid")).thenReturn(existing);
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("StartingPositionTimestamp", "2000000");
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> provisioner.provision(r, props, ctx(true, "existing-esm-uuid")));
+ assertEquals("ValidationError", ex.getErrorCode());
+ assertEquals("Updating StartingPositionTimestamp requires resource replacement, which is not supported.", ex.getMessage());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java
index 461f4b9c5c..37030bdf08 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java
@@ -899,6 +899,62 @@ class EsmIntegrationTest {
.body("message", containsString("only supported for Amazon Kinesis"));
}
+ // ──────────────────────────── Self-Managed Kafka ESM ────────────────────────────
+
+ @Test
+ @Order(80)
+ void createSelfManagedKafkaEventSourceMapping() {
+ // Create Self-Managed Apache Kafka ESM with SelfManagedEventSource, Topics, and StartingPosition
+ String uuid = given()
+ .contentType("application/json")
+ .body("""
+ {
+ "FunctionName": "%s",
+ "SelfManagedEventSource": {
+ "Endpoints": {
+ "KAFKA_BOOTSTRAP_SERVERS": ["b-1.example.com:9092", "b-2.example.com:9092"]
+ }
+ },
+ "Topics": ["orders", "payments"],
+ "StartingPosition": "TRIM_HORIZON"
+ }
+ """.formatted(FUNCTION_NAME))
+ .when()
+ .post(LAMBDA_BASE + "/event-source-mappings")
+ .then()
+ .statusCode(202)
+ .body("UUID", notNullValue())
+ .body("State", equalTo("Enabled"))
+ .body("$", not(hasKey("EventSourceArn")))
+ .body("SelfManagedEventSource.Endpoints.KAFKA_BOOTSTRAP_SERVERS",
+ hasItems("b-1.example.com:9092", "b-2.example.com:9092"))
+ .body("Topics", hasItems("orders", "payments"))
+ .body("StartingPosition", equalTo("TRIM_HORIZON"))
+ .extract()
+ .path("UUID");
+
+ // Verify GET by UUID
+ given()
+ .when()
+ .get(LAMBDA_BASE + "/event-source-mappings/" + uuid)
+ .then()
+ .statusCode(200)
+ .body("UUID", equalTo(uuid))
+ .body("$", not(hasKey("EventSourceArn")))
+ .body("SelfManagedEventSource.Endpoints.KAFKA_BOOTSTRAP_SERVERS",
+ hasItems("b-1.example.com:9092", "b-2.example.com:9092"))
+ .body("Topics", hasItems("orders", "payments"))
+ .body("StartingPosition", equalTo("TRIM_HORIZON"));
+
+ // Verify DELETE by UUID
+ given()
+ .when()
+ .delete(LAMBDA_BASE + "/event-source-mappings/" + uuid)
+ .then()
+ .statusCode(202)
+ .body("UUID", equalTo(uuid));
+ }
+
// ──────────────────────────── Multi-account ESM ────────────────────────────
/**
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/EventSourceMappingSerializationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/EventSourceMappingSerializationTest.java
new file mode 100644
index 0000000000..0e18bc2a6d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/EventSourceMappingSerializationTest.java
@@ -0,0 +1,116 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class EventSourceMappingSerializationTest {
+
+ private ObjectMapper objectMapper;
+ private LambdaController controller;
+
+ @BeforeEach
+ void setUp() {
+ objectMapper = new ObjectMapper();
+ controller = new LambdaController(null, null, objectMapper);
+ }
+
+ @Test
+ void testModelGettersAndSetters() {
+ EventSourceMapping esm = new EventSourceMapping();
+ Map<String, Object> endpoints = Map.of("KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092"));
+ Map<String, Object> selfManagedEventSource = Map.of("Endpoints", endpoints);
+ List<String> topics = List.of("orders-topic", "events-topic");
+ List<Map<String, Object>> sourceAccess = List.of(
+ Map.of("Type", "BASIC_AUTH", "URI", "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-secret")
+ );
+
+ esm.setSelfManagedEventSource(selfManagedEventSource);
+ esm.setTopics(topics);
+ esm.setSourceAccessConfigurations(sourceAccess);
+
+ assertEquals(selfManagedEventSource, esm.getSelfManagedEventSource());
+ assertEquals(topics, esm.getTopics());
+ assertEquals(sourceAccess, esm.getSourceAccessConfigurations());
+
+ // Verify null-safety when passing null for List
+ esm.setTopics(null);
+ assertNotNull(esm.getTopics());
+ assertTrue(esm.getTopics().isEmpty());
+
+ esm.setSourceAccessConfigurations(null);
+ assertNotNull(esm.getSourceAccessConfigurations());
+ assertTrue(esm.getSourceAccessConfigurations().isEmpty());
+ }
+
+ @Test
+ void testJacksonSerializationDeserialization() throws Exception {
+ EventSourceMapping esm = new EventSourceMapping();
+ esm.setUuid("test-uuid-123");
+ esm.setFunctionName("myFunction");
+ esm.setBatchSize(100);
+ esm.setSelfManagedEventSource(Map.of("Endpoints", Map.of("KAFKA_BOOTSTRAP_SERVERS", List.of("10.0.0.1:9092"))));
+ esm.setTopics(List.of("kafka-test-topic"));
+ esm.setSourceAccessConfigurations(List.of(Map.of("Type", "SASL_SCRAM_256_AUTH", "URI", "arn:aws:secretsmanager:test")));
+
+ String json = objectMapper.writeValueAsString(esm);
+ EventSourceMapping deserialized = objectMapper.readValue(json, EventSourceMapping.class);
+
+ assertEquals("test-uuid-123", deserialized.getUuid());
+ assertEquals("myFunction", deserialized.getFunctionName());
+ assertEquals(100, deserialized.getBatchSize());
+ assertNotNull(deserialized.getSelfManagedEventSource());
+ assertEquals(List.of("kafka-test-topic"), deserialized.getTopics());
+ assertEquals(1, deserialized.getSourceAccessConfigurations().size());
+ }
+
+ @Test
+ void testBuildEsmResponseIncludesKafkaFieldsAndOmitsNullEventSourceArn() {
+ EventSourceMapping esm = new EventSourceMapping();
+ esm.setUuid("esm-kafka-001");
+ esm.setFunctionArn("arn:aws:lambda:us-east-1:123456789012:function:kafkaConsumer");
+ // Self-managed Kafka does not have EventSourceArn
+ esm.setEventSourceArn(null);
+ esm.setBatchSize(50);
+ esm.setState("Enabled");
+ esm.setLastModified(1700000000000L);
+ esm.setSelfManagedEventSource(Map.of("Endpoints", Map.of("KAFKA_BOOTSTRAP_SERVERS", List.of("192.168.1.10:9092"))));
+ esm.setTopics(List.of("telemetry-topic"));
+ esm.setSourceAccessConfigurations(List.of(
+ Map.of("Type", "CLIENT_CERTIFICATE_TLS_AUTH", "URI", "arn:aws:secretsmanager:us-east-1:123456789012:secret:cert")
+ ));
+
+ Map<String, Object> response = controller.buildEsmResponse(esm);
+
+ assertEquals("esm-kafka-001", response.get("UUID"));
+ assertEquals("arn:aws:lambda:us-east-1:123456789012:function:kafkaConsumer", response.get("FunctionArn"));
+ assertFalse(response.containsKey("EventSourceArn"), "EventSourceArn must be omitted when null per AWS wire protocol");
+ assertNotNull(response.get("SelfManagedEventSource"));
+ assertEquals(List.of("telemetry-topic"), response.get("Topics"));
+ assertNotNull(response.get("SourceAccessConfigurations"));
+ }
+
+ @Test
+ void testBuildEsmResponseWithEventSourceArnPresent() {
+ EventSourceMapping esm = new EventSourceMapping();
+ esm.setUuid("esm-sqs-001");
+ esm.setFunctionArn("arn:aws:lambda:us-east-1:123456789012:function:sqsConsumer");
+ esm.setEventSourceArn("arn:aws:sqs:us-east-1:123456789012:my-queue");
+ esm.setBatchSize(10);
+ esm.setState("Enabled");
+ esm.setLastModified(1700000000000L);
+
+ Map<String, Object> response = controller.buildEsmResponse(esm);
+
+ assertEquals("arn:aws:sqs:us-east-1:123456789012:my-queue", response.get("EventSourceArn"));
+ assertFalse(response.containsKey("SelfManagedEventSource"));
+ assertFalse(response.containsKey("Topics"));
+ assertFalse(response.containsKey("SourceAccessConfigurations"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
index 8d750644a8..170cbb21a8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
@@ -3,7 +3,10 @@ package io.github.hectorvent.floci.services.lambda;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
import io.github.hectorvent.floci.services.lambda.model.LambdaFileSystemConfig;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.zip.CodeStore;
@@ -42,7 +45,10 @@ class LambdaServiceTest {
CodeStore codeStore = new CodeStore(Path.of("target/test-data/lambda-code"));
ZipExtractor zipExtractor = new ZipExtractor();
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
- service = new LambdaService(store, warmPool, codeStore, zipExtractor, regionResolver);
+ StorageFactory storageFactory = mock(StorageFactory.class);
+ when(storageFactory.create(anyString(), anyString(), any()))
+ .thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
+ service = new LambdaService(store, warmPool, codeStore, zipExtractor, null, regionResolver, storageFactory);
}
private Map<String, Object> baseRequest(String name) {
@@ -1149,4 +1155,284 @@ class LambdaServiceTest {
pool.shutdownNow();
}
}
+
+ @Test
+ void createEventSourceMapping_selfManagedKafka_success() {
+ service.createFunction(REGION, baseRequest("kafka-fn"));
+
+ Map<String, Object> request = new java.util.HashMap<>(Map.of(
+ "FunctionName", "kafka-fn",
+ "Topics", List.of("my-topic"),
+ "SelfManagedEventSource", Map.of(
+ "Endpoints", Map.of(
+ "KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092")
+ )
+ ),
+ "SourceAccessConfigurations", List.of(
+ Map.of("Type", "SASL_SCRAM_256_AUTH", "URI", "arn:aws:secretsmanager:us-east-1:000000000000:secret:my-secret")
+ )
+ ));
+
+ EventSourceMapping esm = service.createEventSourceMapping(REGION, request);
+
+ assertNotNull(esm);
+ assertNotNull(esm.getUuid());
+ assertNull(esm.getEventSourceArn());
+ assertEquals(List.of("my-topic"), esm.getTopics());
+ assertNotNull(esm.getSelfManagedEventSource());
+ assertEquals(1, esm.getSourceAccessConfigurations().size());
+ assertEquals("Enabled", esm.getState());
+ assertTrue(esm.isEnabled());
+
+ // Verify update
+ EventSourceMapping updated = service.updateEventSourceMapping(esm.getUuid(), Map.of(
+ "Topics", List.of("updated-topic")
+ ));
+ assertEquals(List.of("updated-topic"), updated.getTopics());
+
+ // Verify delete
+ service.deleteEventSourceMapping(esm.getUuid());
+ assertThrows(AwsException.class, () -> service.getEventSourceMapping(esm.getUuid()));
+ }
+
+ @Test
+ void createEventSourceMapping_selfManagedKafka_missingTopics_throws() {
+ service.createFunction(REGION, baseRequest("kafka-fn-missing-topics"));
+
+ Map<String, Object> request = new java.util.HashMap<>(Map.of(
+ "FunctionName", "kafka-fn-missing-topics",
+ "SelfManagedEventSource", Map.of(
+ "Endpoints", Map.of(
+ "KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092")
+ )
+ )
+ ));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> service.createEventSourceMapping(REGION, request));
+ assertEquals("InvalidParameterValueException", ex.getErrorCode());
+ assertEquals(400, ex.getHttpStatus());
+ assertTrue(ex.getMessage().contains("Topics"));
+ }
+
+ @Test
+ void createEventSourceMapping_selfManagedKafka_missingBootstrapServers_throws() {
+ service.createFunction(REGION, baseRequest("kafka-fn-missing-servers"));
+
+ Map<String, Object> request = new java.util.HashMap<>(Map.of(
+ "FunctionName", "kafka-fn-missing-servers",
+ "Topics", List.of("my-topic"),
+ "SelfManagedEventSource", Map.of(
+ "Endpoints", Map.of()
+ )
+ ));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> service.createEventSourceMapping(REGION, request));
+ assertEquals("InvalidParameterValueException", ex.getErrorCode());
+ assertEquals(400, ex.getHttpStatus());
+ assertTrue(ex.getMessage().contains("KAFKA_BOOTSTRAP_SERVERS"));
+ }
+
+ @Test
+ void createEventSourceMapping_selfManagedKafka_atTimestamp_succeeds() {
+ service.createFunction(REGION, baseRequest("kafka-fn-at-timestamp"));
+
+ Map<String, Object> request = new java.util.HashMap<>(Map.of(
+ "FunctionName", "kafka-fn-at-timestamp",
+ "Topics", List.of("my-topic"),
+ "SelfManagedEventSource", Map.of(
+ "Endpoints", Map.of(
+ "KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092")
+ )
+ ),
+ "StartingPosition", "AT_TIMESTAMP",
+ "StartingPositionTimestamp", 123456789
+ ));
+
+ EventSourceMapping esm = service.createEventSourceMapping(REGION, request);
+ assertNotNull(esm);
+ assertEquals("AT_TIMESTAMP", esm.getStartingPosition());
+ assertEquals(123456789000L, esm.getStartingPositionTimestamp());
+ }
+
+ @Test
+ void createEventSourceMapping_dynamoDb_atTimestamp_throws() {
+ service.createFunction(REGION, baseRequest("dynamo-fn-at-timestamp"));
+
+ Map<String, Object> request = new java.util.HashMap<>(Map.of(
+ "FunctionName", "dynamo-fn-at-timestamp",
+ "EventSourceArn", "arn:aws:dynamodb:us-east-1:000000000000:table/my-table/stream/2026-01-01T00:00:00.000",
+ "StartingPosition", "AT_TIMESTAMP",
+ "StartingPositionTimestamp", 123456789
+ ));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> service.createEventSourceMapping(REGION, request));
+ assertEquals("InvalidParameterValueException", ex.getErrorCode());
+ assertEquals(400, ex.getHttpStatus());
+ assertTrue(ex.getMessage().contains("AT_TIMESTAMP is only supported for Amazon Kinesis"));
+ }
+
+ @Test
+ void createEventSourceMapping_selfManagedKafka_crossRegionFunctionArn_throws() {
+ service.createFunction(REGION, baseRequest("kafka-fn-cross-region"));
+
+ Map<String, Object> request = new java.util.HashMap<>(Map.of(
+ "FunctionName", "arn:aws:lambda:us-west-2:000000000000:function:kafka-fn-cross-region",
+ "Topics", List.of("my-topic"),
+ "SelfManagedEventSource", Map.of(
+ "Endpoints", Map.of(
+ "KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092")
+ )
+ )
+ ));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> service.createEventSourceMapping(REGION, request));
+ assertEquals("InvalidParameterValueException", ex.getErrorCode());
+ assertEquals(400, ex.getHttpStatus());
+ assertTrue(ex.getMessage().contains("Region 'us-west-2' in ARN does not match request region 'us-east-1'"));
+ }
+
+ @Test
+ void createEventSourceMapping_mixedSources_throws() {
+ service.createFunction(REGION, baseRequest("kafka-fn-mixed"));
+
+ Map<String, Object> request = new java.util.HashMap<>(Map.of(
+ "FunctionName", "kafka-fn-mixed",
+ "EventSourceArn", "arn:aws:sqs:us-east-1:000000000000:my-queue",
+ "Topics", List.of("my-topic"),
+ "SelfManagedEventSource", Map.of(
+ "Endpoints", Map.of(
+ "KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092")
+ )
+ )
+ ));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> service.createEventSourceMapping(REGION, request));
+ assertEquals("InvalidParameterValueException", ex.getErrorCode());
+ assertEquals(400, ex.getHttpStatus());
+ assertTrue(ex.getMessage().contains("Cannot specify both EventSourceArn and SelfManagedEventSource/Topics"));
+ }
+
+ @Test
+ void createEventSourceMapping_selfManagedKafka_malformedTopics_throws() {
+ service.createFunction(REGION, baseRequest("kafka-fn-malformed-topics"));
+
+ Map<String, Object> request = new java.util.HashMap<>(Map.of(
+ "FunctionName", "kafka-fn-malformed-topics",
+ "Topics", List.of(123),
+ "SelfManagedEventSource", Map.of(
+ "Endpoints", Map.of(
+ "KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092")
+ )
+ )
+ ));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> service.createEventSourceMapping(REGION, request));
+ assertEquals("InvalidParameterValueException", ex.getErrorCode());
+ assertEquals(400, ex.getHttpStatus());
+ }
+
+ @Test
+ void updateEventSourceMapping_malformedTopics_throws() {
+ service.createFunction(REGION, baseRequest("kafka-fn-update-topics"));
+
+ EventSourceMapping esm = service.createEventSourceMapping(REGION, Map.of(
+ "FunctionName", "kafka-fn-update-topics",
+ "Topics", List.of("valid-topic"),
+ "SelfManagedEventSource", Map.of(
+ "Endpoints", Map.of(
+ "KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092")
+ )
+ )
+ ));
+
+ assertThrows(AwsException.class, () -> service.updateEventSourceMapping(esm.getUuid(), Map.of(
+ "Topics", List.of()
+ )));
+ assertThrows(AwsException.class, () -> service.updateEventSourceMapping(esm.getUuid(), Map.of(
+ "Topics", List.of(456)
+ )));
+ }
+
+ @Test
+ void updateEventSourceMapping_functionTargetValidation() {
+ service.createFunction(REGION, baseRequest("fn-esm-target-1"));
+ service.createFunction(REGION, baseRequest("fn-esm-target-2"));
+
+ EventSourceMapping esm = service.createEventSourceMapping(REGION, Map.of(
+ "FunctionName", "fn-esm-target-1",
+ "Topics", List.of("valid-topic"),
+ "SelfManagedEventSource", Map.of(
+ "Endpoints", Map.of(
+ "KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092")
+ )
+ )
+ ));
+
+ // Valid function update
+ EventSourceMapping updated = service.updateEventSourceMapping(esm.getUuid(), Map.of(
+ "FunctionName", "fn-esm-target-2"
+ ));
+ assertEquals("fn-esm-target-2", updated.getFunctionName());
+ assertTrue(updated.getFunctionArn().contains("fn-esm-target-2"));
+
+ // Qualified version target update
+ service.publishVersion(REGION, "fn-esm-target-2", "v1");
+ EventSourceMapping updatedVersion = service.updateEventSourceMapping(esm.getUuid(), Map.of(
+ "FunctionName", "fn-esm-target-2:1"
+ ));
+ assertEquals("fn-esm-target-2", updatedVersion.getFunctionName());
+ assertTrue(updatedVersion.getFunctionArn().endsWith(":fn-esm-target-2:1"));
+
+ // Qualified alias target update
+ service.createAlias(REGION, "fn-esm-target-2", "live", "1", "production alias", null);
+ EventSourceMapping updatedAlias = service.updateEventSourceMapping(esm.getUuid(), Map.of(
+ "FunctionName", "fn-esm-target-2:live"
+ ));
+ assertEquals("fn-esm-target-2", updatedAlias.getFunctionName());
+ assertTrue(updatedAlias.getFunctionArn().endsWith(":fn-esm-target-2:live"));
+
+ // Qualified $LATEST target update
+ EventSourceMapping updatedLatest = service.updateEventSourceMapping(esm.getUuid(), Map.of(
+ "FunctionName", "fn-esm-target-2:$LATEST"
+ ));
+ assertEquals("fn-esm-target-2", updatedLatest.getFunctionName());
+ assertTrue(updatedLatest.getFunctionArn().endsWith(":fn-esm-target-2:$LATEST"));
+
+ // Create ESM with qualified function reference
+ EventSourceMapping esmQualified = service.createEventSourceMapping(REGION, Map.of(
+ "FunctionName", "fn-esm-target-2:live",
+ "Topics", List.of("valid-topic"),
+ "SelfManagedEventSource", Map.of(
+ "Endpoints", Map.of(
+ "KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092")
+ )
+ )
+ ));
+ assertEquals("fn-esm-target-2", esmQualified.getFunctionName());
+ assertTrue(esmQualified.getFunctionArn().endsWith(":fn-esm-target-2:live"));
+
+ // Non-existent version or alias throws 404
+ assertThrows(AwsException.class, () -> service.updateEventSourceMapping(esm.getUuid(), Map.of(
+ "FunctionName", "fn-esm-target-2:99"
+ )));
+ assertThrows(AwsException.class, () -> service.updateEventSourceMapping(esm.getUuid(), Map.of(
+ "FunctionName", "fn-esm-target-2:non-existent-alias"
+ )));
+
+ // Non-existent function throws
+ assertThrows(AwsException.class, () -> service.updateEventSourceMapping(esm.getUuid(), Map.of(
+ "FunctionName", "non-existent-fn"
+ )));
+
+ // Cross-region function ARN throws
+ assertThrows(AwsException.class, () -> service.updateEventSourceMapping(esm.getUuid(), Map.of(
+ "FunctionName", "arn:aws:lambda:us-west-2:000000000000:function:other-region-fn"
+ )));
+ }
}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 4324b03ff2..e1e36f0165 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -80,7 +80,7 @@ AWS::KMS::Key KmsCfnProvisioner
AWS::Kinesis::Stream KinesisCfnProvisioner
AWS::KinesisFirehose::DeliveryStream FirehoseCfnProvisioner
AWS::Lambda::Alias LambdaVersionAliasCfnProvisioner
-AWS::Lambda::EventSourceMapping LEGACY_SWITCH
+AWS::Lambda::EventSourceMapping LambdaEventSourceMappingCfnProvisioner
AWS::Lambda::Function LEGACY_SWITCH
AWS::Lambda::LayerVersion LEGACY_SWITCH
AWS::Lambda::MicrovmImage LambdaMicrovmsCfnProvisioner