fix(lambdaweb): give the code bucket check the version as s3:VersionId (#6483)

This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-25 07:39:20 -04:00
1 parent 3dc5d356d0
commit 8f3a6eafeb
6 files changed
+61 -10

No files matched your search

+1 -1
View File
@@ -36,7 +36,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` and the function's account as `aws:SourceAccount`. 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.
- **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.
- **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. The network connector ARN is checked for shape only.
- **Resource policies** are checked the way AWS checks them before storing: the document grammar, a `lambda:` action, a `Resource` that names the function, a valid principal, and no public `Allow`. A wildcard principal needs a positive condition (`StringEquals`, `StringLike`, `ArnLike`, `Bool`) on a trusted key such as `aws:PrincipalAccount` or `aws:PrincipalArn`, with no wildcard in the account it names. An `IamAuth` endpoint evaluates it on requests, as below.
@@ -59,6 +59,15 @@ public class ServiceCallAuthorizer {
*/
public Decision authorize(String service, String action, String resourceArn,
String sourceArn, String sourceAccount) {
return authorize(service, action, resourceArn, sourceArn, sourceAccount, Map.of());
}
/**
* As {@link #authorize(String, String, String, String, String)}, with the keys the target
* service adds for the request, such as {@code s3:versionid} for an object version.
*/
public Decision authorize(String service, String action, String resourceArn, String sourceArn,
String sourceAccount, Map<String, List<String>> requestKeys) {
if (!config.services().iam().enforcementEnabled()) {
return Decision.ALLOW;
}
@@ -73,6 +82,7 @@ public class ServiceCallAuthorizer {
.toList();
Map<String, List<String>> context = IamConditionContextResolver.serviceCallContext(
servicePrincipal, resourceArn, ownerAccountId, sourceArn, sourceAccount);
context.putAll(requestKeys);
Decision decision = evaluator.evaluateServicePrincipal(
documents.isEmpty() ? null : documents, servicePrincipal, action, resourceArn, context);
if (decision == Decision.DENY) {
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -640,7 +641,8 @@ public class LambdaWebService implements Resettable {
throw new AwsException("ValidationException", "Zipped size must be smaller than "
+ LambdaWebCode.MAX_BYTES + " bytes", 400);
}
requireLambdaCanRead(fn, revision);
requireLambdaCanRead(fn, revision,
build.versionId != null ? build.versionId : object.object().getVersionId());
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);
@@ -663,13 +665,14 @@ public class LambdaWebService implements Resettable {
}
/** AWS evaluates only s3:GetObjectVersion, although its message names both actions. */
private void requireLambdaCanRead(WebFunction fn, WebFunctionRevision revision) {
private void requireLambdaCanRead(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,
function.accountId()) == Decision.DENY) {
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.",
@@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
@@ -121,6 +122,23 @@ class ServiceCallAuthorizerTest {
authorizer.authorize("s3", "sns:Publish", TOPIC, "arn:aws:s3:::bucket", OWNER));
}
@Test
void theKeysTheTargetAddsReachThePolicy() {
String object = "arn:aws:s3:::code/app.zip";
String policy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"lambda.amazonaws.com"},"Action":"s3:GetObjectVersion","Resource":"%s",
"Condition":{"StringEquals":{"s3:VersionId":"v2"}}}]}""".formatted(object);
providers.add((scope, arn) -> object.equals(arn)
? List.of(new ResourcePolicyProvider.ResourcePolicy(policy, OWNER)) : List.of());
assertEquals(Decision.ALLOW, authorizer.authorize("lambda", "s3:GetObjectVersion", object, null, OWNER,
Map.of(IamConditionContextResolver.VERSION_ID, List.of("v2"))));
assertEquals(Decision.DENY, authorizer.authorize("lambda", "s3:GetObjectVersion", object, null, OWNER,
Map.of(IamConditionContextResolver.VERSION_ID, List.of("v1"))));
assertEquals(Decision.DENY, authorizer.authorize("lambda", "s3:GetObjectVersion", object, null, OWNER));
}
@Test
void aDenyInTheTopicPolicyWins() {
topicPolicy("""
@@ -92,9 +92,7 @@ class LambdaWebCodeBucketIntegrationTest {
void lambdaNeedsGetObjectVersionUnderTheConditionsItSends() {
s3Service.putBucketVersioning(bucket, "Enabled");
put(bucket);
String refusal = "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 principal access and retry.";
String refusal = lambdaRefusal();
refused(null, refusal);
policy(allow("\"s3:GetObject\"", null));
@@ -115,8 +113,29 @@ class LambdaWebCodeBucketIntegrationTest {
refused(null, refusal);
}
private void put(String in) {
s3Service.putObject(in, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
@Test
void aGrantForOneVersionAdmitsOnlyThatVersion() {
s3Service.putBucketVersioning(bucket, "Enabled");
String older = put(bucket);
String latest = put(bucket);
policy(allow("\"s3:GetObjectVersion\"", "{\"StringEquals\":{\"s3:VersionId\":\"" + latest + "\"}}"));
accepted(null);
accepted(latest);
refused(older, lambdaRefusal());
policy(allow("\"s3:GetObjectVersion\"", "{\"StringEquals\":{\"s3:VersionId\":\"" + older + "\"}}"));
refused(null, lambdaRefusal());
accepted(older);
}
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"
+ " principal access and retry.";
}
private String put(String in) {
return s3Service.putObject(in, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of())
.getVersionId();
}
private void policy(String statements) {
@@ -947,7 +947,8 @@ class LambdaWebServiceTest {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
when(serviceCalls.authorize(eq("lambda"), eq("s3:GetObjectVersion"), eq("arn:aws:s3:::code/app.zip"),
startsWith(ARN + "/revision/rev-"), eq(ACCOUNT_ID))).thenReturn(Decision.DENY);
startsWith(ARN + "/revision/rev-"), eq(ACCOUNT_ID), eq(Map.of("s3:versionid", List.of("v1")))))
.thenReturn(Decision.DENY);
when(s3.openObject("code", "app.zip", null)).thenReturn(object(new byte[0]));
AwsException create = error(() -> service.createFunction(REGION, createRequest("app")));