mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
Validate the compact UTF-8 JSON environment before function creation or configuration mutation. Both paths previously accepted the 5,000-character value reported in #7995. Cover exact byte boundaries, aggregate variables, Unicode, JSON escaping, and rejected-update atomicity through the AWS SDK. Stop quota serialization through a bounded UTF-8 counting sink without allocating complete JSON and byte-array copies. Keep unchanged legacy environments out of CloudFormation configuration updates while validating changed variables and preserving environment removal. Add early-stop, one-megabyte input, Unicode buffer-boundary, and legacy-stack rollback regressions. Include AWS's String measured diagnostic while retaining at most 5,120 UTF-8 bytes and terminating larger input early. Drop incomplete trailing UTF-8 characters before adding an ellipsis. Keep the 1 MB robustness request on CreateFunction, and assert every SDK configuration-update body stays below the separate 5,120-byte request limit. Cover complete measured JSON and bounded Unicode previews.
This commit is contained in:
1 parent
33968bca39
commit
b2fa9b3f6c
6 files changed
+526
-4
No files matched your search
@@ -75,6 +75,22 @@ Floci Lambda runs your function code locally inside real Docker containers - clo
|
||||
supported ranges before changing any stored settings. A rejected value returns
|
||||
`InvalidParameterValueException` and leaves the function configuration unchanged.
|
||||
|
||||
`CreateFunction` and `UpdateFunctionConfiguration` enforce the 4 KB environment-variable
|
||||
limit. The compact JSON `Variables` object must fit within 4,096 UTF-8 bytes, including
|
||||
keys, values, punctuation, and JSON escaping, as described in the
|
||||
[AWS deployment guidance](https://docs.aws.amazon.com/lambda/latest/dg/troubleshooting-deployment.html).
|
||||
An oversized environment returns HTTP 400 with `InvalidParameterValueException` before
|
||||
creating a function or changing any stored configuration. Omitting `Environment` on an
|
||||
update preserves the existing variables; an empty `Variables` object clears them.
|
||||
Validation stops serializing oversized input without allocating full JSON and UTF-8 copies.
|
||||
Quota errors include AWS's `String measured:` detail. The diagnostic retains up to 5,120
|
||||
UTF-8 bytes of compact variables JSON; larger inputs end with `...`, dropping any incomplete
|
||||
trailing UTF-8 character. This keeps diagnostic allocation and serialization bounded.
|
||||
CloudFormation omits unchanged environment variables during in-place configuration updates,
|
||||
so a function persisted before quota enforcement can retain an oversized environment when
|
||||
another property changes. Changing or removing its variables still updates the environment
|
||||
and enforces the quota.
|
||||
|
||||
The event invoke configuration is stored and returned as AWS does, and `AWS::Lambda::EventInvokeConfig`
|
||||
provisions it from a stack. A SAM function's `EventInvokeConfig` expands into that resource as
|
||||
`sam deploy` does: on `$LATEST`, or on the `AutoPublishAlias` alias, with the inline role policy for
|
||||
|
||||
+5
-1
@@ -411,8 +411,12 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
|
||||
StackResource r) {
|
||||
LambdaFunction current = existing;
|
||||
if (lambdaConfigurationChanged(current, desired.configRequest())) {
|
||||
Map<String, Object> configuration = new HashMap<>(desired.configRequest());
|
||||
if (Objects.equals(current.getEnvironment(), environmentVariables(configuration.get("Environment")))) {
|
||||
configuration.remove("Environment");
|
||||
}
|
||||
current = lambdaService.updateFunctionConfiguration(region, current.getFunctionName(),
|
||||
desired.configRequest());
|
||||
configuration);
|
||||
}
|
||||
if (lambdaCodeChanged(current, desired.code(), r.getAttributes().get(LAMBDA_CODE_IDENTITY_ATTR))) {
|
||||
current = lambdaService.updateFunctionCode(region, current.getFunctionName(), desired.code().request());
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
@@ -53,8 +54,13 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.InvalidPathException;
|
||||
@@ -111,6 +117,8 @@ public class LambdaService implements ResourceProvider {
|
||||
private static final int MAX_SOURCE_ACCESS_CONFIGURATIONS = 23;
|
||||
private static final int LIST_FUNCTIONS_PAGE_SIZE = 50;
|
||||
private static final int MAX_LIST_FUNCTIONS_ITEMS = 10_000;
|
||||
private static final int MAX_ENVIRONMENT_BYTES = 4096;
|
||||
private static final int MAX_ENVIRONMENT_DIAGNOSTIC_BYTES = 5120;
|
||||
// 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).
|
||||
@@ -2843,12 +2851,67 @@ public class LambdaService implements ResourceProvider {
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, String> environmentVariables(Map<String, Object> environment) {
|
||||
private Map<String, String> environmentVariables(Map<String, Object> environment) {
|
||||
if (environment == null) {
|
||||
return null;
|
||||
}
|
||||
return (Map<String, String>) (Map<?, ?>) structureValue(
|
||||
Map<String, String> variables = (Map<String, String>) (Map<?, ?>) structureValue(
|
||||
environment.get("Variables"), "Environment.Variables");
|
||||
if (variables != null) {
|
||||
EnvironmentSizeOutputStream output = new EnvironmentSizeOutputStream();
|
||||
// A Writer preserves Unicode characters; Jackson's byte generator escapes surrogate pairs.
|
||||
try (OutputStreamWriter writer = new OutputStreamWriter(output, StandardCharsets.UTF_8)) {
|
||||
objectMapper.writer().without(SerializationFeature.INDENT_OUTPUT).writeValue(writer, variables);
|
||||
} catch (IOException e) {
|
||||
if (!output.truncated) {
|
||||
throw new AwsException("SerializationException", "Environment.Variables could not be serialized", 400);
|
||||
}
|
||||
}
|
||||
if (output.size > MAX_ENVIRONMENT_BYTES) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"Lambda was unable to configure your environment variables because the environment variables "
|
||||
+ "you have provided exceeded the 4KB limit. String measured: " + output.measuredString(),
|
||||
400);
|
||||
}
|
||||
}
|
||||
return variables;
|
||||
}
|
||||
|
||||
private static final class EnvironmentSizeOutputStream extends OutputStream {
|
||||
private final byte[] measured = new byte[MAX_ENVIRONMENT_DIAGNOSTIC_BYTES];
|
||||
private int size;
|
||||
private boolean truncated;
|
||||
|
||||
@Override
|
||||
public void write(int value) throws IOException {
|
||||
if (size == measured.length) {
|
||||
overflow();
|
||||
}
|
||||
measured[size++] = (byte) value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] source, int offset, int length) throws IOException {
|
||||
Objects.checkFromIndexSize(offset, length, source.length);
|
||||
int copied = Math.min(length, measured.length - size);
|
||||
System.arraycopy(source, offset, measured, size, copied);
|
||||
size += copied;
|
||||
if (copied < length) {
|
||||
overflow();
|
||||
}
|
||||
}
|
||||
|
||||
private void overflow() throws IOException {
|
||||
truncated = true;
|
||||
throw new IOException("Environment exceeds the diagnostic capture limit");
|
||||
}
|
||||
|
||||
private String measuredString() {
|
||||
CharBuffer decoded = CharBuffer.allocate(size);
|
||||
StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.IGNORE)
|
||||
.decode(ByteBuffer.wrap(measured, 0, size), decoded, true);
|
||||
return decoded.flip().toString() + (truncated ? "..." : "");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+38
-1
@@ -51,13 +51,14 @@ class LambdaCfnProvisionerTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
// Scalar properties and flat tag lists only, so a passthrough engine keeps this isolated.
|
||||
// Literal properties only, so a passthrough engine keeps this isolated.
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null || node.isMissingNode() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
when(engine.omitNoValue(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, REGION, "000000000000", "my-stack");
|
||||
}
|
||||
|
||||
@@ -165,6 +166,42 @@ class LambdaCfnProvisionerTest {
|
||||
assertEquals("team", r.getAttributes().get(TEMPLATE_TAG_KEYS_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unrelatedUpdateOmitsAnUnchangedLegacyOversizedEnvironment() {
|
||||
Map<String, String> variables = Map.of("BIG", "x".repeat(5000));
|
||||
stubInPlaceUpdate("my-fn", Map.of()).setEnvironment(variables);
|
||||
ObjectNode props = props("my-fn").put("Description", "updated description");
|
||||
props.putObject("Environment").set("Variables", mapper.valueToTree(variables));
|
||||
|
||||
provisioner.provision(function("my-fn"), props, updateCtx("my-fn"));
|
||||
|
||||
verify(lambda).updateFunctionConfiguration(eq(REGION), eq("my-fn"), argThat(request ->
|
||||
!request.containsKey("Environment") && "updated description".equals(request.get("Description"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changedEnvironmentStillReachesLambdaValidation() {
|
||||
stubInPlaceUpdate("my-fn", Map.of()).setEnvironment(Map.of("MARKER", "original"));
|
||||
Map<String, String> variables = Map.of("BIG", "x".repeat(5000));
|
||||
ObjectNode props = props("my-fn");
|
||||
props.putObject("Environment").set("Variables", mapper.valueToTree(variables));
|
||||
|
||||
provisioner.provision(function("my-fn"), props, updateCtx("my-fn"));
|
||||
|
||||
verify(lambda).updateFunctionConfiguration(eq(REGION), eq("my-fn"), argThat(request ->
|
||||
Map.of("Variables", variables).equals(request.get("Environment"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void removingEnvironmentStillClearsStoredVariables() {
|
||||
stubInPlaceUpdate("my-fn", Map.of()).setEnvironment(Map.of("MARKER", "original"));
|
||||
|
||||
provisioner.provision(function("my-fn"), props("my-fn"), updateCtx("my-fn"));
|
||||
|
||||
verify(lambda).updateFunctionConfiguration(eq(REGION), eq("my-fn"), argThat(request ->
|
||||
Map.of("Variables", Map.of()).equals(request.get("Environment"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inPlaceUpdateWithTheTagsPropertyGoneUntagsOnlyTheTemplateKeys() {
|
||||
stubInPlaceUpdate("my-fn", Map.of("team", "a", "env", "dev", "oob", "x"));
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
package io.floci.aws.services.lambda;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.services.lambda.model.LambdaFunction;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.core.interceptor.Context;
|
||||
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
|
||||
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.lambda.LambdaClient;
|
||||
import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest;
|
||||
import software.amazon.awssdk.services.lambda.model.Environment;
|
||||
import software.amazon.awssdk.services.lambda.model.FunctionCode;
|
||||
import software.amazon.awssdk.services.lambda.model.GetFunctionConfigurationResponse;
|
||||
import software.amazon.awssdk.services.lambda.model.InvalidParameterValueException;
|
||||
import software.amazon.awssdk.services.lambda.model.ResourceNotFoundException;
|
||||
import software.amazon.awssdk.services.lambda.model.UpdateFunctionConfigurationRequest;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@QuarkusTest
|
||||
class LambdaEnvironmentSizeIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "799500000001";
|
||||
private final List<String> functions = new ArrayList<>();
|
||||
private LambdaClient client;
|
||||
|
||||
@Inject
|
||||
LambdaFunctionStore functionStore;
|
||||
|
||||
@BeforeEach
|
||||
void openClient() {
|
||||
client = AwsTestClients.create(LambdaClient.builder().overrideConfiguration(configuration -> configuration
|
||||
.addExecutionInterceptor(new ExecutionInterceptor() {
|
||||
@Override
|
||||
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes attributes) {
|
||||
if (context.request() instanceof UpdateFunctionConfigurationRequest) {
|
||||
long length = context.requestBody().orElseThrow().contentLength();
|
||||
assertTrue(length < 5120,
|
||||
"Update bodies must stay below the separate 5,120-byte request limit: " + length);
|
||||
}
|
||||
}
|
||||
})), ACCOUNT, Region.US_EAST_1);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() {
|
||||
try {
|
||||
for (String name : functions) {
|
||||
client.deleteFunction(request -> request.functionName(name));
|
||||
}
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("oversizedEnvironments")
|
||||
void createRejectsOversizedEnvironmentWithoutCreatingFunction(Map<String, String> variables) throws IOException {
|
||||
String name = functionName();
|
||||
CreateFunctionRequest request = functionRequest(name).environment(environment(variables)).build();
|
||||
|
||||
InvalidParameterValueException error = assertThrows(InvalidParameterValueException.class,
|
||||
() -> client.createFunction(request));
|
||||
|
||||
assertQuotaError(error);
|
||||
assertMeasuredJson(error, variables);
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> client.getFunctionConfiguration(get -> get.functionName(name)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("oversizedEnvironments")
|
||||
void rejectedUpdatePreservesConfiguration(Map<String, String> variables) throws IOException {
|
||||
String name = createFunction(Map.of("MARKER", "original"));
|
||||
GetFunctionConfigurationResponse original = configuration(name);
|
||||
|
||||
InvalidParameterValueException error = assertThrows(InvalidParameterValueException.class,
|
||||
() -> client.updateFunctionConfiguration(request -> request.functionName(name)
|
||||
.description("rejected update").timeout(60).memorySize(512)
|
||||
.environment(environment(variables))));
|
||||
|
||||
assertQuotaError(error);
|
||||
assertMeasuredJson(error, variables);
|
||||
GetFunctionConfigurationResponse unchanged = configuration(name);
|
||||
assertEquals(original.environment(), unchanged.environment());
|
||||
assertEquals(original.description(), unchanged.description());
|
||||
assertEquals(original.timeout(), unchanged.timeout());
|
||||
assertEquals(original.memorySize(), unchanged.memorySize());
|
||||
assertEquals(original.revisionId(), unchanged.revisionId());
|
||||
assertEquals(original.lastModified(), unchanged.lastModified());
|
||||
assertEquals(original.lastUpdateStatus(), unchanged.lastUpdateStatus());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("acceptedEnvironments")
|
||||
void createAndUpdateAcceptEnvironmentWithinLimit(Map<String, String> variables) throws IOException {
|
||||
String name = createFunction(variables);
|
||||
assertEnvironment(name, variables);
|
||||
|
||||
client.updateFunctionConfiguration(request -> request.functionName(name)
|
||||
.environment(environment(Map.of("MARKER", "replacement"))));
|
||||
client.updateFunctionConfiguration(request -> request.functionName(name).environment(environment(variables)));
|
||||
|
||||
assertEnvironment(name, variables);
|
||||
}
|
||||
|
||||
@Test
|
||||
void omittedEnvironmentPreservesVariablesAndEmptyVariablesClearThem() throws IOException {
|
||||
String name = createFunction(Map.of("BIG", "x".repeat(4086)));
|
||||
|
||||
client.updateFunctionConfiguration(request -> request.functionName(name).description("updated"));
|
||||
assertEquals(Map.of("BIG", "x".repeat(4086)), configuration(name).environment().variables());
|
||||
|
||||
client.updateFunctionConfiguration(request -> request.functionName(name).environment(environment(Map.of())));
|
||||
assertNull(configuration(name).environment());
|
||||
}
|
||||
|
||||
@Test
|
||||
void substantiallyOversizedCreateReturnsABoundedMeasuredJsonPreview() throws IOException {
|
||||
String name = functionName();
|
||||
Map<String, String> variables = Map.of("BIG", "x".repeat(1_000_000));
|
||||
CreateFunctionRequest request = functionRequest(name).environment(environment(variables)).build();
|
||||
|
||||
InvalidParameterValueException error = assertThrows(InvalidParameterValueException.class,
|
||||
() -> client.createFunction(request));
|
||||
|
||||
assertQuotaError(error);
|
||||
String measured = measuredJson(error);
|
||||
assertTrue(measured.startsWith("{\"BIG\":\"" + "x".repeat(100)));
|
||||
assertTrue(measured.endsWith("..."));
|
||||
assertTrue(measured.getBytes(StandardCharsets.UTF_8).length <= 5123);
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> client.getFunctionConfiguration(get -> get.functionName(name)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cloudFormationUpdatesLegacyEnvironmentOnlyWhenVariablesChange() throws IOException {
|
||||
String stackName = "legacy-environment-" + UUID.randomUUID();
|
||||
String name = functionName();
|
||||
Map<String, String> legacy = Map.of("BIG", "x".repeat(5000));
|
||||
try (CloudFormationClient cloudFormation = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), ACCOUNT, Region.US_EAST_1)) {
|
||||
cloudFormation.createStack(request -> request.stackName(stackName)
|
||||
.templateBody(stackTemplate(name, "original", Map.of("MARKER", "original"))));
|
||||
try {
|
||||
CfnStackWaits.awaitStatus(cloudFormation, stackName, "CREATE_COMPLETE");
|
||||
// Seed the stored state of a function created before quota enforcement existed.
|
||||
LambdaFunction stored = functionStore.getForAccount(ACCOUNT, "us-east-1", name).orElseThrow();
|
||||
stored.setEnvironment(legacy);
|
||||
functionStore.saveForAccount(ACCOUNT, "us-east-1", stored);
|
||||
|
||||
updateStack(cloudFormation, stackName, stackTemplate(name, "updated", legacy));
|
||||
assertEquals("updated", configuration(name).description());
|
||||
assertEnvironment(name, legacy);
|
||||
assertThrows(InvalidParameterValueException.class, () -> client.updateFunctionConfiguration(
|
||||
request -> request.functionName(name).environment(environment(legacy))));
|
||||
|
||||
cloudFormation.updateStack(request -> request.stackName(stackName)
|
||||
.templateBody(stackTemplate(name, "rejected", Map.of("BIG", "x".repeat(5001)))));
|
||||
CfnStackWaits.awaitStatus(cloudFormation, stackName, "UPDATE_ROLLBACK_COMPLETE");
|
||||
assertEquals("updated", configuration(name).description());
|
||||
assertEnvironment(name, legacy);
|
||||
|
||||
updateStack(cloudFormation, stackName,
|
||||
stackTemplate(name, "reduced", Map.of("MARKER", "valid")));
|
||||
assertEnvironment(name, Map.of("MARKER", "valid"));
|
||||
|
||||
updateStack(cloudFormation, stackName, stackTemplate(name, "cleared", null));
|
||||
assertNull(configuration(name).environment());
|
||||
} finally {
|
||||
cloudFormation.deleteStack(request -> request.stackName(stackName));
|
||||
CfnStackWaits.awaitStackDeleted(stackName, "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
|
||||
+ "/20261111/us-east-1/cloudformation/aws4_request");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void updateStack(CloudFormationClient client, String name, String template) {
|
||||
client.updateStack(request -> request.stackName(name).templateBody(template));
|
||||
CfnStackWaits.awaitStatus(client, name, "UPDATE_COMPLETE");
|
||||
}
|
||||
|
||||
private static String stackTemplate(String name, String description, Map<String, String> variables) {
|
||||
Map<String, Object> properties = new HashMap<>(Map.of(
|
||||
"FunctionName", name,
|
||||
"Runtime", "nodejs20.x",
|
||||
"Handler", "index.handler",
|
||||
"Role", "arn:aws:iam::" + ACCOUNT + ":role/lambda-role",
|
||||
"Code", Map.of("ZipFile", "exports.handler = async () => 1;"),
|
||||
"Description", description));
|
||||
if (variables != null) {
|
||||
properties.put("Environment", Map.of("Variables", variables));
|
||||
}
|
||||
return new ObjectMapper().valueToTree(Map.of("Resources", Map.of("Function", Map.of(
|
||||
"Type", "AWS::Lambda::Function", "Properties", properties)))).toString();
|
||||
}
|
||||
|
||||
private static Stream<Map<String, String>> oversizedEnvironments() {
|
||||
return Stream.of(
|
||||
Map.of("BIG", "x".repeat(5000)),
|
||||
Map.of("BIG", "x".repeat(4087)),
|
||||
Map.of("AA", "x".repeat(2040), "BB", "x".repeat(2040)),
|
||||
Map.of("BIG", "é".repeat(2043) + "x"),
|
||||
Map.of("BIG", "x".repeat(4084) + "😀"),
|
||||
Map.of("BIG", "x".repeat(3991) + "😀" + "x".repeat(92)),
|
||||
Map.of("BIG", "\"".repeat(2043) + "x"),
|
||||
Map.of("BIG", "\n".repeat(2043) + "x"));
|
||||
}
|
||||
|
||||
private static Stream<Map<String, String>> acceptedEnvironments() {
|
||||
return Stream.of(
|
||||
Map.of(),
|
||||
Map.of("BIG", "x".repeat(4085)),
|
||||
Map.of("BIG", "x".repeat(4086)),
|
||||
Map.of("AA", "x".repeat(2040), "BB", "x".repeat(2039)),
|
||||
Map.of("BIG", "é".repeat(2043)),
|
||||
Map.of("BIG", "x".repeat(4082) + "😀"),
|
||||
Map.of("BIG", "x".repeat(3991) + "😀" + "x".repeat(91)),
|
||||
Map.of("BIG", "\"".repeat(2043)),
|
||||
Map.of("BIG", "\n".repeat(2043)));
|
||||
}
|
||||
|
||||
private String createFunction(Map<String, String> variables) throws IOException {
|
||||
String name = functionName();
|
||||
client.createFunction(functionRequest(name).environment(environment(variables)).build());
|
||||
functions.add(name);
|
||||
return name;
|
||||
}
|
||||
|
||||
private static CreateFunctionRequest.Builder functionRequest(String name) throws IOException {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
|
||||
zip.putNextEntry(new ZipEntry("index.js"));
|
||||
zip.write("exports.handler = async () => 1;".getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
return CreateFunctionRequest.builder().functionName(name).runtime("nodejs20.x")
|
||||
.role("arn:aws:iam::" + ACCOUNT + ":role/lambda-role").handler("index.handler")
|
||||
.description("original").timeout(10).memorySize(256)
|
||||
.code(FunctionCode.builder().zipFile(SdkBytes.fromByteArray(bytes.toByteArray())).build());
|
||||
}
|
||||
|
||||
private GetFunctionConfigurationResponse configuration(String name) {
|
||||
return client.getFunctionConfiguration(request -> request.functionName(name));
|
||||
}
|
||||
|
||||
private void assertEnvironment(String name, Map<String, String> variables) {
|
||||
GetFunctionConfigurationResponse configuration = configuration(name);
|
||||
if (variables.isEmpty()) {
|
||||
assertNull(configuration.environment());
|
||||
} else {
|
||||
assertEquals(variables, configuration.environment().variables());
|
||||
}
|
||||
}
|
||||
|
||||
private static Environment environment(Map<String, String> variables) {
|
||||
return Environment.builder().variables(variables).build();
|
||||
}
|
||||
|
||||
private static String functionName() {
|
||||
return "environment-size-" + UUID.randomUUID();
|
||||
}
|
||||
|
||||
private static void assertQuotaError(InvalidParameterValueException error) {
|
||||
assertEquals(400, error.statusCode());
|
||||
assertEquals("InvalidParameterValueException", error.awsErrorDetails().errorCode());
|
||||
assertTrue(error.awsErrorDetails().errorMessage()
|
||||
.contains("environment variables you have provided exceeded the 4KB limit"));
|
||||
}
|
||||
|
||||
private static void assertMeasuredJson(InvalidParameterValueException error, Map<String, String> variables) {
|
||||
assertEquals(new ObjectMapper().valueToTree(variables).toString(), measuredJson(error));
|
||||
}
|
||||
|
||||
private static String measuredJson(InvalidParameterValueException error) {
|
||||
String message = error.awsErrorDetails().errorMessage();
|
||||
String marker = " String measured: ";
|
||||
assertTrue(message.contains(marker), "The quota error must include AWS's measured JSON detail");
|
||||
return message.substring(message.indexOf(marker) + marker.length());
|
||||
}
|
||||
}
|
||||
@@ -29,10 +29,13 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.AbstractMap;
|
||||
import java.util.AbstractSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -44,6 +47,7 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -111,6 +115,100 @@ class LambdaServiceTest {
|
||||
assertNotNull(fn.getRevisionId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createFunctionRejectsEnvironmentOverFourKilobytes() {
|
||||
Map<String, Object> request = baseRequest("oversized-environment-create");
|
||||
request.put("Environment", Map.of("Variables", Map.of("BIG", "x".repeat(5000))));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.createFunction(REGION, request));
|
||||
|
||||
assertEquals("InvalidParameterValueException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertTrue(error.getMessage().contains("environment variables you have provided exceeded the 4KB limit"));
|
||||
AwsException missing = assertThrows(AwsException.class,
|
||||
() -> service.getFunction(REGION, "oversized-environment-create"));
|
||||
assertEquals("ResourceNotFoundException", missing.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void oversizedEnvironmentStopsSerializationBeforeTraversingTheWholeMap() {
|
||||
AtomicInteger visited = new AtomicInteger();
|
||||
Map<String, String> variables = new AbstractMap<>() {
|
||||
@Override
|
||||
public Set<Entry<String, String>> entrySet() {
|
||||
return new AbstractSet<>() {
|
||||
@Override
|
||||
public Iterator<Entry<String, String>> iterator() {
|
||||
return Stream.generate(() -> {
|
||||
int index = visited.incrementAndGet();
|
||||
if (index > 64) {
|
||||
throw new AssertionError("Quota validation traversed too much of the environment");
|
||||
}
|
||||
return Map.entry("KEY_" + index, "x".repeat(512));
|
||||
}).limit(10_000).iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return 10_000;
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
Map<String, Object> request = baseRequest("bounded-environment-create");
|
||||
request.put("Environment", Map.of("Variables", variables));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.createFunction(REGION, request));
|
||||
|
||||
assertEquals("InvalidParameterValueException", error.getErrorCode());
|
||||
assertTrue(visited.get() < 64);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"é", "😀"})
|
||||
void measuredEnvironmentPreviewIsBoundedWithoutSplittingUtf8(String character) {
|
||||
Map<String, Object> request = baseRequest("bounded-unicode-diagnostic");
|
||||
request.put("Environment", Map.of("Variables", Map.of(
|
||||
"BIG", "x".repeat(5110) + character.repeat(10_000))));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.createFunction(REGION, request));
|
||||
|
||||
assertEquals("InvalidParameterValueException", error.getErrorCode());
|
||||
String marker = " String measured: ";
|
||||
assertTrue(error.getMessage().contains(marker));
|
||||
String measured = error.getMessage().substring(error.getMessage().indexOf(marker) + marker.length());
|
||||
String expected = "{\"BIG\":\"" + "x".repeat(5110) + ("é".equals(character) ? "é" : "") + "...";
|
||||
assertEquals(expected, measured);
|
||||
assertTrue(measured.getBytes(StandardCharsets.UTF_8).length <= 5123);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateFunctionConfigurationRejectsEnvironmentOverFourKilobytes() {
|
||||
Map<String, Object> request = baseRequest("oversized-environment-update");
|
||||
request.put("Environment", Map.of("Variables", Map.of("MARKER", "original")));
|
||||
LambdaFunction original = service.createFunction(REGION, request);
|
||||
String description = original.getDescription();
|
||||
String revisionId = original.getRevisionId();
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.updateFunctionConfiguration(REGION, "oversized-environment-update", Map.of(
|
||||
"Description", "rejected update",
|
||||
"Timeout", 60,
|
||||
"MemorySize", 512,
|
||||
"Environment", Map.of("Variables", Map.of("BIG", "x".repeat(5000))))));
|
||||
|
||||
assertEquals("InvalidParameterValueException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertTrue(error.getMessage().contains("environment variables you have provided exceeded the 4KB limit"));
|
||||
LambdaFunction unchanged = service.getFunction(REGION, "oversized-environment-update");
|
||||
assertEquals(Map.of("MARKER", "original"), unchanged.getEnvironment());
|
||||
assertEquals(description, unchanged.getDescription());
|
||||
assertEquals(10, unchanged.getTimeout());
|
||||
assertEquals(256, unchanged.getMemorySize());
|
||||
assertEquals(revisionId, unchanged.getRevisionId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAndUpdateFunctionFileSystemConfig() {
|
||||
Map<String, Object> request = baseRequest("efs-function");
|
||||
|
||||
Reference in new issue
Block a user