fix(lambda): round-trip StartingPosition on event source mappings (#2370)

* fix(lambda): round-trip StartingPosition on event source mappings

CreateEventSourceMapping accepted StartingPosition and StartingPositionTimestamp
but never stored them, so GetEventSourceMapping, ListEventSourceMappings and the
create response all omitted the fields entirely.

Any IaC tool that refreshes a mapping therefore reads the starting position back
as unset. Both fields are ForceNew in Terraform's aws_lambda_event_source_mapping,
so every plan proposes adding the value it already asked for and destroys and
recreates the mapping - on every single apply, indefinitely.

Store both on the mapping and emit them from buildEsmResponse, omitting them
when unset the way AWS does for sources that have no starting position. Absent
stays absent on the way in too: AWS requires a starting position for stream
sources, but Floci has always accepted mappings without one, so the new
validation only checks what a caller actually sent. There is no update path
because UpdateEventSourceMapping does not accept the field.

Also pass both through the CloudFormation provisioner, which dropped them for
the same reason.

* fix(lambda): surface a clear error on a malformed StartingPositionTimestamp

Addresses review feedback on the previous commit: silently dropping an
unparseable StartingPositionTimestamp let a bad CloudFormation template value
disappear into the generic "StartingPositionTimestamp is required" error,
pointing at the wrong problem and hiding the value that actually failed.

* test(cloudformation): cover StartingPosition through the CFN provisioner

Addresses review feedback: the existing ESM CFN test only exercises SQS
without a starting position, so nothing verified StartingPosition/
StartingPositionTimestamp actually survives provisionLambdaEventSourceMapping
rather than only the direct API path EsmIntegrationTest already covers.

* fix(cloudformation): reject non-finite StartingPositionTimestamp values

Double.parseDouble accepts "NaN"/"Infinity"/"-Infinity" without throwing,
so those slipped past the existing NumberFormatException catch and were
later rounded by LambdaService into epoch-zero or long-extremum
timestamps instead of being rejected.
This commit is contained in:
sheldon-nadarajah-sft authored and GitHub committed 2026-08-18 09:48:43 -04:00
1 parent 36a55f5060
commit 151e3fcc7a
6 files changed
+421

No files matched your search

@@ -4181,6 +4181,154 @@ class CloudFormationIntegrationTest {
.statusCode(404);
}
@Test
void createStack_lambdaEventSourceMappingWithStartingPosition() {
String stackName = "cfn-esm-starting-position-stack";
String funcName = "cfn-esm-starting-position-func";
String streamName = "cfn-esm-starting-position-stream";
String template = """
{
"Resources": {
"MyStream": {
"Type": "AWS::Kinesis::Stream",
"Properties": {
"Name": "%s",
"ShardCount": 1
}
},
"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 });"
}
}
},
"MyESM": {
"Type": "AWS::Lambda::EventSourceMapping",
"Properties": {
"FunctionName": { "Ref": "MyFunction" },
"EventSourceArn": { "Fn::GetAtt": ["MyStream", "Arn"] },
"StartingPosition": "AT_TIMESTAMP",
"StartingPositionTimestamp": 1787036486.712,
"BatchSize": 5
}
}
}
}
""".formatted(streamName, funcName);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
// The whole point of this test: StartingPosition/StartingPositionTimestamp must survive
// the CFN -> Lambda plumbing, not just the direct-API path EsmIntegrationTest covers.
given()
.when()
.get("/2015-03-31/event-source-mappings?FunctionName=" + funcName)
.then()
.statusCode(200)
.body("EventSourceMappings[0].StartingPosition", equalTo("AT_TIMESTAMP"))
.body("EventSourceMappings[0].StartingPositionTimestamp", equalTo(1787036486.712f));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
void createStack_lambdaEventSourceMappingWithNonFiniteStartingPositionTimestampFailsResource() {
String stackName = "cfn-esm-nonfinite-timestamp-stack";
String funcName = "cfn-esm-nonfinite-timestamp-func";
String streamName = "cfn-esm-nonfinite-timestamp-stream";
// "NaN" is passed as a JSON string since JSON itself has no NaN/Infinity literal;
// Double.parseDouble happily accepts it, which is exactly what the isFinite guard exists to catch.
String template = """
{
"Resources": {
"MyStream": {
"Type": "AWS::Kinesis::Stream",
"Properties": {
"Name": "%s",
"ShardCount": 1
}
},
"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 });"
}
}
},
"MyESM": {
"Type": "AWS::Lambda::EventSourceMapping",
"Properties": {
"FunctionName": { "Ref": "MyFunction" },
"EventSourceArn": { "Fn::GetAtt": ["MyStream", "Arn"] },
"StartingPosition": "AT_TIMESTAMP",
"StartingPositionTimestamp": "NaN",
"BatchSize": 5
}
}
}
}
""".formatted(streamName, funcName);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("CREATE_FAILED"));
}
@Test
void crossStackReference_fnImportValue() {
// Stack A exports a bucket name
@@ -1,14 +1,18 @@
package io.github.hectorvent.floci.services.lambda;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.config.JsonPathConfig;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.math.BigDecimal;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -29,6 +33,8 @@ class EsmIntegrationTest {
"arn:aws:sqs:" + REGION + ":" + ACCOUNT_ID + ":" + QUEUE_NAME;
private static final String FUNCTION_ARN =
"arn:aws:lambda:" + REGION + ":" + ACCOUNT_ID + ":function:" + FUNCTION_NAME;
private static final String STREAM_ARN =
"arn:aws:kinesis:" + REGION + ":" + ACCOUNT_ID + ":stream/esm-test-stream";
private static final String NON_DEFAULT_ACCOUNT = "000000000001";
private static final String MULTI_ACCOUNT_QUEUE_NAME = "esm-multi-account-queue";
private static final String MULTI_ACCOUNT_FUNCTION_NAME = "esm-multi-account-fn";
@@ -723,6 +729,176 @@ class EsmIntegrationTest {
}
}
// ──────────────────────────── StartingPosition ────────────────────────────
@Test
@Order(70)
void createEventSourceMappingWithStartingPositionRoundTrips() {
String uuid = given()
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"EventSourceArn": "%s",
"StartingPosition": "LATEST"
}
""".formatted(FUNCTION_NAME, STREAM_ARN))
.when()
.post(LAMBDA_BASE + "/event-source-mappings")
.then()
.statusCode(202)
.body("StartingPosition", equalTo("LATEST"))
.extract()
.path("UUID");
given()
.when()
.get(LAMBDA_BASE + "/event-source-mappings/" + uuid)
.then()
.statusCode(200)
.body("StartingPosition", equalTo("LATEST"));
// List has its own response-building path, and Terraform refreshes through it too.
given()
.queryParam("FunctionName", FUNCTION_NAME)
.when()
.get(LAMBDA_BASE + "/event-source-mappings")
.then()
.statusCode(200)
.body("EventSourceMappings.find { it.UUID == '" + uuid + "' }.StartingPosition",
equalTo("LATEST"));
given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202);
}
@Test
@Order(71)
void createEventSourceMappingWithAtTimestampRoundTripsItsTimestamp() {
double startingPositionTimestamp = 1787036486.712;
String uuid = given()
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"EventSourceArn": "%s",
"StartingPosition": "AT_TIMESTAMP",
"StartingPositionTimestamp": %s
}
""".formatted(FUNCTION_NAME, STREAM_ARN, startingPositionTimestamp))
.when()
.post(LAMBDA_BASE + "/event-source-mappings")
.then()
.statusCode(202)
.body("StartingPosition", equalTo("AT_TIMESTAMP"))
.extract()
.path("UUID");
// Lambda is a restJson1 service, so the timestamp goes out as epoch seconds — the same
// convention it came in on, and the one LastModified already uses. Read as BigDecimal
// because RestAssured's default float mapping cannot hold millisecond precision at this
// magnitude, and would report a passing round-trip as a ~57s drift.
BigDecimal returned = given()
.when()
.get(LAMBDA_BASE + "/event-source-mappings/" + uuid)
.then()
.statusCode(200)
.body("StartingPosition", equalTo("AT_TIMESTAMP"))
.extract()
.jsonPath(new JsonPathConfig(JsonPathConfig.NumberReturnType.BIG_DECIMAL))
.get("StartingPositionTimestamp");
assertEquals(startingPositionTimestamp, returned.doubleValue(), 0.001);
given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202);
}
@Test
@Order(72)
void responseOmitsStartingPositionWhenUnset() {
// AWS omits the field on mappings that have none (SQS sources never do) rather than
// returning it as null.
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("$", not(hasKey("StartingPosition")))
.body("$", not(hasKey("StartingPositionTimestamp")))
.extract()
.path("UUID");
given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202);
}
@Test
@Order(73)
void createEventSourceMappingRejectsUnknownStartingPosition() {
given()
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"EventSourceArn": "%s",
"StartingPosition": "AT_SEQUENCE_NUMBER"
}
""".formatted(FUNCTION_NAME, STREAM_ARN))
.when()
.post(LAMBDA_BASE + "/event-source-mappings")
.then()
.statusCode(400)
.body("message", containsString("TRIM_HORIZON, LATEST, AT_TIMESTAMP"));
}
@Test
@Order(74)
void createEventSourceMappingRejectsAtTimestampWithoutATimestamp() {
given()
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"EventSourceArn": "%s",
"StartingPosition": "AT_TIMESTAMP"
}
""".formatted(FUNCTION_NAME, STREAM_ARN))
.when()
.post(LAMBDA_BASE + "/event-source-mappings")
.then()
.statusCode(400)
.body("message", containsString("StartingPositionTimestamp is required"));
}
@Test
@Order(75)
void createEventSourceMappingRejectsAtTimestampOnANonKinesisSource() {
String dynamoStreamArn =
"arn:aws:dynamodb:" + REGION + ":" + ACCOUNT_ID
+ ":table/esm-at-timestamp-table/stream/2026-01-01T00:00:00.000";
given()
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"EventSourceArn": "%s",
"StartingPosition": "AT_TIMESTAMP",
"StartingPositionTimestamp": 1787036486.712
}
""".formatted(FUNCTION_NAME, dynamoStreamArn))
.when()
.post(LAMBDA_BASE + "/event-source-mappings")
.then()
.statusCode(400)
.body("message", containsString("only supported for Amazon Kinesis"));
}
// ──────────────────────────── Multi-account ESM ────────────────────────────
/**