feat(lambdaweb): fail a revision whose code is not a zip (#6141)

* feat(lambdaweb): fail a revision whose code is not a zip

A revision whose code is not a zip is Failed, as on AWS, and cannot be
deployed. The endpoint CreateWebFunction makes on such a revision is
Failed too and answers 409 Platform.EndpointNotActive. An empty object
is a 500 InternalServerException with an empty body, as on AWS.

* fix(lambdaweb): remove a code copy that cannot be read and name the {} body

* test(lambdaweb): upload a real zip in the compatibility tests
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-21 22:56:15 -04:00
1 parent 7c202a8966
commit 62972c91bf
21 files changed
+466 -33

No files matched your search

@@ -10,7 +10,10 @@ setup() {
BUCKET="cli-lambda-web-code-$$"
ROLE_ARN="arn:aws:iam::000000000000:role/lambda-web"
aws_cmd s3api create-bucket --bucket "$BUCKET" >/dev/null 2>&1 || true
printf 'zip' > "$BATS_TEST_TMPDIR/app.zip"
# A revision whose code is not a zip fails. python3 ships in the CLI image.
python3 -c 'import sys, zipfile
with zipfile.ZipFile(sys.argv[1], "w") as z:
z.writestr("index.js", "")' "$BATS_TEST_TMPDIR/app.zip"
aws_cmd s3api put-object --bucket "$BUCKET" --key app.zip --body "$BATS_TEST_TMPDIR/app.zip" >/dev/null
}
@@ -56,7 +56,7 @@ class LambdaWebTest {
s3 = TestFixtures.s3Client();
bucket = TestFixtures.uniqueName("sdk-test-web-code");
s3.createBucket(r -> r.bucket(bucket));
s3.putObject(r -> r.bucket(bucket).key("app.zip"), RequestBody.fromString("zip"));
s3.putObject(r -> r.bucket(bucket).key("app.zip"), RequestBody.fromBytes(LambdaUtils.minimalZip()));
}
/** Only "already gone" is tolerated; any other failure to clean up fails the run. */
+2 -1
View File
@@ -34,7 +34,8 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A
## Emulation Behavior
- **Instant convergence:** a revision and an endpoint are stored `Active` and an endpoint update is stored `Successful`. The create and update responses still report the transitional state AWS reports (`Pending`, `updateStatus: InProgress`, and the per-region block as it was before the update), so a waiter sees one poll.
- **Instant convergence:** a revision and an endpoint are stored `Active`, or `Failed` as below, and an endpoint update is stored `Successful`. The create and update responses still report the transitional state AWS reports (`Pending`, `updateStatus: InProgress`, and the per-region block as it was before the update), so a waiter sees one poll.
- **Failed revisions:** a revision whose code is not a zip is stored `Failed`, as on AWS. It cannot be deployed: weights that name it, or `LatestRevision` while it is the newest revision, are `409 ConflictException`, and `LatestRevision` endpoints stay on their revision. The endpoint of a `CreateWebFunction` whose revision fails is `Failed` too. It answers every request with `409` and `Platform.EndpointNotActive` and refuses updates until it is deleted. In a stack, the revision's resource fails with the revision's `stateReason` and the rollback deletes it. An empty object is a `500 InternalServerException` with the body `{}`, as on AWS.
- **Code comes from S3 only.** The object named in `buildConfig.codeConfig.s3Object` must exist in Floci's S3, as on AWS. AWS also requires bucket versioning and a bucket policy for the Lambda service principal. Floci does not check them yet.
- **Each revision keeps its own copy of the code**, read at creation from the version the request names or the current one, under the Lambda `code-path`. As on AWS, a later write or delete in the bucket does not change what the revision runs. AWS moves a revision to `Failed` when it later finds its object version gone, which Floci does not do.
- **Execution role and network connector** ARNs are checked for shape only. The assume-role check AWS makes is not done yet.
@@ -169,6 +169,14 @@ public class LambdaWebCfnProvisioner implements CfnResourceProvisioner {
revision = service.createRevision(ctx.region(), functionName, request);
}
r.setPhysicalId(revision.revisionArn);
if (revision.failureReason != null) {
// The AWS handler waits for Active, so a Failed revision fails the resource as NotStabilized.
AwsException failure = new AwsException("NotStabilized", revision.failureReason, 400);
CfnRollback.guarded(r, ctx, true, () -> delete(REVISION, r.getPhysicalId(), ctx.region()), () -> { },
() -> {
throw failure;
});
}
ReplacementCleanup.record(r, ctx, attributesBefore);
r.getAttributes().put("FunctionArn", revision.functionArn);
r.getAttributes().put("RevisionArn", revision.revisionArn);
@@ -21,6 +21,8 @@ import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Stream;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
/**
* The code package each revision copied from S3 when it was created. AWS prepares its own copy at
@@ -45,17 +47,29 @@ public class LambdaWebCode {
this.baseDir = baseDir;
}
void store(String accountId, String region, String functionName, String revisionId, InputStream zip) {
/** Returns the number of bytes kept. */
long store(String accountId, String region, String functionName, String revisionId, InputStream zip) {
Path file = file(accountId, region, functionName, revisionId);
try {
Files.createDirectories(file.getParent());
Files.copy(zip, file, StandardCopyOption.REPLACE_EXISTING);
return Files.copy(zip, file, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
deleteRevision(accountId, region, functionName, revisionId);
throw new UncheckedIOException("Could not keep the code of " + functionName + " revision " + revisionId, e);
}
}
boolean opensAsZip(String accountId, String region, String functionName, String revisionId) {
try (ZipFile ignored = new ZipFile(file(accountId, region, functionName, revisionId).toFile())) {
return true;
} catch (ZipException e) {
return false;
} catch (IOException e) {
deleteRevision(accountId, region, functionName, revisionId);
throw new UncheckedIOException("Could not read the code of " + functionName + " revision " + revisionId, e);
}
}
void deleteRevision(String accountId, String region, String functionName, String revisionId) {
try {
Files.deleteIfExists(file(accountId, region, functionName, revisionId));
@@ -171,6 +171,11 @@ public class LambdaWebDataPlane {
return;
}
WebFunctionTarget target = located.get();
if (target.endpoint().failed) {
metrics.answered(target, LambdaWebErrorPages.ENDPOINT_NOT_ACTIVE.status());
page(request, LambdaWebErrorPages.ENDPOINT_NOT_ACTIVE, requestId, false);
return;
}
Integer rateLimit = target.endpoint().throttleConfig == null ? null : target.endpoint().throttleConfig.rateLimit;
if (Integer.valueOf(0).equals(rateLimit)) {
metrics.answered(target, LambdaWebErrorPages.ENDPOINT_DISABLED.status());
@@ -19,6 +19,7 @@ final class LambdaWebErrorPages {
static final Page FORBIDDEN = new Page(403, "Forbidden", null, "You are not authorized to access this endpoint.");
static final Page INVALID_ENDPOINT = new Page(404, "Not Found", "Platform.InvalidEndpoint",
"The requested endpoint could not be found.");
static final Page ENDPOINT_NOT_ACTIVE = new Page(409, "Conflict", "Platform.EndpointNotActive", APPLICATION_ERROR);
static final Page ENDPOINT_DISABLED = new Page(503, "Service Unavailable", "Platform.EndpointDisabled",
"The service is temporarily unable to handle your request. Please try again later.");
static final Page REQUEST_TIMEOUT = new Page(504, "Gateway Timeout", "Runtime.RequestTimeout",
@@ -0,0 +1,11 @@
package io.github.hectorvent.floci.services.lambdaweb;
import io.github.hectorvent.floci.core.common.AwsException;
/** An internal error. AWS answers it with the type in the header and the body {@code {}}. */
public final class LambdaWebInternalServerException extends AwsException {
LambdaWebInternalServerException() {
super("InternalServerException", null, 500);
}
}
@@ -0,0 +1,21 @@
package io.github.hectorvent.floci.services.lambdaweb;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import java.util.Map;
@Provider
public final class LambdaWebInternalServerExceptionMapper implements ExceptionMapper<LambdaWebInternalServerException> {
@Override
public Response toResponse(LambdaWebInternalServerException exception) {
return Response.status(exception.getHttpStatus())
.type(MediaType.APPLICATION_JSON)
.header("X-Amzn-Errortype", exception.getErrorCode())
.entity(Map.of())
.build();
}
}
@@ -52,7 +52,7 @@ final class LambdaWebResponses {
out.put("revisionArn", revision.revisionArn);
out.put("revisionId", revision.revisionId);
putIfPresent(out, "description", revision.description);
putRevisionState(out, view);
putRevisionState(out, revision, view);
out.put("createdAt", timestamp(revision.createdAt));
return out;
}
@@ -87,10 +87,13 @@ final class LambdaWebResponses {
return out;
}
private static void putRevisionState(Map<String, Object> out, View view) {
private static void putRevisionState(Map<String, Object> out, WebFunctionRevision revision, View view) {
if (view == View.CREATED) {
out.put("state", "Pending");
out.put("stateReason", "The revision is being activated.");
} else if (revision.failureReason != null) {
out.put("state", "Failed");
out.put("stateReason", revision.failureReason);
} else {
out.put("state", "Active");
out.put("stateReason", "The revision is active.");
@@ -159,6 +162,15 @@ final class LambdaWebResponses {
: "The endpoint is being activated and is not yet invokable in any region.");
return;
}
if (endpoint.failed) {
out.put("state", "Failed");
out.put("stateReason", regional
? "The endpoint activation failed because of an internal error."
: "The endpoint activation failed in " + endpoint.regions + ". The endpoint is not invokable in"
+ " any region. For details, see the stateReason for those regions in regionalEndpoints."
+ " To retry, delete the endpoint and create it again.");
return;
}
out.put("state", "Active");
out.put("stateReason", regional ? "The endpoint is active in the region." : "The endpoint is active and invokable.");
if (view == View.UPDATED) {
@@ -53,10 +53,11 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Control plane of Lambda Web Functions (apiVersion 2025-03-07). A revision and an endpoint are
* stored Active and an endpoint update is stored Successful. The create and update responses show
* the transitional state AWS reports. Invocation through an endpoint domain is not part of this
* service.
* Control plane of Lambda Web Functions (apiVersion 2025-03-07). A revision is stored Active, or
* Failed when its code is not a zip. An endpoint is stored Active, or Failed when CreateWebFunction
* gives it a Failed revision, and an endpoint update is stored Successful. The create and update
* responses show the transitional state AWS reports. Invocation through an endpoint domain is not
* part of this service.
*/
@ApplicationScoped
public class LambdaWebService implements Resettable {
@@ -95,6 +96,7 @@ public class LambdaWebService implements Resettable {
private static final Set<String> PRINCIPAL_KEYS = Set.of("AWS", "Service", "Federated", "CanonicalUser");
private static final String POLICY_SYNTAX = "Policy has syntax errors.";
private static final String INVALID_PRINCIPAL = "The provided principal was invalid. Please check the principal and try again.";
private static final String NOT_A_ZIP = "Failed to read zip file: zip: not a valid zip file";
private static final String INVALID_TAGS = "One or more of your tags are invalid. Please ensure none of your tag keys"
+ " start with \"aws:\", none are empty, and there are no duplicate tag keys.";
@@ -305,6 +307,7 @@ public class LambdaWebService implements Resettable {
WebFunctionRevision revision = buildRevision(fn, revisionConfig);
keepCode(region, fn, revision);
attachEndpoint(region, fn, endpoint, revision);
endpoint.failed = revision.failureReason != null;
fn.revisions.put(revision.revisionId, revision);
fn.endpoints.put(endpoint.endpointName, endpoint);
indexDomains(fn, endpoint);
@@ -405,7 +408,7 @@ public class LambdaWebService implements Resettable {
keepCode(region, fn, revision);
fn.revisions.put(revision.revisionId, revision);
for (WebFunctionEndpoint endpoint : fn.endpoints.values()) {
if ("LatestRevision".equals(endpoint.autoDeploymentMode)) {
if ("LatestRevision".equals(endpoint.autoDeploymentMode) && revision.failureReason == null) {
endpoint.revisionWeights = List.of(weight(revision.revisionId, 100));
endpoint.updatedAt = now();
}
@@ -431,9 +434,10 @@ public class LambdaWebService implements Resettable {
synchronized (lockFor(region, functionName)) {
WebFunction fn = function(region, functionName);
List<WebFunctionRevision> snapshots = fn.revisions.values().stream()
.filter(r -> list.matchesState(r.failureReason == null ? "Active" : "Failed"))
.map(r -> copy(r, WebFunctionRevision.class))
.toList();
return page(list.matchesState("Active") ? snapshots : List.of(), list,
return page(snapshots, list,
scope("ListWebFunctionRevisions", region, functionName, list), LambdaWebService::newestFirst);
}
}
@@ -587,10 +591,11 @@ public class LambdaWebService implements Resettable {
if (s3Service == null) {
return;
}
String accountId = AwsArnUtils.parse(fn.functionArn).accountId();
WebFunctionRevision.BuildConfig build = revision.buildConfig;
long size;
try (S3Service.ObjectRead object = s3Service.openObject(build.bucket, build.key, build.versionId)) {
code.store(AwsArnUtils.parse(fn.functionArn).accountId(), region, fn.functionName, revision.revisionId,
object.body());
size = code.store(accountId, region, fn.functionName, revision.revisionId, object.body());
} catch (IOException e) {
throw new UncheckedIOException("Could not close the code object s3://" + build.bucket + "/" + build.key, e);
} catch (AwsException e) {
@@ -609,6 +614,15 @@ public class LambdaWebService implements Resettable {
throw new AwsException("ValidationException", "The S3 object " + object + " (versionId=" + build.versionId
+ ") is inaccessible. Verify the request parameters and permissions are correct.", 400);
}
if (size == 0) {
// An empty object is an internal error on AWS.
code.deleteRevision(accountId, region, fn.functionName, revision.revisionId);
throw new LambdaWebInternalServerException();
}
if (!code.opensAsZip(accountId, region, fn.functionName, revision.revisionId)) {
code.deleteRevision(accountId, region, fn.functionName, revision.revisionId);
revision.failureReason = NOT_A_ZIP;
}
}
private static void validateRevisionShape(LambdaWebValidation v, JsonNode request, String prefix) {
@@ -712,9 +726,10 @@ public class LambdaWebService implements Resettable {
synchronized (lockFor(region, functionName)) {
WebFunction fn = function(region, functionName);
List<WebFunctionEndpoint> snapshots = fn.endpoints.values().stream()
.filter(e -> list.matchesState(e.failed ? "Failed" : "Active"))
.map(e -> copy(e, WebFunctionEndpoint.class))
.toList();
return page(list.matchesState("Active") ? snapshots : List.of(), list,
return page(snapshots, list,
scope("ListWebFunctionEndpoints", region, functionName, list), e -> e.endpointName);
}
}
@@ -735,6 +750,10 @@ public class LambdaWebService implements Resettable {
synchronized (lockFor(region, functionName)) {
WebFunction fn = function(region, functionName);
WebFunctionEndpoint endpoint = endpoint(fn, endpointName);
if (endpoint.failed) {
throw new AwsException("ConflictException", "The endpoint " + endpoint.endpointName
+ " is in Failed state. The operation is allowed only when the endpoint is in Active state.", 409);
}
WebFunctionEndpoint before = copy(endpoint, WebFunctionEndpoint.class);
String effectiveMode = mode != null ? mode : endpoint.autoDeploymentMode;
@@ -938,18 +957,29 @@ public class LambdaWebService implements Resettable {
private static List<WebFunctionEndpoint.RevisionWeight> resolveWeights(WebFunction fn,
List<WebFunctionEndpoint.RevisionWeight> weights) {
for (WebFunctionEndpoint.RevisionWeight weight : weights) {
if (!fn.revisions.containsKey(weight.revisionId)) {
WebFunctionRevision revision = fn.revisions.get(weight.revisionId);
if (revision == null) {
throw new AwsException("ResourceNotFoundException",
"The revision " + weight.revisionId + " does not exist.", 404);
}
if (revision.failureReason != null) {
throw new AwsException("ConflictException", "The revision " + weight.revisionId
+ " is in Failed state and cannot be deployed. Only revisions in Active state can be deployed.", 409);
}
}
return List.copyOf(weights);
}
/** The newest revision, which LatestRevision mode deploys. */
private static Optional<String> latestRevision(WebFunction fn) {
return fn.revisions.values().stream()
.max(Comparator.comparing((WebFunctionRevision r) -> r.createdAt))
.map(r -> r.revisionId);
Optional<WebFunctionRevision> latest = fn.revisions.values().stream()
.max(Comparator.comparing((WebFunctionRevision r) -> r.createdAt));
if (latest.isPresent() && latest.get().failureReason != null) {
throw new AwsException("ConflictException", "The latest revision " + latest.get().revisionId
+ " is in Failed state and cannot be deployed. Only revisions in Active state can be deployed."
+ " Create a new revision.", 409);
}
return latest.map(r -> r.revisionId);
}
private static WebFunctionEndpoint.RevisionWeight weight(String revisionId, int weight) {
@@ -26,6 +26,8 @@ public final class WebFunctionEndpoint {
public ScalingConfig scalingConfig;
public ThrottleConfig throttleConfig;
public String updateStatus;
/** Created on a revision that failed. It stays Failed until it is deleted. */
public boolean failed;
public Map<String, String> regionalDomainNames = new LinkedHashMap<>();
public Instant createdAt;
public Instant updatedAt;
@@ -17,6 +17,8 @@ public final class WebFunctionRevision {
public BuildConfig buildConfig = new BuildConfig();
public ServiceConfig serviceConfig = new ServiceConfig();
public Instant createdAt;
/** The stateReason of a Failed revision. */
public String failureReason;
@RegisterForReflection
public static final class BuildConfig {
@@ -1,8 +1,10 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebZips;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
@@ -37,7 +39,7 @@ class CloudFormationLambdaWebIntegrationTest {
@Test
void stackProvisionsFunctionRevisionAndEndpoint() {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, "app.zip", "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
String suffix = Long.toString(System.nanoTime(), 36);
String functionName = "cfn-web-" + suffix;
String stackName = "cfn-web-stack-" + suffix;
@@ -99,6 +101,50 @@ class CloudFormationLambdaWebIntegrationTest {
.then().statusCode(404));
}
@Test
void aRevisionOnCodeThatIsNotAZipFailsItsResource() {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "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);
String functionName = "cfn-web-bad-" + suffix;
String stackName = "cfn-web-bad-stack-" + suffix;
String notZip = template(functionName, 30).replace("\"app.zip\"", "\"notzip.zip\"");
cloudFormation(stackName, "CreateStack", notZip);
await().untilAsserted(() -> describeStacks(stackName, "ROLLBACK_COMPLETE"));
stackEvents(stackName).body(containsString(
"<ResourceStatusReason>Failed to read zip file: zip: not a valid zip file</ResourceStatusReason>"));
given().when().get("/2025-03-07/web-functions/" + functionName).then().statusCode(404);
cloudFormation(stackName, "DeleteStack", null);
// A replacement on such code fails the update, and the rollback deletes it.
String updatedStack = stackName + "-update";
cloudFormation(updatedStack, "CreateStack", template(functionName, 30));
String revisionId = outputs(describeStacks(updatedStack, "CREATE_COMPLETE")).get("RevId");
cloudFormation(updatedStack, "UpdateStack", notZip);
await().untilAsserted(() -> describeStacks(updatedStack, "UPDATE_ROLLBACK_COMPLETE"));
given().contentType("application/json").body("{}")
.when().post("/2025-03-07/web-functions/" + functionName + "/list-revisions")
.then().statusCode(200)
.body("revisions", hasSize(1))
.body("revisions[0].revisionId", equalTo(revisionId));
cloudFormation(updatedStack, "DeleteStack", null);
await().untilAsserted(() -> given().when().get("/2025-03-07/web-functions/" + functionName)
.then().statusCode(404));
}
private static ValidatableResponse stackEvents(String stackName) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
}
/** A revision whose code object does not exist, created after the endpoint, so the update fails there. */
private static final String BAD_REVISION = """
"Bad": {
@@ -271,6 +271,20 @@ class LambdaWebCfnProvisionerTest {
assertEquals("The revision is active.", r.getAttributes().get("StateReason"));
}
@Test
void aFailedRevisionFailsTheResourceAndIsDeleted() {
WebFunctionRevision failed = revision("rev-aaaaa");
failed.failureReason = "Failed to read zip file: zip: not a valid zip file";
when(service.createRevision(eq(REGION), eq("app"), any())).thenReturn(failed);
StackResource r = resource(LambdaWebCfnProvisioner.REVISION);
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, revisionProps(), ctx(null)));
assertEquals("Failed to read zip file: zip: not a valid zip file", e.getMessage());
verify(service).deleteRevision(REGION, FN_ARN, failed.revisionArn);
assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
}
@Test
void unchangedRevisionIsKeptOnUpdate() {
WebFunctionRevision existing = revision("rev-aaaaa");
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebZips;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
@@ -11,7 +12,6 @@ import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -83,7 +83,7 @@ class CloudFrontWebFunctionOriginServingTest {
static String createFunction(S3Service s3Service, PartitionCleanup cleanup, String functionName, String authType) {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, "app.zip", "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
String domain = given().contentType("application/json")
.body("""
{"functionName": "%s",
@@ -94,6 +94,38 @@ class LambdaWebDataPlaneIntegrationTest {
given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);
}
@Test
void anEndpointCreatedOnAFailedRevisionIsNotActive() {
String functionName = "dp-failed-" + Long.toString(System.nanoTime(), 36);
String domain = createFunction(functionName, "ApplicationManaged",
"this is not a zip\n".getBytes(StandardCharsets.UTF_8));
Response response = given().header("Host", domain).when().get("/");
response.then().statusLine("HTTP/1.1 409 Conflict")
.header("content-type", "text/html")
.header("connection", "keep-alive")
.header("lambda-web-error-type", "Platform.EndpointNotActive")
.header("lambda-web-request-id", matchesPattern(REQUEST_ID))
.header("content-length", "225")
.body(equalTo(LambdaWebErrorPages.html(LambdaWebErrorPages.ENDPOINT_NOT_ACTIVE,
response.header("lambda-web-request-id"))));
given().header("Host", domain).when().head("/")
.then().statusCode(409)
.header("lambda-web-error-type", "Platform.EndpointNotActive")
.header("content-length", "225")
.body(equalTo(""));
Map<String, String> endpoint = Map.of("FunctionName", functionName, "EndpointName", "dev");
metrics.awaitPublished(Duration.ofSeconds(5));
assertEquals(2, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "HTTPResponseStatusClass4XX",
endpoint, "Sum"));
assertEquals(0, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "ExecutedRequests", endpoint, "Sum"));
given().when().delete(BASE + "/web-functions/" + functionName + "/endpoints/dev").then().statusCode(204);
given().header("Host", domain).when().get("/")
.then().statusCode(404).header("lambda-web-error-type", "Platform.InvalidEndpoint");
given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);
}
private static String readUntil(InputStream in, String end) throws IOException {
StringBuilder read = new StringBuilder();
while (!read.toString().endsWith(end)) {
@@ -246,8 +278,12 @@ class LambdaWebDataPlaneIntegrationTest {
}
private String createFunction(String functionName, String authType) {
return createFunction(functionName, authType, LambdaWebZips.indexJs(""));
}
private String createFunction(String functionName, String authType, byte[] code) {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, "app.zip", "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", code, "application/zip", Map.of());
return given().contentType("application/json")
.body("""
{"functionName": "%s",
@@ -18,6 +18,7 @@ class LambdaWebErrorPagesTest {
assertEquals(230, length(LambdaWebErrorPages.FORBIDDEN));
assertEquals(225, length(LambdaWebErrorPages.INVALID_ENDPOINT));
assertEquals(264, length(LambdaWebErrorPages.UNSUPPORTED_HTTP_VERSION));
assertEquals(225, length(LambdaWebErrorPages.ENDPOINT_NOT_ACTIVE));
assertEquals(274, length(LambdaWebErrorPages.ENDPOINT_DISABLED));
assertEquals(249, length(LambdaWebErrorPages.REQUEST_TIMEOUT));
assertEquals(236, length(LambdaWebErrorPages.ORIGIN_REQUEST_ERROR));
@@ -52,7 +52,7 @@ class LambdaWebIntegrationTest {
@BeforeAll
void seedCode() {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, KEY, "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
s3Service.putObject(BUCKET, KEY, LambdaWebZips.indexJs(""), "application/zip", Map.of());
}
@Test
@@ -584,4 +584,83 @@ class LambdaWebIntegrationTest {
.then().statusCode(200)
.body("accountUsage.functionCount", equalTo(0));
}
@Test
@Order(11)
void codeThatIsNotAZipFailsTheRevisionAndItsEndpoint() {
String fn = FN + "-failed";
s3Service.putObject(BUCKET, "notzip.zip", "this is not a zip\n".getBytes(StandardCharsets.UTF_8),
"application/zip", Map.of());
s3Service.putObject(BUCKET, "empty.zip", new byte[0], "application/zip", Map.of());
String notZip = """
{"buildConfig": {"codeConfig": {"s3Object": {"bucket": "%s", "key": "notzip.zip"}},
"runtimeConfig": {"runtime": "nodejs24.x"}},
"serviceConfig": {"executionRoleArn": "%s"}}
""".formatted(BUCKET, ROLE);
String failed = given().contentType("application/json")
.body("""
{"functionName": "%s", "revisionConfig": %s,
"endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",
"authType": "ApplicationManaged", "autoDeploymentMode": "LatestRevision"}}
""".formatted(fn, notZip))
.when().put(BASE + "/web-functions")
.then().statusCode(202)
.body("revision.state", equalTo("Pending"))
.body("endpoint.state", equalTo("Pending"))
.extract().path("revision.revisionId");
String reason = "Failed to read zip file: zip: not a valid zip file";
given().when().get(BASE + "/web-functions/" + fn).then().statusCode(200).body("state", equalTo("Active"));
given().when().get(BASE + "/web-functions/" + fn + "/revisions/" + failed)
.then().statusCode(200)
.body("state", equalTo("Failed"))
.body("stateReason", equalTo(reason));
given().when().get(BASE + "/web-functions/" + fn + "/endpoints/dev")
.then().statusCode(200)
.body("state", equalTo("Failed"))
.body("stateReason", equalTo("The endpoint activation failed in [us-east-1]. The endpoint is not"
+ " invokable in any region. For details, see the stateReason for those regions in"
+ " regionalEndpoints. To retry, delete the endpoint and create it again."))
.body("updateStatus", nullValue())
.body("revisionWeights[0].revisionId", equalTo(failed))
.body("regionalEndpoints.us-east-1.state", equalTo("Failed"))
.body("regionalEndpoints.us-east-1.stateReason",
equalTo("The endpoint activation failed because of an internal error."))
.body("regionalEndpoints.us-east-1.updateStatus", nullValue());
String failedFilter = "{\"filters\": [{\"name\": \"state\", \"values\": [\"Failed\"]}]}";
given().contentType("application/json").body(failedFilter)
.when().post(BASE + "/web-functions/" + fn + "/list-revisions")
.then().statusCode(200)
.body("revisions", hasSize(1))
.body("revisions[0].state", equalTo("Failed"))
.body("revisions[0].stateReason", equalTo(reason));
given().contentType("application/json").body(failedFilter)
.when().post(BASE + "/web-functions/" + fn + "/list-endpoints")
.then().statusCode(200)
.body("endpoints", hasSize(1))
.body("endpoints[0].state", equalTo("Failed"));
given().contentType("application/json").body("{\"description\": \"retry\"}")
.when().patch(BASE + "/web-functions/" + fn + "/endpoints/dev")
.then().statusCode(409)
.header("X-Amzn-Errortype", "ConflictException")
.body("message", equalTo("The endpoint dev is in Failed state. The operation is allowed only when"
+ " the endpoint is in Active state."));
given().contentType("application/json").body(notZip)
.when().post(BASE + "/web-functions/" + fn + "/revisions")
.then().statusCode(202)
.body("state", equalTo("Pending"));
// An empty object is an internal error with the body {}, as on AWS.
given().contentType("application/json").body(notZip.replace("notzip.zip", "empty.zip"))
.when().post(BASE + "/web-functions/" + fn + "/revisions")
.then().statusCode(500)
.header("X-Amzn-Errortype", "InternalServerException")
.body(equalTo("{}"));
given().contentType("application/json").body("{}")
.when().post(BASE + "/web-functions/" + fn + "/list-revisions")
.then().statusCode(200)
.body("revisions", hasSize(2));
given().when().delete(BASE + "/web-functions/" + fn).then().statusCode(204);
}
}
@@ -23,15 +23,19 @@ import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -46,6 +50,7 @@ class LambdaWebServiceTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String ARN = "arn:aws:lambda:us-east-1:000000000000:web-function/app";
private static final String ROLE = "arn:aws:iam::000000000000:role/web";
private static final byte[] NOT_A_ZIP = "this is not a zip\n".getBytes(StandardCharsets.UTF_8);
private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
@@ -603,13 +608,15 @@ class LambdaWebServiceTest {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
LambdaWebCode code = new LambdaWebCode(storageDir.resolve("code"));
when(s3.openObject("code", "app.zip", null)).thenReturn(object("first"));
byte[] v1 = LambdaWebZips.indexJs("v1");
byte[] v2 = LambdaWebZips.indexJs("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("second"));
when(s3.openObject("code", "app.zip", null)).thenReturn(object(v2));
String second = service.createRevision(REGION, "app", revisionConfig(30)).revisionId;
assertEquals("first", Files.readString(code.file(ACCOUNT_ID, REGION, "app", first)));
assertEquals("second", Files.readString(code.file(ACCOUNT_ID, REGION, "app", second)));
assertArrayEquals(v1, Files.readAllBytes(code.file(ACCOUNT_ID, REGION, "app", first)));
assertArrayEquals(v2, Files.readAllBytes(code.file(ACCOUNT_ID, REGION, "app", second)));
service.deleteRevision(REGION, "app", first);
assertFalse(Files.exists(code.file(ACCOUNT_ID, REGION, "app", first)));
service.deleteFunction(REGION, "app");
@@ -619,7 +626,8 @@ class LambdaWebServiceTest {
@Test
void aStartKeepsOnlyTheCopiesOfStoredRevisions() throws IOException {
S3Service s3 = mock(S3Service.class);
when(s3.openObject("code", "app.zip", null)).thenReturn(object("code"));
byte[] zip = LambdaWebZips.indexJs("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"))
.revisions.keySet().iterator().next();
@@ -627,7 +635,7 @@ class LambdaWebServiceTest {
code.store(ACCOUNT_ID, REGION, "app", "rev-stray", new ByteArrayInputStream(new byte[] {1}));
service(new FileStorageFactory(storageDir), "http://localhost:4566", s3);
assertEquals("code", Files.readString(code.file(ACCOUNT_ID, REGION, "app", revisionId)));
assertArrayEquals(zip, Files.readAllBytes(code.file(ACCOUNT_ID, REGION, "app", revisionId)));
assertFalse(Files.exists(code.file(ACCOUNT_ID, REGION, "app", "rev-stray")));
service(new MemoryStorageFactory(), "http://localhost:4566", s3);
@@ -644,6 +652,16 @@ class LambdaWebServiceTest {
assertEquals(2, Files.readAllBytes(code.file(ACCOUNT_ID, "_", "app", "rev-aaaaa"))[0]);
}
@Test
void aCopyThatCannotBeReadIsRemoved() throws IOException {
LambdaWebCode code = new LambdaWebCode(storageDir.resolve("code"));
Path copy = code.file(ACCOUNT_ID, REGION, "app", "rev-aaaaa");
Files.createDirectories(copy);
assertThrows(UncheckedIOException.class, () -> code.opensAsZip(ACCOUNT_ID, REGION, "app", "rev-aaaaa"));
assertFalse(Files.exists(copy));
}
@Test
void aVersionThatCannotBeReadIsNamedInTheError() {
S3Service s3 = mock(S3Service.class);
@@ -667,8 +685,110 @@ class LambdaWebServiceTest {
message(() -> service.createFunction(REGION, createRequest("app"))));
}
private static S3Service.ObjectRead object(String data) {
byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
@Test
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")));
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));
assertEquals("Failed to read zip file: zip: not a valid zip file", bad.failureReason);
assertFalse(Files.exists(new LambdaWebCode(storageDir.resolve("code")).file(ACCOUNT_ID, REGION, "app",
bad.revisionId)));
assertEquals(good, service.getEndpoint(REGION, "app", "dev").revisionWeights.get(0).revisionId,
"a LatestRevision endpoint stays on its revision");
assertEquals(List.of(bad.revisionId), service.listRevisions(REGION, "app", stateFilter("Failed")).items()
.stream().map(r -> r.revisionId).toList());
String refusal = "The revision " + bad.revisionId + " is in Failed state and cannot be deployed."
+ " Only revisions in Active state can be deployed.";
ObjectNode toBad = mapper.createObjectNode().put("autoDeploymentMode", "Disabled");
toBad.putArray("revisionWeights").addObject().put("revisionId", bad.revisionId).put("weight", 100);
AwsException update = error(() -> service.updateEndpoint(REGION, "app", "dev", toBad));
assertEquals("ConflictException", update.getErrorCode());
assertEquals(409, update.getHttpStatus());
assertEquals(refusal, update.getMessage());
assertEquals(good, service.getEndpoint(REGION, "app", "dev").revisionWeights.get(0).revisionId);
ObjectNode weighted = endpointConfig("web").put("autoDeploymentMode", "Disabled");
weighted.set("revisionWeights", toBad.get("revisionWeights"));
assertEquals(refusal, message(() -> service.createEndpoint(REGION, "app", weighted)));
String latestRefusal = "The latest revision " + bad.revisionId + " is in Failed state and cannot be deployed."
+ " Only revisions in Active state can be deployed. Create a new revision.";
ObjectNode disabled = mapper.createObjectNode().put("autoDeploymentMode", "Disabled");
disabled.putArray("revisionWeights").addObject().put("revisionId", good).put("weight", 100);
service.updateEndpoint(REGION, "app", "dev", disabled);
assertEquals(latestRefusal, message(() -> service.updateEndpoint(REGION, "app", "dev",
mapper.createObjectNode().put("autoDeploymentMode", "LatestRevision"))));
assertEquals(latestRefusal, message(() -> service.createEndpoint(REGION, "app", endpointConfig("auto"))));
service.deleteRevision(REGION, "app", bad.revisionId);
assertEquals(List.of(good), List.copyOf(service.getFunction(REGION, "app").revisions.keySet()));
}
@Test
void aFunctionCreatedOnCodeThatIsNotAZipHasAFailedEndpoint() {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
when(s3.openObject("code", "app.zip", null)).thenReturn(object(NOT_A_ZIP));
service.createFunction(REGION, createRequest("app"));
WebFunctionEndpoint dev = service.getEndpoint(REGION, "app", "dev");
assertTrue(dev.failed);
String bad = dev.revisionWeights.get(0).revisionId;
assertNotNull(service.getRevision(REGION, "app", bad).failureReason);
AwsException update = error(() -> service.updateEndpoint(REGION, "app", "dev",
mapper.createObjectNode().put("description", "retry")));
assertEquals("ConflictException", update.getErrorCode());
assertEquals("The endpoint dev is in Failed state. The operation is allowed only when the endpoint is in"
+ " 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")));
String good = service.createRevision(REGION, "app", revisionConfig(30)).revisionId;
dev = service.getEndpoint(REGION, "app", "dev");
assertEquals(good, dev.revisionWeights.get(0).revisionId);
assertTrue(dev.failed);
assertEquals(1, service.listEndpoints(REGION, "app", stateFilter("Failed")).items().size());
assertTrue(service.listEndpoints(REGION, "app", stateFilter("Active")).items().isEmpty());
service.deleteRevision(REGION, "app", bad);
service.deleteEndpoint(REGION, "app", "dev");
}
@Test
void anEmptyObjectIsAnInternalErrorThatCreatesNoRevision() throws IOException {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
when(s3.openObject("code", "app.zip", null)).thenReturn(object(new byte[0]));
AwsException create = error(() -> service.createFunction(REGION, createRequest("app")));
assertInstanceOf(LambdaWebInternalServerException.class, create);
assertEquals("InternalServerException", create.getErrorCode());
assertEquals(500, create.getHttpStatus());
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")));
service.createFunction(REGION, createRequest("app"));
when(s3.openObject("code", "app.zip", null)).thenReturn(object(new byte[0]));
assertInstanceOf(LambdaWebInternalServerException.class,
error(() -> service.createRevision(REGION, "app", revisionConfig(30))));
assertEquals(1, service.getFunction(REGION, "app").revisions.size());
try (Stream<Path> copies = Files.walk(storageDir.resolve("code"))) {
assertEquals(1, copies.filter(Files::isRegularFile).count());
}
}
private ObjectNode stateFilter(String state) {
ObjectNode request = mapper.createObjectNode();
request.putArray("filters").addObject().put("name", "state").putArray("values").add(state);
return request;
}
private static S3Service.ObjectRead object(byte[] bytes) {
return new S3Service.ObjectRead(new S3Object("code", "app.zip", bytes, "application/zip"),
new ByteArrayInputStream(bytes));
}
@@ -0,0 +1,27 @@
package io.github.hectorvent.floci.services.lambdaweb;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/** Code packages for tests that create Web Function revisions. */
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();
}
}