test(lambda): share Node.js ZIP fixtures across services (#8434)

This commit is contained in:
Jackson Price authored and GitHub committed 2026-11-15 14:26:55 -04:00
1 parent f534c1c431
commit be18211c98
38 files changed
+193 -395

No files matched your search

@@ -1,6 +1,7 @@
package io.floci.aws.services.apigatewayv2;
import java.io.ByteArrayOutputStream;
import io.floci.aws.testing.LambdaCodeFixtures;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
@@ -14,8 +15,6 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
@@ -35,13 +34,7 @@ public final class WebSocketTestSupport {
* Used to create Lambda function deployment packages in tests.
*/
public static String createLambdaZip(String handlerCode) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry("index.js"));
zos.write(handlerCode.getBytes());
zos.closeEntry();
}
return Base64.getEncoder().encodeToString(baos.toByteArray());
return LambdaCodeFixtures.nodeJsZipBase64(handlerCode);
}
// ──────────────────────────── Lambda cleanup ────────────────────────────
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.cloudformation.model.Stack;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.MutableClock;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
@@ -17,10 +18,7 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
@@ -28,8 +26,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -50,6 +46,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudFormationIntegrationTest {
private static final String HANDLER_SOURCE = "exports.handler=async(e)=>({statusCode:200})";
private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String SM_CONTENT_TYPE = "application/x-amz-json-1.1";
@@ -73,20 +71,6 @@ class CloudFormationIntegrationTest {
clock.reset();
}
private static byte[] buildHandlerZip() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry("index.js"));
zos.write("exports.handler=async(e)=>({statusCode:200})".getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
}
return baos.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* DeleteStack answers before the stack is gone: the deletion runs on an executor. Waits until
* DescribeStacks reports DELETE_COMPLETE or no longer knows the stack, and fails on DELETE_FAILED
@@ -719,7 +703,7 @@ class CloudFormationIntegrationTest {
@Test
void createStack_lambdaWithS3Code() {
byte[] zipBytes = buildHandlerZip();
byte[] zipBytes = LambdaCodeFixtures.nodeJsZip(HANDLER_SOURCE);
// Create S3 bucket
given()
@@ -1881,7 +1865,7 @@ class CloudFormationIntegrationTest {
@Test
void createStack_lambdaWithZipFile() {
String base64Zip = Base64.getEncoder().encodeToString(buildHandlerZip());
String base64Zip = LambdaCodeFixtures.nodeJsZipBase64(HANDLER_SOURCE);
String template = """
{
@@ -6,9 +6,9 @@ import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.lambda.LambdaService;
import io.floci.aws.services.lambdaweb.LambdaWebCodeBuckets;
import io.floci.aws.services.lambdaweb.LambdaWebRoles;
import io.floci.aws.services.lambdaweb.LambdaWebZips;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
@@ -55,7 +55,7 @@ class CloudFormationLambdaWebIntegrationTest {
void stackProvisionsFunctionRevisionAndEndpoint() {
LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/cfn-web");
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", LambdaCodeFixtures.nodeJsZip(""), "application/zip", Map.of());
String suffix = Long.toString(System.nanoTime(), 36);
String functionName = "cfn-web-" + suffix;
String stackName = "cfn-web-stack-" + suffix;
@@ -121,7 +121,7 @@ class CloudFormationLambdaWebIntegrationTest {
void aRevisionOnCodeThatIsNotAZipFailsItsResource() {
LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/cfn-web");
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", LambdaCodeFixtures.nodeJsZip(""), "application/zip", Map.of());
s3Service.putObject(BUCKET, "notzip.zip", "this is not a zip\n".getBytes(StandardCharsets.UTF_8),
"application/zip", Map.of());
String suffix = Long.toString(System.nanoTime(), 36);
@@ -157,7 +157,7 @@ class CloudFormationLambdaWebIntegrationTest {
void aCustomResourceIsGivenRegionalEndpointsAsAnObject() {
LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/cfn-web");
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", LambdaCodeFixtures.nodeJsZip(""), "application/zip", Map.of());
String suffix = Long.toString(System.nanoTime(), 36);
String functionName = "cfn-web-probe-" + suffix;
String stackName = "cfn-web-probe-stack-" + suffix;
@@ -193,7 +193,7 @@ class CloudFormationLambdaWebIntegrationTest {
void regionalEndpointsIsAnObjectThatAnOutputCannotHold() {
LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/cfn-web");
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", LambdaCodeFixtures.nodeJsZip(""), "application/zip", Map.of());
String suffix = Long.toString(System.nanoTime(), 36);
String functionName = "cfn-web-regional-" + suffix;
String stackName = "cfn-web-regional-stack-" + suffix;
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
@@ -11,14 +12,10 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
@@ -37,6 +34,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class SamTransformIntegrationTest {
private static final String HANDLER_SOURCE = "exports.handler=async(e)=>({statusCode:200})";
private final List<String> stacksToDelete = new ArrayList<>();
@BeforeAll
@@ -238,15 +237,10 @@ class SamTransformIntegrationTest {
.header("X-Amz-Executed-Version", equalTo("1"))
.body("ok", equalTo(true));
ByteArrayOutputStream changedCode = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(changedCode)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("exports.handler = async () => ({ ok: false });".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
String changedCode = LambdaCodeFixtures.nodeJsZipBase64("exports.handler = async () => ({ ok: false });");
given()
.contentType("application/json")
.body("{\"ZipFile\":\"" + Base64.getEncoder().encodeToString(changedCode.toByteArray()) + "\"}")
.body("{\"ZipFile\":\"" + changedCode + "\"}")
.when()
.put("/2015-03-31/functions/sam-alias-func/code")
.then()
@@ -1653,7 +1647,7 @@ class SamTransformIntegrationTest {
.then()
.statusCode(200);
byte[] zipBytes = buildHandlerZip();
byte[] zipBytes = LambdaCodeFixtures.nodeJsZip(HANDLER_SOURCE);
given()
.contentType("application/zip")
.body(zipBytes)
@@ -2277,7 +2271,7 @@ class SamTransformIntegrationTest {
String bucket = "sam-layer-code";
stacksToDelete.add(stack);
given().when().put("/" + bucket).then().statusCode(200);
given().contentType("application/zip").body(buildHandlerZip())
given().contentType("application/zip").body(LambdaCodeFixtures.nodeJsZip(HANDLER_SOURCE))
.when().put("/" + bucket + "/layer.zip").then().statusCode(200);
String template = """
Transform: AWS::Serverless-2016-10-31
@@ -2337,11 +2331,11 @@ class SamTransformIntegrationTest {
.body("CompatibleRuntimes", hasItems("nodejs22.x", "python3.14"))
.body("CompatibleArchitectures", hasItem("arm64"))
.body("LicenseInfo", equalTo("MIT"))
.body("Content.CodeSize", equalTo(buildHandlerZip().length));
.body("Content.CodeSize", equalTo(LambdaCodeFixtures.nodeJsZip(HANDLER_SOURCE).length));
given().when().get("/2015-03-31/functions/sam-layer-consumer")
.then().statusCode(200).body("Configuration.Layers[0].Arn", equalTo(arn))
.body("Configuration.Environment.Variables.DependsOn", equalTo("Layer"));
given().contentType("application/zip").body(buildHandlerZip())
given().contentType("application/zip").body(LambdaCodeFixtures.nodeJsZip(HANDLER_SOURCE))
.when().put("/" + bucket + "/updated.zip").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack").formParam("StackName", stack)
@@ -2381,20 +2375,6 @@ class SamTransformIntegrationTest {
.split("</OutputValue>")[0];
}
private static byte[] buildHandlerZip() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry("index.js"));
zos.write("exports.handler=async(e)=>({statusCode:200})".getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
}
return baos.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void waitForStackStatus(String stackName, String status) {
String expected = "<StackStatus>" + status + "</StackStatus>";
String body = "";
@@ -7,8 +7,8 @@ import io.floci.aws.services.cloudfront.model.Origin;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.lambdaweb.LambdaWebCodeBuckets;
import io.floci.aws.services.lambdaweb.LambdaWebRoles;
import io.floci.aws.services.lambdaweb.LambdaWebZips;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
@@ -91,7 +91,7 @@ class CloudFrontWebFunctionOriginServingTest {
String functionName, String authType) {
LambdaWebRoles.trustLambda(iamService, ROLE);
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", LambdaCodeFixtures.nodeJsZip(""), "application/zip", Map.of());
String domain = given().contentType("application/json")
.body("""
{"functionName": "%s",
@@ -5,17 +5,14 @@ import io.floci.aws.services.lambda.LambdaService;
import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials;
import io.floci.aws.services.lambda.model.LambdaFunction;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
@@ -134,13 +131,7 @@ class LambdaExecutionRoleIamEnforcementIntegrationTest {
}
private static String handlerZipBase64() throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("exports.handler = async () => ({});\n".getBytes());
zip.closeEntry();
}
return Base64.getEncoder().encodeToString(bytes.toByteArray());
return LambdaCodeFixtures.nodeJsZipBase64("exports.handler = async () => ({});\n");
}
private static String auth(String accessKeyId, String service) {
@@ -6,6 +6,7 @@ import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.kinesis.KinesisService;
import io.floci.aws.services.sqs.SqsService;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.SqsTestQueue;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
@@ -13,14 +14,10 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -150,20 +147,14 @@ class KinesisEsmOnFailureDockerIntegrationTest {
}
private static String poisonRaisingZipBase64() throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("""
exports.handler = async (event) => {
for (const record of event.Records) {
if (Buffer.from(record.kinesis.data, 'base64').toString() === 'poison') {
throw new Error('poison record');
}
}
};
""".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return Base64.getEncoder().encodeToString(bytes.toByteArray());
return LambdaCodeFixtures.nodeJsZipBase64("""
exports.handler = async (event) => {
for (const record of event.Records) {
if (Buffer.from(record.kinesis.data, 'base64').toString() === 'poison') {
throw new Error('poison record');
}
}
};
""");
}
}
@@ -1,15 +1,9 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@@ -55,7 +49,7 @@ class LambdaAccountSettingsIntegrationTest {
"Handler": "index.handler",
"Code": {"ZipFile": "%s"}
}
""".formatted(zipBase64()))
""".formatted(LambdaCodeFixtures.nodeJsZipBase64("exports.handler = async () => ({ ok: true });")))
.when()
.post("/2015-03-31/functions")
.then()
@@ -86,18 +80,4 @@ class LambdaAccountSettingsIntegrationTest {
private static String auth(String accountId) {
return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260101/us-east-1/lambda/aws4_request";
}
private static String zipBase64() {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(out)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("exports.handler = async () => ({ ok: true });".getBytes());
zip.closeEntry();
}
return Base64.getEncoder().encodeToString(out.toByteArray());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -1,6 +1,6 @@
package io.floci.aws.services.lambda;
import io.floci.aws.services.lambdaweb.LambdaWebZips;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.LambdaCodeSourcesProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
@@ -33,8 +33,8 @@ class LambdaAsyncReactiveSyncIntegrationTest {
@Test
void uploadFromANonDefaultAccountRedeploysTheFunctionInTheBackground() throws Exception {
byte[] v1 = LambdaWebZips.indexJs("exports.handler = async () => 'v1';");
byte[] v2 = LambdaWebZips.indexJs("exports.handler = async () => 'v2';");
byte[] v1 = LambdaCodeFixtures.nodeJsZip("exports.handler = async () => 'v1';");
byte[] v2 = LambdaCodeFixtures.nodeJsZip("exports.handler = async () => 'v2';");
given().header("Authorization", S3_AUTH).when().put("/" + BUCKET).then().statusCode(200);
given().header("Authorization", S3_AUTH).body(v1).when().put("/" + BUCKET + "/" + KEY).then().statusCode(200);
given()
@@ -3,6 +3,7 @@ package io.floci.aws.services.lambda;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.dockerjava.api.DockerClient;
import io.floci.aws.services.sqs.SqsService;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.SqsTestQueue;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
@@ -10,13 +11,8 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -168,14 +164,7 @@ class LambdaAsyncRetryDockerIntegrationTest {
}
private static String failingZipBase64() throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("exports.handler = async () => { throw new Error('boom'); };\n"
.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return Base64.getEncoder().encodeToString(bytes.toByteArray());
return LambdaCodeFixtures.nodeJsZipBase64("exports.handler = async () => { throw new Error('boom'); };\n");
}
private boolean isDockerAvailable() {
@@ -4,6 +4,7 @@ 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.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
@@ -26,7 +27,6 @@ import software.amazon.awssdk.services.lambda.model.InvalidParameterValueExcepti
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;
@@ -35,8 +35,6 @@ 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.*;
@@ -251,16 +249,11 @@ class LambdaEnvironmentSizeIntegrationTest {
}
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();
}
byte[] bytes = LambdaCodeFixtures.nodeJsZip("exports.handler = async () => 1;");
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());
.code(FunctionCode.builder().zipFile(SdkBytes.fromByteArray(bytes)).build());
}
private GetFunctionConfigurationResponse configuration(String name) {
@@ -2,6 +2,7 @@ package io.floci.aws.services.lambda;
import com.github.dockerjava.api.DockerClient;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
@@ -11,13 +12,8 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
@@ -145,13 +141,7 @@ class LambdaExecutionRoleDockerIntegrationTest {
};
};
""";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(handler.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return Base64.getEncoder().encodeToString(bytes.toByteArray());
return LambdaCodeFixtures.nodeJsZipBase64(handler);
}
private boolean isDockerAvailable() {
@@ -1,13 +1,10 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@@ -73,19 +70,13 @@ class LambdaFunctionUrlAccountRoutingTest {
}
private byte[] lambdaZip() throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("""
exports.handler = async (event) => ({
statusCode: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify({ accountId: event.requestContext.accountId })
});
""".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return bytes.toByteArray();
return LambdaCodeFixtures.nodeJsZip("""
exports.handler = async (event) => ({
statusCode: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify({ accountId: event.requestContext.accountId })
});
""");
}
private String urlId(String functionUrl) {
@@ -3,6 +3,7 @@ package io.floci.aws.services.lambda;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.PartitionCleanup;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
@@ -1,13 +1,10 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@@ -59,20 +56,14 @@ class LambdaFunctionUrlResponseStreamTest {
}
private byte[] lambdaZip() throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("""
exports.handler = awslambda.streamifyResponse(async (event, responseStream) => {
responseStream = awslambda.HttpResponseStream.from(responseStream, {
statusCode: 201, headers: { "content-type": "text/event-stream" } });
responseStream.write("data: first\\n\\n");
responseStream.write("data: last\\n\\n");
responseStream.end();
});
""".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return bytes.toByteArray();
return LambdaCodeFixtures.nodeJsZip("""
exports.handler = awslambda.streamifyResponse(async (event, responseStream) => {
responseStream = awslambda.HttpResponseStream.from(responseStream, {
statusCode: 201, headers: { "content-type": "text/event-stream" } });
responseStream.write("data: first\\n\\n");
responseStream.write("data: last\\n\\n");
responseStream.end();
});
""");
}
}
@@ -1,14 +1,9 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
@@ -119,18 +114,13 @@ class LambdaGetFunctionConcurrencyIntegrationTest {
}
private static void createFunction(String account, String region, String name) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("exports.handler = async () => ({});".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
String code = LambdaCodeFixtures.nodeJsZipBase64("exports.handler = async () => ({});");
given().header("Authorization", auth(account, region)).contentType("application/json")
.body("""
{"FunctionName":"%s","Runtime":"nodejs20.x",
"Role":"arn:aws:iam::%s:role/lambda-role","Handler":"index.handler",
"Code":{"ZipFile":"%s"}}
""".formatted(name, account, Base64.getEncoder().encodeToString(bytes.toByteArray())))
""".formatted(name, account, code))
.when().post(FUNCTIONS).then().statusCode(201);
}
@@ -1,6 +1,7 @@
package io.floci.aws.services.lambda;
import io.floci.aws.core.common.Digests;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
@@ -585,13 +586,7 @@ class LambdaIntegrationTest {
@Order(40)
void getFunction_codeLocation_isDownloadableAndByteExact() throws Exception {
// Build a real zip with a nodejs handler file (extractZipCode verifies it).
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry("index.js"));
zos.write("exports.handler = async () => ({ statusCode: 200 });\n".getBytes());
zos.closeEntry();
}
String zipB64 = Base64.getEncoder().encodeToString(baos.toByteArray());
String zipB64 = LambdaCodeFixtures.nodeJsZipBase64("exports.handler = async () => ({ statusCode: 200 });\n");
given()
.contentType("application/json")
@@ -647,15 +642,10 @@ class LambdaIntegrationTest {
"downloaded package must be byte-identical to the uploaded zip");
// Redeploy overwrites in place (stable key), no stale package accumulates.
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos2)) {
zos.putNextEntry(new ZipEntry("index.js"));
zos.write("exports.handler = async () => ({ statusCode: 201 });\n".getBytes());
zos.closeEntry();
}
String replacementArchive = LambdaCodeFixtures.nodeJsZipBase64("exports.handler = async () => ({ statusCode: 201 });\n");
given()
.contentType("application/json")
.body("{ \"ZipFile\": \"%s\" }".formatted(Base64.getEncoder().encodeToString(baos2.toByteArray())))
.body("{ \"ZipFile\": \"%s\" }".formatted(replacementArchive))
.when()
.put(BASE_PATH + "/functions/code-dl-fn/code")
.then()
@@ -8,18 +8,16 @@ import io.floci.aws.services.lambda.model.LambdaLayerVersion;
import io.floci.aws.services.lambda.zip.ZipExtractor;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.s3.model.S3Object;
import io.floci.aws.testing.LambdaCodeFixtures;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Answers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -220,13 +218,7 @@ class LambdaLayerCodePathIsolationTest {
}
private static byte[] zipBytes(String content) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(content.getBytes());
zip.closeEntry();
}
return bytes.toByteArray();
return LambdaCodeFixtures.nodeJsZip(content);
}
private static void assertEqualsContent(String path, String expected) throws Exception {
@@ -1,5 +1,6 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -42,13 +43,7 @@ class LambdaLayerIntegrationTest {
}
private static String functionZipBase64() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry("index.js"));
zos.write("exports.handler = async () => ({ statusCode: 200 });".getBytes());
zos.closeEntry();
}
return Base64.getEncoder().encodeToString(baos.toByteArray());
return LambdaCodeFixtures.nodeJsZipBase64("exports.handler = async () => ({ statusCode: 200 });");
}
// ── PublishLayerVersion ───────────────────────────────────────────────────
@@ -2,14 +2,13 @@ package io.floci.aws.services.lambda;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
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.util.Base64;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -31,8 +30,7 @@ class LambdaPermissionTagLayerIntegrationTest {
@Test
@Order(1)
void createFunction() throws Exception {
byte[] zip = LambdaCodeFixtures.nodeJsZip("exports.handler = async () => ({});");
String zipBase64 = Base64.getEncoder().encodeToString(zip);
String zipBase64 = LambdaCodeFixtures.nodeJsZipBase64("exports.handler = async () => ({});");
given()
.contentType("application/json")
@@ -1,15 +1,13 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
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.io.ByteArrayOutputStream;
import java.time.Duration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
@@ -29,13 +27,7 @@ class LambdaReactiveSyncIntegrationTest {
private static final String FN = "reactive-sync-fn";
private static byte[] makeZip(String body) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry("index.js"));
zos.write(("exports.handler = async (e) => ({ body: '" + body + "' });").getBytes());
zos.closeEntry();
}
return baos.toByteArray();
return LambdaCodeFixtures.nodeJsZip("exports.handler = async (e) => ({ body: '" + body + "' });");
}
@Test
@@ -1,5 +1,6 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -1,14 +1,11 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@@ -54,13 +51,6 @@ class LambdaS3DeploymentIntegrationTest {
}
private static byte[] makeZip(String body) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(("exports.handler = async () => ({ body: '" + body + "' });")
.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return bytes.toByteArray();
return LambdaCodeFixtures.nodeJsZip("exports.handler = async () => ({ body: '" + body + "' });");
}
}
@@ -18,6 +18,7 @@ import io.floci.aws.services.lambda.zip.ZipExtractor;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.s3.model.S3Object;
import io.floci.aws.services.s3.model.S3ObjectUpdatedEvent;
import io.floci.aws.testing.LambdaCodeFixtures;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -2864,13 +2865,7 @@ class LambdaServiceTest {
}
private static String zipWithBody(String body) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry("index.js"));
zos.write((body + "\n").getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
}
return Base64.getEncoder().encodeToString(baos.toByteArray());
return LambdaCodeFixtures.nodeJsZipBase64(body + "\n");
}
@Test
@@ -1,16 +1,12 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
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.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -301,19 +297,13 @@ class LambdaVersionIntegrationTest {
}
private void createInvocableFunction(String fnName) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry("index.js"));
zos.write("""
exports.handler = async (event, context) => ({
ok: true,
envVersion: process.env.AWS_LAMBDA_FUNCTION_VERSION,
contextVersion: context.functionVersion
});
""".getBytes());
zos.closeEntry();
}
String base64Zip = Base64.getEncoder().encodeToString(baos.toByteArray());
String base64Zip = LambdaCodeFixtures.nodeJsZipBase64("""
exports.handler = async (event, context) => ({
ok: true,
envVersion: process.env.AWS_LAMBDA_FUNCTION_VERSION,
contextVersion: context.functionVersion
});
""");
given()
.contentType("application/json")
@@ -1,5 +1,6 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
@@ -23,15 +24,11 @@ import software.amazon.awssdk.services.lambda.model.Runtime;
import software.amazon.awssdk.services.lambda.model.VpcConfig;
import software.amazon.awssdk.services.lambda.model.VpcConfigResponse;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -72,13 +69,8 @@ class LambdaVpcResourceValidationIntegrationTest {
"Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}
""")).role().arn();
cleanup.add(() -> iam.deleteRole(r -> r.roleName(name)));
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("exports.handler = async event => event;".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
code = FunctionCode.builder().zipFile(SdkBytes.fromByteArray(bytes.toByteArray())).build();
byte[] bytes = LambdaCodeFixtures.nodeJsZip("exports.handler = async event => event;");
code = FunctionCode.builder().zipFile(SdkBytes.fromByteArray(bytes)).build();
cleanup.add(() -> {
try {
lambda.deleteFunction(r -> r.functionName(name));
@@ -5,6 +5,7 @@ import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.Session;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
@@ -62,7 +63,7 @@ class LambdaWebAuthTypeConditionKeysIntegrationTest {
String name = "auth-type-" + Long.toString(System.nanoTime(), 36);
LambdaWebRoles.trustLambda(iamService, ROLE);
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", LambdaCodeFixtures.nodeJsZip(""), "application/zip", Map.of());
cleanup.register(() -> given().header("Authorization", auth(ACCOUNT, "lambda"))
.when().delete(BASE + "/" + name));
given().header("Authorization", auth(ACCOUNT, "lambda")).contentType("application/json")
@@ -3,6 +3,7 @@ package io.floci.aws.services.lambdaweb;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
@@ -163,7 +164,7 @@ class LambdaWebCodeBucketIntegrationTest {
}
private String put(String in) {
return s3Service.putObject(in, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of())
return s3Service.putObject(in, "app.zip", LambdaCodeFixtures.nodeJsZip(""), "application/zip", Map.of())
.getVersionId();
}
@@ -10,6 +10,7 @@ import io.floci.aws.services.cloudfront.model.OriginAccessControl;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.lambdaweb.LambdaWebEnvironmentManager.Environment;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
@@ -23,7 +24,6 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -44,8 +44,6 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
@@ -548,7 +546,8 @@ class LambdaWebDataPlaneDockerIntegrationTest {
@Timeout(180)
void anEnvironmentRunsTheCodeTheRevisionWasCreatedFrom() throws Exception {
String domain = createFunction(30);
s3Service.putObject(BUCKET, functionName + ".zip", zip("process.exit(1);"), "application/zip", Map.of());
s3Service.putObject(BUCKET, functionName + ".zip", LambdaCodeFixtures.nodeJsZip("process.exit(1);"),
"application/zip", Map.of());
given().header("Host", domain).when().get("/status/200").then().statusCode(200).body(equalTo("status body"));
}
@@ -672,7 +671,7 @@ class LambdaWebDataPlaneDockerIntegrationTest {
functionName = "dp-docker-" + Long.toString(System.nanoTime(), 36);
LambdaWebRoles.trustLambda(iamService, ROLE);
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, functionName + ".zip", zip(APP), "application/zip", Map.of());
s3Service.putObject(BUCKET, functionName + ".zip", LambdaCodeFixtures.nodeJsZip(APP), "application/zip", Map.of());
return given().contentType("application/json")
.body("""
{"functionName": "%s",
@@ -942,16 +941,6 @@ class LambdaWebDataPlaneDockerIntegrationTest {
.filter(line -> line.regionMatches(true, 0, prefix, 0, prefix.length())).toList();
}
private static byte[] zip(String indexJs) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(indexJs.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return bytes.toByteArray();
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
@@ -2,6 +2,7 @@ package io.floci.aws.services.lambdaweb;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.response.Response;
@@ -160,7 +161,7 @@ class LambdaWebDataPlaneIntegrationTest {
.body("state", equalTo("Failed"))
.body("stateReason", equalTo(reason));
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", LambdaCodeFixtures.nodeJsZip(""), "application/zip", Map.of());
given().when().get(revision).then().statusCode(200).body("state", equalTo("Failed"));
given().contentType("application/json")
.body("{\"autoDeploymentMode\": \"Disabled\", \"revisionWeights\": [{\"revisionId\": \"" + revisionId
@@ -176,7 +177,7 @@ class LambdaWebDataPlaneIntegrationTest {
@Test
void anEnvironmentDoesNotStartWhenLambdaCanNoLongerAssumeTheRole() {
String functionName = "dp-role-" + Long.toString(System.nanoTime(), 36);
String domain = createFunction(functionName, "ApplicationManaged", LambdaWebZips.indexJs(""),
String domain = createFunction(functionName, "ApplicationManaged", LambdaCodeFixtures.nodeJsZip(""),
"arn:aws:iam::000000000000:role/" + functionName);
iamService.updateAssumeRolePolicy(functionName, """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
@@ -377,7 +378,7 @@ class LambdaWebDataPlaneIntegrationTest {
@Test
void theGlobalDomainOfAFunctionInAnotherRegionCountsAPageInTheDefaultRegion() {
String functionName = "dp-global-" + Long.toString(System.nanoTime(), 36);
createFunction("us-west-2", functionName, "ApplicationManaged", LambdaWebZips.indexJs(""), ROLE);
createFunction("us-west-2", functionName, "ApplicationManaged", LambdaCodeFixtures.nodeJsZip(""), ROLE);
String west = auth("test", "us-west-2", "lambda");
String endpoints = BASE + "/web-functions/" + functionName + "/endpoints";
String revisionId = given().header("Authorization", west).when().get(endpoints + "/dev").then().statusCode(200)
@@ -412,7 +413,7 @@ class LambdaWebDataPlaneIntegrationTest {
}
private String createFunction(String functionName, String authType) {
return createFunction(functionName, authType, LambdaWebZips.indexJs(""));
return createFunction(functionName, authType, LambdaCodeFixtures.nodeJsZip(""));
}
private String createFunction(String functionName, String authType, byte[] code) {
@@ -6,6 +6,7 @@ import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
@@ -18,13 +19,9 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
@@ -147,13 +144,7 @@ class LambdaWebIamAuthIntegrationTest {
}
private static byte[] zip() throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(APP.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return bytes.toByteArray();
return LambdaCodeFixtures.nodeJsZip(APP);
}
private boolean isDockerAvailable() {
@@ -2,6 +2,7 @@ package io.floci.aws.services.lambdaweb;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
@@ -57,7 +58,7 @@ class LambdaWebIntegrationTest {
void seedCode() {
LambdaWebRoles.trustLambda(iamService, ROLE);
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, KEY, LambdaWebZips.indexJs(""), "application/zip", Map.of());
s3Service.putObject(BUCKET, KEY, LambdaCodeFixtures.nodeJsZip(""), "application/zip", Map.of());
}
@Test
@@ -455,7 +456,7 @@ class LambdaWebIntegrationTest {
.body("message", equalTo("The specified S3 object does not exist: s3://" + BUCKET
+ "/missing.zip. Verify the object exists in the bucket."));
s3Service.putObject(BUCKET, "deleted.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
s3Service.putObject(BUCKET, "deleted.zip", LambdaCodeFixtures.nodeJsZip(""), "application/zip", Map.of());
String marker = s3Service.deleteObject(BUCKET, "deleted.zip").getVersionId();
given().contentType("application/json")
.body("""
@@ -24,6 +24,7 @@ import io.floci.aws.services.lambdaweb.model.WebFunctionEndpoint;
import io.floci.aws.services.lambdaweb.model.WebFunctionRevision;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.s3.model.S3Object;
import io.floci.aws.testing.LambdaCodeFixtures;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -1082,8 +1083,8 @@ class LambdaWebServiceTest {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
LambdaWebCode code = new LambdaWebCode(storageDir.resolve("code"));
byte[] v1 = LambdaWebZips.indexJs("v1");
byte[] v2 = LambdaWebZips.indexJs("v2");
byte[] v1 = LambdaCodeFixtures.nodeJsZip("v1");
byte[] v2 = LambdaCodeFixtures.nodeJsZip("v2");
when(s3.openObject("code", "app.zip", null)).thenReturn(object(v1));
String first = service.createFunction(REGION, createRequest("app")).revisions.keySet().iterator().next();
when(s3.openObject("code", "app.zip", null)).thenReturn(object(v2));
@@ -1100,7 +1101,7 @@ class LambdaWebServiceTest {
@Test
void aStartKeepsOnlyTheCopiesOfStoredRevisions() throws IOException {
S3Service s3 = mock(S3Service.class);
byte[] zip = LambdaWebZips.indexJs("code");
byte[] zip = LambdaCodeFixtures.nodeJsZip("code");
when(s3.openObject("code", "app.zip", null)).thenReturn(object(zip));
FileStorageFactory storage = new FileStorageFactory(storageDir);
String revisionId = service(storage, "http://localhost:4566", s3).createFunction(REGION, createRequest("app"))
@@ -1163,7 +1164,7 @@ class LambdaWebServiceTest {
void aRevisionWhoseCodeIsNotAZipIsFailedAndCannotBeDeployed() {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
when(s3.openObject("code", "app.zip", null)).thenReturn(object(LambdaWebZips.indexJs("v1")));
when(s3.openObject("code", "app.zip", null)).thenReturn(object(LambdaCodeFixtures.nodeJsZip("v1")));
String good = service.createFunction(REGION, createRequest("app")).revisions.keySet().iterator().next();
when(s3.openObject("code", "app.zip", null)).thenReturn(object(NOT_A_ZIP));
WebFunctionRevision bad = service.createRevision(REGION, "app", revisionConfig(30));
@@ -1231,7 +1232,7 @@ class LambdaWebServiceTest {
+ " Active state.", update.getMessage());
// A good revision still moves the endpoint's weights, and the endpoint stays Failed, as on AWS.
when(s3.openObject("code", "app.zip", null)).thenReturn(object(LambdaWebZips.indexJs("v2")));
when(s3.openObject("code", "app.zip", null)).thenReturn(object(LambdaCodeFixtures.nodeJsZip("v2")));
String good = service.createRevision(REGION, "app", revisionConfig(30)).revisionId;
dev = service.getEndpoint(REGION, "app", "dev");
assertEquals(good, dev.revisionWeights.get(0).revisionId);
@@ -1256,7 +1257,7 @@ class LambdaWebServiceTest {
assertEquals("The function arn:aws:lambda:us-east-1:000000000000:web-function/app does not exist.",
message(() -> service.getFunction(REGION, "app")));
when(s3.openObject("code", "app.zip", null)).thenReturn(object(LambdaWebZips.indexJs("v1")));
when(s3.openObject("code", "app.zip", null)).thenReturn(object(LambdaCodeFixtures.nodeJsZip("v1")));
service.createFunction(REGION, createRequest("app"));
when(s3.openObject("code", "app.zip", null)).thenReturn(object(new byte[0]));
assertInstanceOf(LambdaWebInternalServerException.class,
@@ -1309,7 +1310,7 @@ class LambdaWebServiceTest {
void anObjectPastTheZippedLimitIsRefusedAndCreatesNothing() throws IOException {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
byte[] zip = LambdaWebZips.indexJs("");
byte[] zip = LambdaCodeFixtures.nodeJsZip("");
String refusal = "Zipped size must be smaller than 536870912 bytes";
when(s3.openObject("code", "app.zip", null)).thenReturn(object(zip, LambdaWebCode.MAX_BYTES + 1));
@@ -1334,7 +1335,7 @@ class LambdaWebServiceTest {
void theNullVersionAsTheLatestIsRefusedBeforeTheSize() {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
byte[] zip = LambdaWebZips.indexJs("");
byte[] zip = LambdaCodeFixtures.nodeJsZip("");
when(s3.openObject("code", "app.zip", null)).thenReturn(nullVersion(object(zip, LambdaWebCode.MAX_BYTES + 1)));
AwsException create = error(() -> service.createFunction(REGION, createRequest("app")));
@@ -1375,7 +1376,7 @@ class LambdaWebServiceTest {
}
when(s3.openObject("code", "app.zip", null))
.thenReturn(object(LambdaWebZips.indexJs(""), LambdaWebCode.MAX_BYTES + 1));
.thenReturn(object(LambdaCodeFixtures.nodeJsZip(""), LambdaWebCode.MAX_BYTES + 1));
assertEquals("Zipped size must be smaller than 536870912 bytes",
message(() -> service.createFunction(REGION, createRequest("app"))));
}
@@ -1384,7 +1385,7 @@ class LambdaWebServiceTest {
void anActiveRevisionPastFiftyDeletesTheOldestUnusedOnes() {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
byte[] zip = LambdaWebZips.indexJs("");
byte[] zip = LambdaCodeFixtures.nodeJsZip("");
when(s3.openObject("code", "app.zip", null)).thenAnswer(invocation -> object(zip));
String pinned = service.createFunction(REGION, createRequest("app")).revisions.keySet().iterator().next();
ObjectNode pin = endpointConfig("pin").put("autoDeploymentMode", "Disabled");
@@ -1425,7 +1426,7 @@ class LambdaWebServiceTest {
void theRevisionALatestRevisionEndpointLeavesStaysUntilTheNextActiveOne() {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
byte[] zip = LambdaWebZips.indexJs("");
byte[] zip = LambdaCodeFixtures.nodeJsZip("");
when(s3.openObject("code", "app.zip", null)).thenAnswer(invocation -> object(zip));
String first = service.createFunction(REGION, createRequest("app")).revisions.keySet().iterator().next();
when(s3.openObject("code", "app.zip", null)).thenAnswer(invocation -> object(NOT_A_ZIP));
@@ -1,14 +1,9 @@
package io.floci.aws.services.lambdaweb;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/** Code packages for tests that deploy function code, Web Function revisions among them. */
public final class LambdaWebZips {
@@ -16,18 +11,6 @@ public final class LambdaWebZips {
private LambdaWebZips() {
}
public static byte[] indexJs(String source) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(source.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return bytes.toByteArray();
}
/** Files whose ZIP64 fields declare these sizes over empty data. */
public static byte[] declaring(long... sizes) {
byte[] empty = {3, 0};
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.sqs.SqsService;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.DynamoDbRequests;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.SqsTestQueue;
import io.quarkus.test.junit.QuarkusTest;
@@ -14,14 +15,10 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -177,22 +174,16 @@ class PipesStreamEnrichmentDockerIntegrationTest {
}
private static String enrichmentZipBase64() throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("""
exports.handler = async (records) => records.flatMap((record) => {
const rowId = record.dynamodb.Keys.sk.S.split('#')[1];
return [1, 2].map((part) => ({
Source: 'orders',
DetailType: 'Order Written',
Detail: JSON.stringify({rowId, part}),
}));
});
""".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return Base64.getEncoder().encodeToString(bytes.toByteArray());
return LambdaCodeFixtures.nodeJsZipBase64("""
exports.handler = async (records) => records.flatMap((record) => {
const rowId = record.dynamodb.Keys.sk.S.split('#')[1];
return [1, 2].map((part) => ({
Source: 'orders',
DetailType: 'Order Written',
Detail: JSON.stringify({rowId, part}),
}));
});
""");
}
private static void putItem(String table, String sortKey) {
@@ -2,6 +2,7 @@ package io.floci.aws.services.s3;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.S3IamEnforcementProfile;
import io.quarkus.test.junit.QuarkusTest;
@@ -10,16 +11,12 @@ import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@@ -89,12 +86,6 @@ class S3InternalLambdaCodeDownloadIntegrationTest {
}
private static byte[] archive(String marker) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(("exports.handler = async () => '" + marker + "';").getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return bytes.toByteArray();
return LambdaCodeFixtures.nodeJsZip("exports.handler = async () => '" + marker + "';");
}
}
@@ -1,23 +1,31 @@
package io.floci.aws.services.lambda;
package io.floci.aws.testing;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
final class LambdaCodeFixtures {
public final class LambdaCodeFixtures {
private LambdaCodeFixtures() {
}
static byte[] nodeJsZip(String handlerSource) throws IOException {
public static byte[] nodeJsZip(String handlerSource) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(handlerSource.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
} catch (IOException e) {
throw new UncheckedIOException("Could not create the in-memory Lambda ZIP", e);
}
return bytes.toByteArray();
}
public static String nodeJsZipBase64(String handlerSource) {
return Base64.getEncoder().encodeToString(nodeJsZip(handlerSource));
}
}
@@ -0,0 +1,41 @@
package io.floci.aws.testing;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.ZipInputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class LambdaCodeFixturesTest {
@Test
void nodeJsZipPreservesUtf8SourceInOneEntry() throws IOException {
String source = "exports.handler = async () => 'café';\n";
assertHandlerSource(LambdaCodeFixtures.nodeJsZip(source), source);
}
@Test
void nodeJsZipBase64ContainsTheHandlerArchive() throws IOException {
String source = "exports.handler = async () => ({ statusCode: 200 });";
byte[] archive = Base64.getDecoder().decode(LambdaCodeFixtures.nodeJsZipBase64(source));
assertHandlerSource(archive, source);
}
@Test
void nodeJsZipSupportsAnEmptyHandlerSource() throws IOException {
assertHandlerSource(LambdaCodeFixtures.nodeJsZip(""), "");
}
private static void assertHandlerSource(byte[] archive, String source) throws IOException {
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(archive))) {
assertEquals("index.js", zip.getNextEntry().getName());
assertEquals(source, new String(zip.readAllBytes(), StandardCharsets.UTF_8));
assertNull(zip.getNextEntry());
}
}
}