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

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

- Add SelfManagedEventSource, Topics, and SourceAccessConfigurations metadata to EventSourceMapping
- Omit EventSourceArn in REST response when null to comply with AWS wire protocol
- Support Kafka source discrimination in LambdaService and guard pollers against null EventSourceArn
- Forward Kafka ESM properties in CloudFormation provisioner
- Add serialization, service, integration, and CloudFormation tests

* fix(lambda): address review comments for self-managed Kafka ESM

* fix(lambda): handle batch size validation, function target update, and cfn access config clearing

* fix(lambda): bind qualified function targets correctly in event source mappings

* fix(cloudformation): use CfnDeletes.safeDelete in Lambda ESM provisioner

* fix(cloudformation): throw AwsException on missing FunctionName in Lambda ESM provisioner

* fix(lambda): handle create-only ESM update, allow AT_TIMESTAMP for Kafka and populate EventSourceMappingArn

* test(cloudformation): assert exact Fn::GetAtt attributes for Lambda ESM
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-05 23:41:44 -04:00
1 parent 025ac714f6
commit ee5c87d6d6
13 files changed
+1450 -97

No files matched your search

@@ -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));
@@ -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";
@@ -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());
}
}
@@ -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 ────────────────────────────
/**
@@ -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"));
}
}
@@ -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"
)));
}
}