diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaEsmTagsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaEsmTagsTest.java new file mode 100644 index 0000000000..5ab8e44190 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaEsmTagsTest.java @@ -0,0 +1,151 @@ +package com.floci.test; + +import org.junit.jupiter.api.*; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.*; +import software.amazon.awssdk.services.lambda.model.Runtime; +import software.amazon.awssdk.services.sqs.SqsClient; +import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; +import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest; +import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest; +import software.amazon.awssdk.services.sqs.model.QueueAttributeName; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.*; + +@DisplayName("Lambda - ESM ARN and tags") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class LambdaEsmTagsTest { + + private static final String FUNCTION_NAME = "sdk-test-esm-tags-fn"; + private static final String SQS_QUEUE_NAME = "sdk-test-esm-tags-queue"; + private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-role"; + + private static LambdaClient lambda; + private static SqsClient sqs; + private static String queueUrl; + private static String esmUuid; + private static String esmArn; + + @BeforeAll + static void setup() { + lambda = TestFixtures.lambdaClient(); + sqs = TestFixtures.sqsClient(); + + lambda.createFunction(CreateFunctionRequest.builder() + .functionName(FUNCTION_NAME) + .runtime(Runtime.NODEJS20_X) + .role(ROLE) + .handler("index.handler") + .code(FunctionCode.builder() + .zipFile(SdkBytes.fromByteArray(LambdaUtils.minimalZip())) + .build()) + .build()); + + queueUrl = sqs.createQueue(CreateQueueRequest.builder() + .queueName(SQS_QUEUE_NAME) + .build()) + .queueUrl(); + } + + @AfterAll + static void cleanup() { + if (lambda != null) { + if (esmUuid != null) { + try { + lambda.deleteEventSourceMapping(DeleteEventSourceMappingRequest.builder() + .uuid(esmUuid).build()); + } catch (Exception ignored) { + // Best-effort teardown: the ordered tests delete the mapping themselves, + // so a ResourceNotFoundException here is the expected case. + } + } + try { + lambda.deleteFunction(DeleteFunctionRequest.builder() + .functionName(FUNCTION_NAME).build()); + } catch (Exception ignored) { + // Best-effort teardown: a leftover function does not affect other suites. + } + lambda.close(); + } + if (sqs != null) { + try { + sqs.deleteQueue(DeleteQueueRequest.builder().queueUrl(queueUrl).build()); + } catch (Exception ignored) { + // Best-effort teardown: a leftover queue does not affect other suites. + } + sqs.close(); + } + } + + @Test + @Order(1) + void createEsm_returnsArnAndStoresTags() { + String queueArn = sqs.getQueueAttributes(GetQueueAttributesRequest.builder() + .queueUrl(queueUrl) + .attributeNames(QueueAttributeName.QUEUE_ARN) + .build()) + .attributes() + .get(QueueAttributeName.QUEUE_ARN); + + CreateEventSourceMappingResponse created = lambda.createEventSourceMapping( + CreateEventSourceMappingRequest.builder() + .functionName(FUNCTION_NAME) + .eventSourceArn(queueArn) + .tags(Map.of("Environment", "uat", "ManagedBy", "terraform")) + .build()); + esmUuid = created.uuid(); + esmArn = created.eventSourceMappingArn(); + + assertThat(esmArn).matches("arn:aws[a-z-]*:lambda:[a-z0-9-]+:\\d{12}:event-source-mapping:" + esmUuid); + + ListTagsResponse tags = lambda.listTags(ListTagsRequest.builder().resource(esmArn).build()); + assertThat(tags.tags()).containsExactlyInAnyOrderEntriesOf( + Map.of("Environment", "uat", "ManagedBy", "terraform")); + } + + @Test + @Order(2) + void getAndListEsm_returnTheSameArn() { + GetEventSourceMappingResponse fetched = lambda.getEventSourceMapping( + GetEventSourceMappingRequest.builder().uuid(esmUuid).build()); + assertThat(fetched.eventSourceMappingArn()).isEqualTo(esmArn); + + ListEventSourceMappingsResponse listed = lambda.listEventSourceMappings( + ListEventSourceMappingsRequest.builder().functionName(FUNCTION_NAME).build()); + assertThat(listed.eventSourceMappings()) + .filteredOn(m -> esmUuid.equals(m.uuid())) + .singleElement() + .extracting(EventSourceMappingConfiguration::eventSourceMappingArn) + .isEqualTo(esmArn); + } + + @Test + @Order(3) + void tagAndUntagResource_onEsmArn() { + lambda.tagResource(TagResourceRequest.builder() + .resource(esmArn) + .tags(Map.of("Layer", "backend")) + .build()); + lambda.untagResource(UntagResourceRequest.builder() + .resource(esmArn) + .tagKeys("ManagedBy") + .build()); + + ListTagsResponse tags = lambda.listTags(ListTagsRequest.builder().resource(esmArn).build()); + assertThat(tags.tags()).containsExactlyInAnyOrderEntriesOf( + Map.of("Environment", "uat", "Layer", "backend")); + } + + @Test + @Order(4) + void listTags_afterDelete_throwsResourceNotFound() { + lambda.deleteEventSourceMapping(DeleteEventSourceMappingRequest.builder().uuid(esmUuid).build()); + esmUuid = null; + + assertThatThrownBy(() -> lambda.listTags(ListTagsRequest.builder().resource(esmArn).build())) + .isInstanceOf(ResourceNotFoundException.class); + } +} diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 2b64a6b5be..33a70eeb81 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -43,9 +43,9 @@ Floci Lambda runs your function code locally inside real Docker containers - clo | `GetFunctionUrlConfig` | Read function URL config | | `UpdateFunctionUrlConfig` | Update function URL config | | `DeleteFunctionUrlConfig` | Delete function URL config | -| `ListTags` | List tags on a function | -| `TagResource` | Tag a function | -| `UntagResource` | Untag a function | +| `ListTags` | List tags on a function or event source mapping | +| `TagResource` | Tag a function or event source mapping | +| `UntagResource` | Untag a function or event source mapping | | `PutFunctionConcurrency` | Set reserved concurrent executions | | `GetFunctionConcurrency` | Get reserved concurrent executions | | `DeleteFunctionConcurrency` | Clear reserved concurrent executions | 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 index 264a969369..f506a35ad2 100644 --- 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 @@ -4,9 +4,9 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; -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.LambdaArnUtils; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping; import jakarta.enterprise.context.ApplicationScoped; @@ -177,14 +177,14 @@ public class LambdaEventSourceMappingCfnProvisioner implements CfnResourceProvis "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(); + EventSourceMapping updated = lambdaService.updateEventSourceMapping(uuid, req); + String esmArn = LambdaArnUtils.eventSourceMappingArn(updated.getRegion(), updated.getAccountId(), uuid); 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(); + EventSourceMapping esm = lambdaService.createEventSourceMapping(ctx.region(), req); + String esmArn = LambdaArnUtils.eventSourceMappingArn(esm.getRegion(), esm.getAccountId(), esm.getUuid()); r.setPhysicalId(esm.getUuid()); r.getAttributes().put("Id", esm.getUuid()); r.getAttributes().put("EventSourceMappingArn", esmArn); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java index 8bba97ff25..fc474dee64 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java @@ -27,8 +27,26 @@ public final class LambdaArnUtils { private static final Pattern ACCOUNT_PATTERN = Pattern.compile("\\d{12}"); private static final Pattern QUALIFIER_PATTERN = Pattern.compile("\\$LATEST|[a-zA-Z0-9-_]+"); + private static final String EVENT_SOURCE_MAPPING_PREFIX = "event-source-mapping:"; + private LambdaArnUtils() {} + /** {@code arn::lambda:::event-source-mapping:}. */ + public static String eventSourceMappingArn(String region, String accountId, String uuid) { + return AwsArnUtils.Arn.of("lambda", region, accountId, EVENT_SOURCE_MAPPING_PREFIX + uuid).toString(); + } + + /** + * The UUID of an event source mapping ARN, or {@code null} when {@code arn} names + * some other Lambda resource. + */ + public static String eventSourceMappingUuid(AwsArnUtils.Arn arn) { + if (!"lambda".equals(arn.service()) || !arn.resource().startsWith(EVENT_SOURCE_MAPPING_PREFIX)) { + return null; + } + return arn.resource().substring(EVENT_SOURCE_MAPPING_PREFIX.length()); + } + /** * Resolved components of a Lambda function reference. * 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 cead65dad6..58d2326883 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 @@ -345,6 +345,8 @@ public class LambdaController { Map buildEsmResponse(EventSourceMapping esm) { ObjectNode node = objectMapper.createObjectNode(); node.put("UUID", esm.getUuid()); + node.put("EventSourceMappingArn", + LambdaArnUtils.eventSourceMappingArn(esm.getRegion(), esm.getAccountId(), esm.getUuid())); node.put("FunctionArn", esm.getFunctionArn()); if (esm.getEventSourceArn() != null) { node.put("EventSourceArn", esm.getEventSourceArn()); 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 a369e78c9a..b1a518a2fc 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 @@ -47,6 +47,7 @@ import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Base64; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -1281,6 +1282,7 @@ public class LambdaService implements ResourceProvider { esm.setSelfManagedEventSource(selfManagedEventSource); esm.setTopics(topics); esm.setSourceAccessConfigurations(sourceAccessConfigurations); + esm.setTags(requestTags(request)); esm.setLastModified(System.currentTimeMillis()); if (eventSourceArn != null && eventSourceArn.contains(":dynamodb:")) { @@ -2215,6 +2217,25 @@ public class LambdaService implements ResourceProvider { environment.get("Variables"), "Environment.Variables"); } + /** + * The request's {@code Tags} member as a string-to-string map, or {@code null} when it is + * absent. A non-object member or a non-string tag value is a {@code SerializationException}. + */ + static Map requestTags(Map request) { + Map requested = structureMember(request, "Tags"); + if (requested == null) { + return null; + } + Map tags = new HashMap<>(); + for (Map.Entry entry : requested.entrySet()) { + if (!(entry.getValue() instanceof String value)) { + throw new AwsException("SerializationException", "Tags values must be strings", 400); + } + tags.put(entry.getKey(), value); + } + return tags; + } + private static void validateEventSourceMappingStructures(Map request) { structureMember(request, "ScalingConfig"); Map destinationConfig = structureMember(request, "DestinationConfig"); @@ -3107,20 +3128,36 @@ public class LambdaService implements ResourceProvider { // ──────────────────────────── Tags ──────────────────────────── public Map listTags(String functionArn) { + EventSourceMapping esm = taggedEventSourceMapping(functionArn); + if (esm != null) { + return esm.getTags(); + } TagTarget target = resolveTagTarget(functionArn); LambdaFunction fn = getFunction(target.region, target.name); return fn.getTags() != null ? fn.getTags() : Map.of(); } public void tagResource(String functionArn, Map tags) { + EventSourceMapping esm = taggedEventSourceMapping(functionArn); + if (esm != null) { + esm.getTags().putAll(tags); + esmStore.save(esm); + return; + } TagTarget target = resolveTagTarget(functionArn); LambdaFunction fn = getFunction(target.region, target.name); - if (fn.getTags() == null) fn.setTags(new java.util.HashMap<>()); + if (fn.getTags() == null) fn.setTags(new HashMap<>()); fn.getTags().putAll(tags); functionStore.save(target.region, fn); } public void untagResource(String functionArn, List tagKeys) { + EventSourceMapping esm = taggedEventSourceMapping(functionArn); + if (esm != null) { + tagKeys.forEach(esm.getTags()::remove); + esmStore.save(esm); + return; + } TagTarget target = resolveTagTarget(functionArn); LambdaFunction fn = getFunction(target.region, target.name); if (fn.getTags() != null) { @@ -3131,6 +3168,33 @@ public class LambdaService implements ResourceProvider { private record TagTarget(String region, String name) {} + /** + * The mapping named by an {@code event-source-mapping:} tag-endpoint ARN, or {@code null} + * when the ARN names some other resource. An ARN in another partition, region or account + * than the mapping's is reported as missing, as AWS does. + */ + private EventSourceMapping taggedEventSourceMapping(String resourceArn) { + if (resourceArn == null || !resourceArn.startsWith("arn:")) { + return null; + } + AwsArnUtils.Arn arn; + try { + arn = AwsArnUtils.parse(resourceArn); + } catch (IllegalArgumentException ignored) { + // Not a well-formed ARN, so not a mapping ARN; resolveTagTarget reports the error. + return null; + } + String uuid = LambdaArnUtils.eventSourceMappingUuid(arn); + if (uuid == null) { + return null; + } + return esmStore.get(uuid) + .filter(esm -> resourceArn.equals(LambdaArnUtils.eventSourceMappingArn( + esm.getRegion(), esm.getAccountId(), esm.getUuid()))) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "The resource you requested does not exist.", 404)); + } + /** * Resolves a tag-endpoint ARN to a (region, shortName) pair. The Lambda * tag APIs only accept an unqualified full function ARN; reject partial diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagController.java index 0a22b85716..e9d9e07a8f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagController.java @@ -75,8 +75,7 @@ public class LambdaTagController { try { @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); - @SuppressWarnings("unchecked") - Map tags = (Map) request.get("Tags"); + Map tags = LambdaService.requestTags(request); if (tags == null) { throw new AwsException("InvalidParameterValueException", "Tags is required", 400); } 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 b3662043b6..649c31a596 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 @@ -38,6 +38,7 @@ public class EventSourceMapping { private Map selfManagedEventSource; private List topics = new ArrayList<>(); private List> sourceAccessConfigurations = new ArrayList<>(); + private Map tags = new HashMap<>(); public EventSourceMapping() { } @@ -101,7 +102,7 @@ public class EventSourceMapping { public Map getShardSequenceNumbers() { return shardSequenceNumbers; } public void setShardSequenceNumbers(Map shardSequenceNumbers) { - this.shardSequenceNumbers = shardSequenceNumbers != null ? shardSequenceNumbers : new java.util.HashMap<>(); + this.shardSequenceNumbers = shardSequenceNumbers != null ? shardSequenceNumbers : new HashMap<>(); } public ScalingConfig getScalingConfig() { return scalingConfig; } @@ -176,6 +177,14 @@ public class EventSourceMapping { this.sourceAccessConfigurations = sourceAccessConfigurations != null ? sourceAccessConfigurations : new ArrayList<>(); } + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags != null ? tags : new HashMap<>(); + } + @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) public static class DestinationConfig { 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 index 38049a54ce..906d57a456 100644 --- 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 @@ -43,6 +43,19 @@ class LambdaEventSourceMappingCfnProvisionerTest { new LambdaEventSourceMappingCfnProvisioner(lambdaService); private final ObjectMapper mapper = new ObjectMapper(); + LambdaEventSourceMappingCfnProvisionerTest() { + when(lambdaService.updateEventSourceMapping(anyString(), any())) + .thenAnswer(inv -> storedMapping(inv.getArgument(0), "us-east-1")); + } + + private static EventSourceMapping storedMapping(String uuid, String region) { + EventSourceMapping esm = new EventSourceMapping(); + esm.setUuid(uuid); + esm.setRegion(region); + esm.setAccountId("000000000000"); + return esm; + } + private ProvisionContext ctx() { return ctx(false, null); } @@ -133,8 +146,7 @@ class LambdaEventSourceMappingCfnProvisionerTest { props.put("Enabled", "true"); props.put("StartingPosition", "TRIM_HORIZON"); - EventSourceMapping esm = new EventSourceMapping(); - esm.setUuid("test-esm-uuid-1234"); + EventSourceMapping esm = storedMapping("test-esm-uuid-1234", "us-east-1"); when(lambdaService.createEventSourceMapping(eq("us-east-1"), any())).thenReturn(esm); provisioner.provision(r, props, ctx()); @@ -155,6 +167,24 @@ class LambdaEventSourceMappingCfnProvisionerTest { assertEquals("TRIM_HORIZON", req.get("StartingPosition")); } + @Test + void eventSourceMappingArnUsesTheRegionTheMappingIsStoredIn() { + StackResource r = new StackResource(); + r.setResourceType("AWS::Lambda::EventSourceMapping"); + + ObjectNode props = mapper.createObjectNode(); + props.put("FunctionName", "my-function"); + props.put("EventSourceArn", "arn:aws:sqs:eu-west-1:000000000000:my-queue"); + + EventSourceMapping esm = storedMapping("cross-region-esm-uuid", "eu-west-1"); + when(lambdaService.createEventSourceMapping(eq("us-east-1"), any())).thenReturn(esm); + + provisioner.provision(r, props, ctx()); + + assertEquals("arn:aws:lambda:eu-west-1:000000000000:event-source-mapping:cross-region-esm-uuid", + r.getAttributes().get("EventSourceMappingArn")); + } + @Test void provisionResolvesNestedIntrinsicsForKafka() { StackResource r = new StackResource(); @@ -175,8 +205,7 @@ class LambdaEventSourceMappingCfnProvisionerTest { props.set("Topics", mapper.createArrayNode().add("my-topic")); - EventSourceMapping esm = new EventSourceMapping(); - esm.setUuid("kafka-esm-uuid"); + EventSourceMapping esm = storedMapping("kafka-esm-uuid", "us-east-1"); when(lambdaService.createEventSourceMapping(eq("us-east-1"), any())).thenReturn(esm); provisioner.provision(r, props, ctx()); @@ -294,8 +323,7 @@ class LambdaEventSourceMappingCfnProvisionerTest { private Map provisionAndCaptureCreateRequest(ObjectNode props) { StackResource r = new StackResource(); r.setResourceType("AWS::Lambda::EventSourceMapping"); - EventSourceMapping esm = new EventSourceMapping(); - esm.setUuid("options-esm-uuid"); + EventSourceMapping esm = storedMapping("options-esm-uuid", "us-east-1"); when(lambdaService.createEventSourceMapping(eq("us-east-1"), any())).thenReturn(esm); provisioner.provision(r, props, ctx()); 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 207f5b6744..617d2f7594 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 @@ -1466,4 +1466,199 @@ class EsmIntegrationTest { given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuidWith).then().statusCode(202); given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuidWithout).then().statusCode(202); } + + // ──────────────────────────── ARN and tags ──────────────────────────── + + private static String esmArn(String region, String uuid) { + return "arn:aws:lambda:" + region + ":" + ACCOUNT_ID + ":event-source-mapping:" + uuid; + } + + @Test + @Order(82) + void eventSourceMappingArnIsReturnedByCreateGetListAndDelete() { + String uuid = given() + .contentType("application/json") + .body(""" + { "FunctionName": "%s", "EventSourceArn": "%s" } + """.formatted(FUNCTION_NAME, QUEUE_ARN)) + .when().post(LAMBDA_BASE + "/event-source-mappings") + .then() + .statusCode(202) + .body("EventSourceMappingArn", startsWith("arn:aws:lambda:" + REGION + ":" + ACCOUNT_ID + + ":event-source-mapping:")) + .extract().path("UUID"); + String arn = esmArn(REGION, uuid); + + given().get(LAMBDA_BASE + "/event-source-mappings/" + uuid) + .then() + .statusCode(200) + .body("EventSourceMappingArn", equalTo(arn)); + + given().queryParam("FunctionName", FUNCTION_ARN).get(LAMBDA_BASE + "/event-source-mappings") + .then() + .statusCode(200) + .body("EventSourceMappings.find { it.UUID == '" + uuid + "' }.EventSourceMappingArn", equalTo(arn)); + + given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid) + .then() + .statusCode(202) + .body("EventSourceMappingArn", equalTo(arn)); + } + + @Test + @Order(83) + void createEventSourceMappingStoresTagsReadableThroughListTags() { + String uuid = given() + .contentType("application/json") + .body(""" + { + "FunctionName": "%s", + "EventSourceArn": "%s", + "Tags": { "Environment": "uat", "ManagedBy": "terraform" } + } + """.formatted(FUNCTION_NAME, QUEUE_ARN)) + .when().post(LAMBDA_BASE + "/event-source-mappings") + .then() + .statusCode(202) + .body("$", not(hasKey("Tags"))) + .extract().path("UUID"); + + given().get("/2017-03-31/tags/" + esmArn(REGION, uuid)) + .then() + .statusCode(200) + .body("Tags.Environment", equalTo("uat")) + .body("Tags.ManagedBy", equalTo("terraform")) + .body("Tags.size()", equalTo(2)); + + given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202); + } + + @Test + @Order(84) + void tagAndUntagResourceOnEventSourceMappingArn() { + String uuid = given() + .contentType("application/json") + .body(""" + { "FunctionName": "%s", "EventSourceArn": "%s" } + """.formatted(FUNCTION_NAME, QUEUE_ARN)) + .when().post(LAMBDA_BASE + "/event-source-mappings") + .then().statusCode(202).extract().path("UUID"); + String arn = esmArn(REGION, uuid); + + given().get("/2017-03-31/tags/" + arn) + .then() + .statusCode(200) + .body("Tags.size()", equalTo(0)); + + given() + .contentType("application/json") + .body("{\"Tags\": {\"Layer\": \"backend\", \"Target\": \"email\"}}") + .when().post("/2017-03-31/tags/" + arn) + .then().statusCode(204); + + given().queryParam("tagKeys", "Target").delete("/2017-03-31/tags/" + arn) + .then().statusCode(204); + + given().get("/2017-03-31/tags/" + arn) + .then() + .statusCode(200) + .body("Tags.Layer", equalTo("backend")) + .body("Tags.size()", equalTo(1)); + + given().get("/2017-03-31/tags/" + FUNCTION_ARN) + .then() + .statusCode(200) + .body("Tags", not(hasKey("Layer"))); + + given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202); + + given().get("/2017-03-31/tags/" + arn) + .then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + @Order(85) + void tagApisReportUnknownOrForeignEventSourceMappingArnAsNotFound() { + given().get("/2017-03-31/tags/" + esmArn(REGION, UUID.randomUUID().toString())) + .then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + + String uuid = given() + .contentType("application/json") + .body(""" + { "FunctionName": "%s", "EventSourceArn": "%s" } + """.formatted(FUNCTION_NAME, QUEUE_ARN)) + .when().post(LAMBDA_BASE + "/event-source-mappings") + .then().statusCode(202).extract().path("UUID"); + + given() + .contentType("application/json") + .body("{\"Tags\": {\"k\": \"v\"}}") + .when().post("/2017-03-31/tags/" + esmArn("eu-west-1", uuid)) + .then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + + given().get("/2017-03-31/tags/" + esmArn(REGION, uuid).replaceFirst("^arn:aws:", "arn:aws-cn:")) + .then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + + given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202); + } + + @Test + @Order(86) + void createEventSourceMappingRejectsNonObjectTags() { + given() + .contentType("application/json") + .body(""" + { "FunctionName": "%s", "EventSourceArn": "%s", "Tags": ["Environment"] } + """.formatted(FUNCTION_NAME, QUEUE_ARN)) + .when().post(LAMBDA_BASE + "/event-source-mappings") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + + given() + .contentType("application/json") + .body(""" + { "FunctionName": "%s", "EventSourceArn": "%s", "Tags": { "Environment": 1 } } + """.formatted(FUNCTION_NAME, QUEUE_ARN)) + .when().post(LAMBDA_BASE + "/event-source-mappings") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + } + + @Test + @Order(87) + void tagResourceRejectsNonStringTagValuesOnEventSourceMapping() { + String uuid = given() + .contentType("application/json") + .body(""" + { "FunctionName": "%s", "EventSourceArn": "%s" } + """.formatted(FUNCTION_NAME, QUEUE_ARN)) + .when().post(LAMBDA_BASE + "/event-source-mappings") + .then().statusCode(202).extract().path("UUID"); + String arn = esmArn(REGION, uuid); + + given() + .contentType("application/json") + .body("{\"Tags\": {\"k\": 1}}") + .when().post("/2017-03-31/tags/" + arn) + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + + given().get("/2017-03-31/tags/" + arn) + .then() + .statusCode(200) + .body("Tags.size()", equalTo(0)); + + given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202); + } }