fix(lambda): validate members the model bounds (ESM Topics, S3 code, alias, LicenseInfo) (#4989)

* fix(lambda): enforce Topics and SourceAccessConfigurations limits on event source mappings

CreateEventSourceMapping and UpdateEventSourceMapping only checked that
Topics was a non-empty list of strings. The model allows at most one
topic, each 1-249 characters matching [^.]([a-zA-Z0-9\-_.]+), and at most
23 SourceAccessConfigurations. Both paths now reject a violation with the
ValidationException message the other Lambda member checks use; the update
path checks before it applies any change.

EsmIntegrationTest.createSelfManagedKafkaEventSourceMapping created a
mapping with two topics, which AWS rejects, so it now uses one.

Refs #4607

* fix(lambda): validate the UpdateFunctionCode S3Bucket and S3Key members

UpdateFunctionCode passed S3Bucket and S3Key straight to the S3 fetch, so a malformed value came back as ServiceUnavailableException. The model limits S3Bucket to 3-63 characters matching [0-9A-Za-z\.\-_]*(?<!\.) and S3Key to 1-1024; both are now checked before the function changes, with the Lambda ValidationException format.

Refs #4607

* fix(lambda): validate alias FunctionVersion and Description

CreateAlias and UpdateAlias stored any FunctionVersion and Description. The model limits FunctionVersion to 1-1024 characters matching (\$LATEST(\.PUBLISHED)?|[0-9]+) and Description to 256; both methods now check them before touching the alias, with the Lambda ValidationException format.

Refs #4607

* fix(lambda): validate the PublishLayerVersion LicenseInfo length

PublishLayerVersion stored a LicenseInfo of any length; the model caps it at 512 characters. It now reuses LambdaService.validateMaxLength (made package-private, like validateEnumList, which the layer service already calls).

Fixes #4607

* fix(lambda): validate empty topics and cap SourceAccessConfigurations for every ESM source

An empty Topic now fails the Topic shape's min length with a ValidationException, the 23-entry SourceAccessConfigurations cap applies to ARN sources as well as self-managed Kafka, and the shared max-items check is reused. Tests: one-topic CloudFormation Kafka case, update leaves stored fields unchanged.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-10-09 23:34:44 -04:00
1 parent fdb21de095
commit c3133f14c3
6 files changed
+269 -17

No files matched your search

@@ -123,6 +123,7 @@ public class LambdaLayerService {
String description = (String) request.get("Description");
String licenseInfo = (String) request.get("LicenseInfo");
LambdaService.validateMaxLength(licenseInfo, "licenseInfo", 512);
LambdaService.validateEnumList(request.get("CompatibleRuntimes"), "compatibleRuntimes",
LambdaService.RUNTIME_VALUES, 15);
@@ -88,6 +88,15 @@ public class LambdaService implements ResourceProvider {
+ "\\d{12}:access-point/fsap-[a-f0-9]{17}$");
private static final Pattern FILE_SYSTEM_LOCAL_MOUNT_PATH = Pattern.compile("^/mnt/[A-Za-z0-9._-]+$");
private static final Pattern LOG_GROUP_PATTERN = Pattern.compile("[.\\-_/#A-Za-z0-9]+");
// The model's Topic shape: 1-249 characters, pattern [^.]([a-zA-Z0-9\-_.]+); Topics holds at most 1.
private static final Pattern TOPIC_PATTERN = Pattern.compile("[^.]([a-zA-Z0-9\\-_.]+)");
private static final int MAX_TOPIC_LENGTH = 249;
private static final int MAX_TOPICS = 1;
private static final int MAX_SOURCE_ACCESS_CONFIGURATIONS = 23;
// UpdateFunctionCode S3Bucket (3-63 characters, [0-9A-Za-z\.\-_]*(?<!\.)) and S3Key (1-1024) shapes.
private static final Pattern S3_BUCKET_PATTERN = Pattern.compile("[0-9A-Za-z\\.\\-_]*(?<!\\.)");
// Create/UpdateAlias FunctionVersion (VersionWithLatestPublished: 1-1024, pattern below) and Description (max 256).
private static final Pattern ALIAS_FUNCTION_VERSION_PATTERN = Pattern.compile("(\\$LATEST(\\.PUBLISHED)?|[0-9]+)");
// The model's own Role pattern, which AWS quotes verbatim in its validation message; it
// already accepts every partition.
private static final Pattern ROLE_ARN_PATTERN = Pattern.compile(
@@ -739,6 +748,7 @@ public class LambdaService implements ResourceProvider {
String imageUri = (String) request.get("ImageUri");
String s3Bucket = (String) request.get("S3Bucket");
String s3Key = (String) request.get("S3Key");
validateS3CodeLocation(s3Bucket, s3Key);
requireMatchingRevisionId(fn, request);
@@ -1375,6 +1385,11 @@ public class LambdaService implements ResourceProvider {
boolean hasEventSourceArn = request.containsKey("EventSourceArn") && request.get("EventSourceArn") != null;
boolean isSelfManagedKafka = hasKafkaSource || hasTopics;
// The SourceAccessConfigurations cap applies to every source type, not only self-managed Kafka
if (request.get("SourceAccessConfigurations") instanceof List<?> accessToCap) {
validateMaxItems(accessToCap, "sourceAccessConfigurations", MAX_SOURCE_ACCESS_CONFIGURATIONS);
}
String eventSourceArn;
String resolvedRegion;
Map<String, Object> selfManagedEventSource = null;
@@ -1429,6 +1444,7 @@ public class LambdaService implements ResourceProvider {
throw new AwsException("InvalidParameterValueException",
"Topics must be a non-empty list of strings", 400);
}
validateTopicConstraints(topicList);
List<String> validatedTopics = new ArrayList<>();
for (Object item : topicList) {
if (!(item instanceof String s) || s.isBlank()) {
@@ -2150,6 +2166,7 @@ public class LambdaService implements ResourceProvider {
throw new AwsException("InvalidParameterValueException",
"Topics must be a non-empty list of strings", 400);
}
validateTopicConstraints(topicList);
List<String> validatedTopics = new ArrayList<>();
for (Object item : topicList) {
if (!(item instanceof String s) || s.isBlank()) {
@@ -2168,6 +2185,7 @@ public class LambdaService implements ResourceProvider {
throw new AwsException("InvalidParameterValueException",
"SourceAccessConfigurations must be a list", 400);
}
validateMaxItems(accessList, "sourceAccessConfigurations", MAX_SOURCE_ACCESS_CONFIGURATIONS);
List<Map<String, Object>> typedAccess = new ArrayList<>();
for (Object item : accessList) {
if (!(item instanceof Map<?, ?> m)) {
@@ -2721,11 +2739,7 @@ public class LambdaService implements ResourceProvider {
if (!(requireListOrNull(value, field) instanceof List<?> list)) {
return;
}
if (list.size() > maxItems) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at '" + field + "' failed to satisfy constraint: "
+ "Member must have length less than or equal to " + maxItems, 400);
}
validateMaxItems(list, field, maxItems);
for (Object item : list) {
validateEnum(item, field + ".member", allowed);
}
@@ -2748,11 +2762,7 @@ public class LambdaService implements ResourceProvider {
if (!(requireListOrNull(value, field) instanceof List<?> list)) {
return;
}
if (list.size() > maxItems) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at '" + field + "' failed to satisfy constraint: "
+ "Member must have length less than or equal to " + maxItems, 400);
}
validateMaxItems(list, field, maxItems);
for (Object item : list) {
validatePattern(item, field + ".member", pattern);
}
@@ -2768,7 +2778,51 @@ public class LambdaService implements ResourceProvider {
}
}
private static void validateMaxLength(Object value, String field, int maxLength) {
/** Topics: at most MAX_TOPICS entries, each 1 to MAX_TOPIC_LENGTH characters matching TOPIC_PATTERN. */
private static void validateTopicConstraints(List<?> topics) {
for (Object topic : topics) {
if (topic instanceof String s) {
validateNonEmpty(s, "topics.member", false);
}
}
validateArnList(topics, "topics", TOPIC_PATTERN, MAX_TOPICS);
for (Object topic : topics) {
validateMaxLength(topic, "topics.member", MAX_TOPIC_LENGTH);
}
}
private static void validateS3CodeLocation(String bucket, String key) {
if (bucket != null) {
if (bucket.length() < 3) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + bucket + "' at 's3Bucket' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 3", 400);
}
validateMaxLength(bucket, "s3Bucket", 63);
validatePattern(bucket, "s3Bucket", S3_BUCKET_PATTERN);
}
if (key != null) {
validateNonEmpty(key, "s3Key", false);
validateMaxLength(key, "s3Key", 1024);
}
}
private static void validateAliasMembers(String functionVersion, String description) {
validateNonEmpty(functionVersion, "functionVersion", false);
validateMaxLength(functionVersion, "functionVersion", 1024);
validatePattern(functionVersion, "functionVersion", ALIAS_FUNCTION_VERSION_PATTERN);
validateMaxLength(description, "description", 256);
}
private static void validateMaxItems(List<?> list, String field, int maxItems) {
if (list.size() > maxItems) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at '" + field + "' failed to satisfy constraint: "
+ "Member must have length less than or equal to " + maxItems, 400);
}
}
static void validateMaxLength(Object value, String field, int maxLength) {
if (!(value instanceof String s) || s.length() <= maxLength) {
return;
}
@@ -2899,6 +2953,7 @@ public class LambdaService implements ResourceProvider {
String functionVersion, String description,
java.util.Map<String, Double> routingConfig) {
validateAliasName(aliasName);
validateAliasMembers(functionVersion, description);
LambdaFunction fn = getFunction(region, functionName);
functionName = fn.getFunctionName();
if (aliasStore != null && aliasStore.get(region, functionName, aliasName).isPresent()) {
@@ -2940,6 +2995,7 @@ public class LambdaService implements ResourceProvider {
String functionVersion, String description,
java.util.Map<String, Double> routingConfig) {
validateAliasName(aliasName);
validateAliasMembers(functionVersion, description);
LambdaAlias alias = getAlias(region, functionName, aliasName);
if (functionVersion != null) alias.setFunctionVersion(functionVersion);
if (description != null) alias.setDescription(description);
@@ -5433,7 +5433,7 @@ class CloudFormationIntegrationTest {
"FunctionName": { "Ref": "MyFunction" },
"Enabled": true,
"BatchSize": 100,
"Topics": ["orders-topic", "events-topic"],
"Topics": ["orders-topic"],
"SelfManagedEventSource": {
"Endpoints": {
"KAFKA_BOOTSTRAP_SERVERS": ["kafka-broker-1:9092", "kafka-broker-2:9092"]
@@ -5511,9 +5511,8 @@ class CloudFormationIntegrationTest {
// Verify Topics
JsonNode topics = esmNode.path("Topics");
assertTrue(topics.isArray() && topics.size() == 2);
assertTrue(topics.isArray() && topics.size() == 1);
assertEquals("orders-topic", topics.get(0).asText());
assertEquals("events-topic", topics.get(1).asText());
// Verify SelfManagedEventSource
JsonNode smes = esmNode.path("SelfManagedEventSource");
@@ -1066,7 +1066,7 @@ class EsmIntegrationTest {
"KAFKA_BOOTSTRAP_SERVERS": ["b-1.example.com:9092", "b-2.example.com:9092"]
}
},
"Topics": ["orders", "payments"],
"Topics": ["orders"],
"StartingPosition": "TRIM_HORIZON"
}
""".formatted(FUNCTION_NAME))
@@ -1079,7 +1079,7 @@ class EsmIntegrationTest {
.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("Topics", hasItems("orders"))
.body("StartingPosition", equalTo("TRIM_HORIZON"))
.extract()
.path("UUID");
@@ -1094,7 +1094,7 @@ class EsmIntegrationTest {
.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("Topics", hasItems("orders"))
.body("StartingPosition", equalTo("TRIM_HORIZON"));
// Verify DELETE by UUID
@@ -141,6 +141,22 @@ class LambdaLayerCodePathIsolationTest {
return serviceFor(baseDir, account, new LambdaLayerStore(AccountAwareStorageBackend.inMemory(account)));
}
@Test
void publishLayerVersion_licenseInfoLongerThan512_isRejected(@TempDir Path baseDir) throws Exception {
// Catches: PublishLayerVersion storing a LicenseInfo over the model's 512-character maximum
LambdaLayerService service = serviceFor(baseDir, "111111111111",
new LambdaLayerStore(AccountAwareStorageBackend.inMemory("111111111111")));
Map<String, Object> request = Map.of("Content", Map.of("ZipFile", zipBase64("layer")),
"LicenseInfo", "l".repeat(513));
AwsException error = assertThrows(AwsException.class,
() -> service.publishLayerVersion("us-east-1", LAYER_NAME, request));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("1 validation error detected: Value at 'licenseInfo' failed to satisfy constraint: "
+ "Member must have length less than or equal to 512", error.getMessage());
}
private static LambdaLayerService serviceFor(Path baseDir, String account, LambdaLayerStore store) {
EmulatorConfig config = mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
when(config.services().lambda().codePath()).thenReturn(baseDir.toString());
@@ -2356,4 +2356,184 @@ class LambdaServiceTest {
LambdaFunction updatedFn = service.getFunction(REGION, "revision-lock-func");
assertNotEquals(initialRevisionId, updatedFn.getRevisionId());
}
@Test
void createEventSourceMapping_moreThanOneTopic_isRejected() {
// Catches: a Topics list longer than the model's maximum of 1 is stored instead of rejected
service.createFunction(REGION, baseRequest("kafka-topics-max-fn"));
AwsException error = assertThrows(AwsException.class, () -> service.createEventSourceMapping(REGION,
kafkaMappingRequest("kafka-topics-max-fn", List.of("topic-a", "topic-b"), List.of())));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("1 validation error detected: Value at 'topics' failed to satisfy constraint: "
+ "Member must have length less than or equal to 1", error.getMessage());
}
@Test
void createEventSourceMapping_topicStartingWithADot_isRejected() {
// Catches: a Topic that doesn't match the model pattern [^.]([a-zA-Z0-9\-_.]+) is stored
service.createFunction(REGION, baseRequest("kafka-topic-pattern-fn"));
AwsException error = assertThrows(AwsException.class, () -> service.createEventSourceMapping(REGION,
kafkaMappingRequest("kafka-topic-pattern-fn", List.of(".hidden"), List.of())));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("1 validation error detected: Value '.hidden' at 'topics.member' failed to satisfy constraint: "
+ "Member must satisfy regular expression pattern: [^.]([a-zA-Z0-9\\-_.]+)", error.getMessage());
}
@Test
void createEventSourceMapping_moreThan23SourceAccessConfigurations_isRejected() {
// Catches: a SourceAccessConfigurations list longer than the model's maximum of 23 is stored
service.createFunction(REGION, baseRequest("kafka-access-max-fn"));
List<Map<String, Object>> access = new ArrayList<>();
for (int i = 0; i < 24; i++) {
access.add(Map.of("Type", "BASIC_AUTH", "URI", "arn:aws:secretsmanager:us-east-1:000000000000:secret:s" + i));
}
AwsException error = assertThrows(AwsException.class, () -> service.createEventSourceMapping(REGION,
kafkaMappingRequest("kafka-access-max-fn", List.of("my-topic"), access)));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("1 validation error detected: Value at 'sourceAccessConfigurations' failed to satisfy constraint: "
+ "Member must have length less than or equal to 23", error.getMessage());
}
@Test
void updateEventSourceMapping_moreThanOneTopic_isRejectedAndLeavesTheMappingUnchanged() {
// Catches: UpdateEventSourceMapping accepting (or half-applying) a Topics list longer than 1
service.createFunction(REGION, baseRequest("kafka-update-topics-fn"));
EventSourceMapping esm = service.createEventSourceMapping(REGION,
kafkaMappingRequest("kafka-update-topics-fn", List.of("my-topic"), List.of()));
// Floci's default BatchSize differs per source type, so compare against the value before the update
int batchSizeBefore = esm.getBatchSize();
AwsException error = assertThrows(AwsException.class, () -> service.updateEventSourceMapping(esm.getUuid(),
Map.of("BatchSize", 5, "Topics", List.of("topic-a", "topic-b"))));
assertEquals("ValidationException", error.getErrorCode());
EventSourceMapping stored = service.getEventSourceMapping(esm.getUuid());
assertEquals(List.of("my-topic"), stored.getTopics());
assertEquals(batchSizeBefore, stored.getBatchSize());
}
@Test
void createEventSourceMapping_emptyTopic_isRejectedWithAValidationException() {
// Catches: an empty Topic reaching the blank check and answering InvalidParameterValueException instead of the Topic shape's min-length ValidationException
service.createFunction(REGION, baseRequest("kafka-topic-empty-fn"));
AwsException error = assertThrows(AwsException.class, () -> service.createEventSourceMapping(REGION,
kafkaMappingRequest("kafka-topic-empty-fn", List.of(""), List.of())));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("1 validation error detected: Value '' at 'topics.member' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1", error.getMessage());
}
@Test
void createEventSourceMapping_sqsSourceWithMoreThan23SourceAccessConfigurations_isRejected() {
// Catches: the 23-entry SourceAccessConfigurations cap being enforced only for self-managed Kafka sources
service.createFunction(REGION, baseRequest("sqs-access-max-fn"));
List<Map<String, Object>> access = new ArrayList<>();
for (int i = 0; i < 24; i++) {
access.add(Map.of("Type", "BASIC_AUTH", "URI", "arn:aws:secretsmanager:us-east-1:000000000000:secret:s" + i));
}
Map<String, Object> request = new HashMap<>();
request.put("FunctionName", "sqs-access-max-fn");
request.put("EventSourceArn", "arn:aws:sqs:us-east-1:000000000000:access-max-queue");
request.put("SourceAccessConfigurations", access);
AwsException error = assertThrows(AwsException.class, () -> service.createEventSourceMapping(REGION, request));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("1 validation error detected: Value at 'sourceAccessConfigurations' failed to satisfy constraint: "
+ "Member must have length less than or equal to 23", error.getMessage());
}
@Test
void updateEventSourceMapping_moreThan23SourceAccessConfigurations_isRejectedAndLeavesTheMappingUnchanged() {
// Catches: UpdateEventSourceMapping accepting (or half-applying) more than 23 SourceAccessConfigurations
service.createFunction(REGION, baseRequest("kafka-update-access-fn"));
EventSourceMapping esm = service.createEventSourceMapping(REGION,
kafkaMappingRequest("kafka-update-access-fn", List.of("my-topic"), List.of()));
int batchSizeBefore = esm.getBatchSize();
List<Map<String, Object>> accessBefore = esm.getSourceAccessConfigurations();
List<Map<String, Object>> access = new ArrayList<>();
for (int i = 0; i < 24; i++) {
access.add(Map.of("Type", "BASIC_AUTH", "URI", "arn:aws:secretsmanager:us-east-1:000000000000:secret:s" + i));
}
AwsException error = assertThrows(AwsException.class, () -> service.updateEventSourceMapping(esm.getUuid(),
Map.of("BatchSize", 5, "SourceAccessConfigurations", access)));
assertEquals("ValidationException", error.getErrorCode());
EventSourceMapping stored = service.getEventSourceMapping(esm.getUuid());
assertEquals(batchSizeBefore, stored.getBatchSize());
assertEquals(accessBefore, stored.getSourceAccessConfigurations());
}
private static Map<String, Object> kafkaMappingRequest(String functionName, List<String> topics,
List<Map<String, Object>> sourceAccessConfigurations) {
Map<String, Object> request = new HashMap<>();
request.put("FunctionName", functionName);
request.put("Topics", topics);
request.put("SelfManagedEventSource", Map.of("Endpoints", Map.of("KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092"))));
if (!sourceAccessConfigurations.isEmpty()) {
request.put("SourceAccessConfigurations", sourceAccessConfigurations);
}
return request;
}
@Test
void updateFunctionCode_s3BucketEndingInADot_isRejected() {
// Catches: UpdateFunctionCode accepting an S3Bucket that breaks the model pattern [0-9A-Za-z\.\-_]*(?<!\.)
service.createFunction(REGION, baseRequest("code-bucket-pattern-fn"));
AwsException error = assertThrows(AwsException.class, () -> service.updateFunctionCode(REGION,
"code-bucket-pattern-fn", Map.of("S3Bucket", "my-bucket.", "S3Key", "code.zip")));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("1 validation error detected: Value 'my-bucket.' at 's3Bucket' failed to satisfy constraint: "
+ "Member must satisfy regular expression pattern: [0-9A-Za-z\\.\\-_]*(?<!\\.)", error.getMessage());
}
@Test
void updateFunctionCode_s3KeyLongerThan1024_isRejected() {
// Catches: UpdateFunctionCode accepting an S3Key longer than the model's 1024-character maximum
service.createFunction(REGION, baseRequest("code-key-length-fn"));
AwsException error = assertThrows(AwsException.class, () -> service.updateFunctionCode(REGION,
"code-key-length-fn", Map.of("S3Bucket", "my-bucket", "S3Key", "k".repeat(1025))));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("1 validation error detected: Value at 's3Key' failed to satisfy constraint: "
+ "Member must have length less than or equal to 1024", error.getMessage());
}
@Test
void createAlias_functionVersionOutsideTheModelPattern_isRejected() {
// Catches: CreateAlias storing a FunctionVersion that isn't $LATEST, $LATEST.PUBLISHED or a number
service.createFunction(REGION, baseRequest("alias-version-fn"));
AwsException error = assertThrows(AwsException.class, () ->
service.createAlias(REGION, "alias-version-fn", "live", "v1", null, null));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("1 validation error detected: Value 'v1' at 'functionVersion' failed to satisfy constraint: "
+ "Member must satisfy regular expression pattern: (\\$LATEST(\\.PUBLISHED)?|[0-9]+)", error.getMessage());
}
@Test
void updateAlias_descriptionLongerThan256_isRejectedAndLeavesTheAliasUnchanged() {
// Catches: UpdateAlias accepting (or half-applying) a Description over the model's 256-character maximum
service.createFunction(REGION, baseRequest("alias-description-fn"));
service.createAlias(REGION, "alias-description-fn", "live", "$LATEST", "original", null);
AwsException error = assertThrows(AwsException.class, () ->
service.updateAlias(REGION, "alias-description-fn", "live", "$LATEST", "d".repeat(257), null));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("original", service.getAlias(REGION, "alias-description-fn", "live").getDescription());
}
}