feat(lambda-web): move a revision to Failed once its code is gone (#7065)

This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-31 10:11:21 -04:00
1 parent 6f982a177b
commit 32a47daee0
7 files changed
+157 -15

No files matched your search

+1 -1
View File
@@ -37,7 +37,7 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A
- **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, or whose files add up to more than 512 MiB, 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 `{}`, and an object over 512 MiB is a `400 ValidationException`, as on AWS.
- **Code comes from S3 only.** The object named in `buildConfig.codeConfig.s3Object` must exist in Floci's S3, as on AWS. A request without `versionId` is refused when the latest version is the null version, so the object has to be written after the bucket's versioning is enabled, as on AWS. When IAM enforcement is on, the bucket policy must also let `lambda.amazonaws.com` take `s3:GetObjectVersion` on the object. The policy sees the new revision ARN as `aws:SourceArn`, the function's account as `aws:SourceAccount` and the version Lambda reads as `s3:VersionId`. As on AWS, `s3:GetObject` is not evaluated, although the error names it. Floci does not check the caller's own S3 permissions or the KMS key policy of an encrypted object.
- **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.
- **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 in the bucket or a delete marker does not change what the revision runs. Deleting that object version, or taking away Lambda's `s3:GetObjectVersion` on it under IAM enforcement, moves the revision to `Failed` for good, as on AWS. AWS does this when it next checks the object, at a time it does not document. Floci checks each time it reads the revision's state or routes a request to it, so the revision fails at once. Its `stateReason` is the `CreateWebFunctionRevision` refusal for the same cause, as AWS's wording was not seen. Endpoints keep their weights, and the requests routed to the revision get `409` with `Platform.RevisionNotActive`.
- **Revision cleanup:** when a revision turns `Active` and the function has more than 50, the oldest revisions that no endpoint routes to are deleted until 50 are left, `Failed` ones included, as on AWS. A new `Failed` revision deletes nothing. The revision that a `LatestRevision` endpoint leaves is not deleted before the next revision turns `Active`, as on AWS.
- **Execution role:** a role in another account is `403 AccessDeniedException` "Cross-account pass role is not allowed.". A role that does not exist in IAM, or whose trust policy does not let `lambda.amazonaws.com` assume it, is `400 ValidationException` "The execution role <arn> cannot be assumed by lambda.amazonaws.com. Verify its trust policy. If the role was just created, retry in a few seconds.". As on AWS, this check sets no `aws:SourceAccount` or `aws:SourceArn`, so a trust policy that requires either refuses the role.
- **Egress network connectors:** `egressNetworkConnectorArn` names a connector version by the connector id, in the function's region, as on AWS. A version that does not exist, a connector name, or another region is `404 ResourceNotFoundException` "The egress network connector <arn> does not exist.". A connector without `WebFunction` in its `AssociatedComputeResourceTypes` is `400 ValidationException`. An unknown region, a partition that is not the region's, or a version such as `0` or `01` is `400 ValidationException` "The egress network connector ARN: '<arn>' is not valid. ...", and a connector in another account is `403 AccessDeniedException`. A version past the 64-bit range is `500 InternalServerException` with the body `{}`, as on AWS. Only a `HomeRegion` endpoint can serve such a revision: `CreateWebFunction` with another endpoint type, and weights of a `PerRegion` or `MultiRegion` endpoint that name such a revision, are `400 ValidationException`. Floci settles a connector at once, so the AWS refusal of a `PENDING` version never happens. When IAM enforcement is on, the caller also needs `lambda:PassNetworkConnector` on the version ARN as the request gives it, refused as on AWS (see [IAM](iam.md)). Floci checks it before the request reaches Lambda, so a refusal comes before the ARN checks above, which AWS runs first. The connector does not change the network of the function's container.
@@ -243,6 +243,9 @@ public class LambdaWebDataPlane {
if (dead != null) {
environments.discard(dead);
}
if (!service.isRevisionActive(target, revision.revisionId)) {
throw new StartFailure(LambdaWebErrorPages.REVISION_NOT_ACTIVE);
}
Integer maxEnvironments = target.endpoint().scalingConfig == null
? null : target.endpoint().scalingConfig.maxEnvironments;
return environments.acquire(target.accountId(), target.servingRegion(), target.function(),
@@ -20,6 +20,8 @@ final class LambdaWebErrorPages {
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);
/** Not recorded against AWS. It follows the EndpointNotActive page. */
static final Page REVISION_NOT_ACTIVE = new Page(409, "Conflict", "Platform.RevisionNotActive", 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",
@@ -42,6 +42,7 @@ import java.net.URI;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
@@ -250,6 +251,25 @@ public class LambdaWebService implements Resettable {
return Optional.ofNullable(originHosts.get(host));
}
/**
* Whether a request routed to {@code revisionId} may run. It can fail and store the revision, so it is called off
* the event loop.
*/
public boolean isRevisionActive(WebFunctionTarget target, String revisionId) {
String functionName = target.function().functionName;
return RequestScopes.callAs(target.accountId(), target.region(), () -> {
synchronized (lockFor(target.region(), functionName)) {
WebFunction fn = functions.get(key(target.region(), functionName)).orElse(null);
WebFunctionRevision revision = fn == null ? null : fn.revisions.get(revisionId);
if (revision == null) {
return true;
}
failLostCode(target.region(), fn, List.of(revision));
return revision.failureReason == null;
}
});
}
/**
* AWS serves the MultiRegion global domain in the region nearest the caller. Floci takes the default region for
* that when the endpoint has it, and the home region otherwise.
@@ -507,7 +527,10 @@ public class LambdaWebService implements Resettable {
String functionName = resolveFunctionName(region, functionNameOrArn, "GetWebFunctionRevision");
String revisionId = resolveRevisionId(region, revisionIdOrArn, "GetWebFunctionRevision");
synchronized (lockFor(region, functionName)) {
return copy(revision(function(region, functionName), revisionId), WebFunctionRevision.class);
WebFunction fn = function(region, functionName);
WebFunctionRevision revision = revision(fn, revisionId);
failLostCode(region, fn, List.of(revision));
return copy(revision, WebFunctionRevision.class);
}
}
@@ -517,6 +540,7 @@ public class LambdaWebService implements Resettable {
String functionName = resolveFunctionName(region, functionNameOrArn, "ListWebFunctionRevisions");
synchronized (lockFor(region, functionName)) {
WebFunction fn = function(region, functionName);
failLostCode(region, fn, fn.revisions.values());
List<WebFunctionRevision> snapshots = fn.revisions.values().stream()
.filter(r -> list.matchesState(r.failureReason == null ? "Active" : "Failed"))
.map(r -> copy(r, WebFunctionRevision.class))
@@ -745,8 +769,9 @@ public class LambdaWebService implements Resettable {
throw new AwsException("ValidationException", "Zipped size must be smaller than "
+ LambdaWebCode.MAX_BYTES + " bytes", 400);
}
requireLambdaCanRead(fn, revision,
build.versionId != null ? build.versionId : object.object().getVersionId());
String versionId = build.versionId != null ? build.versionId : object.object().getVersionId();
requireLambdaCanRead(fn, revision, versionId);
revision.codeVersionId = versionId;
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);
@@ -768,20 +793,68 @@ public class LambdaWebService implements Resettable {
}
}
/** AWS evaluates only s3:GetObjectVersion, although its message names both actions. */
/**
* AWS moves a revision to Failed for good once it finds its object version gone or closed to Lambda, at a time it
* does not document. Floci looks each time a revision's state is read or a request is routed to it. The copy of
* the code stays until the revision is deleted, as an environment may be starting from it.
*/
private void failLostCode(String region, WebFunction fn, Collection<WebFunctionRevision> revisions) {
if (s3Service == null) {
return;
}
boolean failed = false;
for (WebFunctionRevision revision : revisions) {
if (revision.failureReason != null || revision.codeVersionId == null) {
continue;
}
revision.failureReason = lostCodeReason(fn, revision);
failed |= revision.failureReason != null;
}
if (failed) {
persist(region, fn);
}
}
/** AWS's stateReason for this was not seen, so it is the CreateWebFunctionRevision refusal for the same cause. */
private String lostCodeReason(WebFunction fn, WebFunctionRevision revision) {
WebFunctionRevision.BuildConfig build = revision.buildConfig;
try {
s3Service.headObject(build.bucket, build.key, revision.codeVersionId);
} catch (AwsException e) {
if (e.getHttpStatus() != 404) {
throw e;
}
return missingVersion(build, revision.codeVersionId);
}
return lambdaCanRead(fn, revision, revision.codeVersionId) ? null : lambdaCannotRead(build);
}
private void requireLambdaCanRead(WebFunction fn, WebFunctionRevision revision, String versionId) {
if (!lambdaCanRead(fn, revision, versionId)) {
throw new AwsException("ValidationException", lambdaCannotRead(revision.buildConfig), 400);
}
}
/** AWS evaluates only s3:GetObjectVersion, although its message names both actions. */
private boolean lambdaCanRead(WebFunction fn, WebFunctionRevision revision, String versionId) {
WebFunctionRevision.BuildConfig build = revision.buildConfig;
AwsArnUtils.Arn function = AwsArnUtils.parse(fn.functionArn);
String objectArn = AwsArnUtils.Arn.global(function.partition(), "s3", "", build.bucket + "/" + build.key)
.toString();
if (serviceCalls.authorize("lambda", "s3:GetObjectVersion", objectArn, revision.revisionArn,
return serviceCalls.authorize("lambda", "s3:GetObjectVersion", objectArn, revision.revisionArn,
function.accountId(), Map.of(IamConditionContextResolver.VERSION_ID, List.of(versionId)))
== Decision.DENY) {
throw new AwsException("ValidationException", "Lambda service principal " + ServicePrincipals.of("lambda")
+ " does not have s3:GetObject and s3:GetObjectVersion permission on s3://" + build.bucket + "/"
+ build.key + ". Update the bucket policy to grant the Lambda service principal access and retry.",
400);
}
!= Decision.DENY;
}
private static String lambdaCannotRead(WebFunctionRevision.BuildConfig build) {
return "Lambda service principal " + ServicePrincipals.of("lambda")
+ " does not have s3:GetObject and s3:GetObjectVersion permission on s3://" + build.bucket + "/"
+ build.key + ". Update the bucket policy to grant the Lambda service principal access and retry.";
}
private static String missingVersion(WebFunctionRevision.BuildConfig build, String versionId) {
return "The specified S3 object does not exist: s3://" + build.bucket + "/" + build.key
+ " (versionId=" + versionId + "). Verify the object exists and the versionId is correct.";
}
private S3Service.ObjectRead openCode(WebFunctionRevision.BuildConfig build) {
@@ -796,9 +869,7 @@ public class LambdaWebService implements Resettable {
+ ". Verify the object exists in the bucket.", 400);
}
if (e.getHttpStatus() == 404) {
throw new AwsException("ValidationException", "The specified S3 object does not exist: " + object
+ " (versionId=" + build.versionId + "). Verify the object exists and the versionId is correct.",
400);
throw new AwsException("ValidationException", missingVersion(build, build.versionId), 400);
}
throw new AwsException("ValidationException", "The S3 object " + object + " (versionId=" + build.versionId
+ ") is inaccessible. Verify the request parameters and permissions are correct.", 400);
@@ -934,6 +1005,7 @@ public class LambdaWebService implements Resettable {
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);
}
failLostCode(region, fn, fn.revisions.values());
WebFunctionEndpoint before = copy(endpoint, WebFunctionEndpoint.class);
String effectiveMode = mode != null ? mode : endpoint.autoDeploymentMode;
@@ -1052,6 +1124,7 @@ public class LambdaWebService implements Resettable {
if (fn.endpoints.containsKey(endpoint.endpointName)) {
throw new AwsException("ConflictException", "The endpoint " + endpoint.endpointName + " already exists.", 409);
}
failLostCode(region, fn, fn.revisions.values());
if (initialRevision != null) {
endpoint.revisionWeights = List.of(weight(initialRevision.revisionId, 100));
} else if (!endpoint.revisionWeights.isEmpty()) {
@@ -19,6 +19,8 @@ public final class WebFunctionRevision {
public Instant createdAt;
/** The stateReason of a Failed revision. */
public String failureReason;
/** The object version the code was read from, also when the request named none. */
public String codeVersionId;
@RegisterForReflection
public static final class BuildConfig {
@@ -127,6 +127,26 @@ class LambdaWebCodeBucketIntegrationTest {
accepted(older);
}
@Test
void aRevisionFailsForGoodOnceLambdaCanNoLongerReadItsCode() {
s3Service.putBucketVersioning(bucket, "Enabled");
put(bucket);
LambdaWebCodeBuckets.allowLambda(s3Service, bucket);
String revisionId = createRevision(null).statusCode(202).extract().path("revisionId");
String revision = BASE + "/web-functions/" + functionName + "/revisions/" + revisionId;
given().header("Authorization", ROOT).when().get(revision)
.then().statusCode(200).body("state", equalTo("Active"));
s3Service.deleteBucketPolicy(bucket);
given().header("Authorization", ROOT).when().get(revision)
.then().statusCode(200)
.body("state", equalTo("Failed"))
.body("stateReason", equalTo(lambdaRefusal()));
LambdaWebCodeBuckets.allowLambda(s3Service, bucket);
given().header("Authorization", ROOT).when().get(revision)
.then().statusCode(200).body("state", equalTo("Failed"));
}
private String lambdaRefusal() {
return "Lambda service principal lambda.amazonaws.com does not have s3:GetObject and s3:GetObjectVersion"
+ " permission on s3://" + bucket + "/app.zip. Update the bucket policy to grant the Lambda service"
@@ -131,6 +131,48 @@ class LambdaWebDataPlaneIntegrationTest {
given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);
}
@Test
void aRevisionWhoseCodeVersionIsDeletedFailsForGood() {
String functionName = "dp-lost-" + Long.toString(System.nanoTime(), 36);
String domain = createFunction(functionName);
String versionId = s3Service.headObject(BUCKET, "app.zip").getVersionId();
String endpoint = BASE + "/web-functions/" + functionName + "/endpoints/dev";
String revisionId = given().when().get(endpoint).then().statusCode(200)
.extract().path("revisionWeights[0].revisionId");
String revision = BASE + "/web-functions/" + functionName + "/revisions/" + revisionId;
// A delete marker leaves the version the revision runs.
s3Service.deleteObject(BUCKET, "app.zip");
given().when().get(revision).then().statusCode(200).body("state", equalTo("Active"));
s3Service.deleteObject(BUCKET, "app.zip", versionId);
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.RevisionNotActive")
.header("content-length", "225")
.body(equalTo(LambdaWebErrorPages.html(LambdaWebErrorPages.REVISION_NOT_ACTIVE,
response.header("lambda-web-request-id"))));
String reason = "The specified S3 object does not exist: s3://" + BUCKET + "/app.zip (versionId=" + versionId
+ "). Verify the object exists and the versionId is correct.";
given().when().get(revision).then().statusCode(200)
.body("state", equalTo("Failed"))
.body("stateReason", equalTo(reason));
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "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
+ "\", \"weight\": 100}]}")
.when().patch(endpoint)
.then().statusCode(409)
.body("message", equalTo("The revision " + revisionId + " is in Failed state and cannot be deployed."
+ " Only revisions in Active state can be deployed."));
given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);
}
@Test
void anEnvironmentDoesNotStartWhenLambdaCanNoLongerAssumeTheRole() {
String functionName = "dp-role-" + Long.toString(System.nanoTime(), 36);