feat(lambdaweb): check the code bucket versioning and policy as AWS does (#6479)

This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-24 23:33:50 -04:00
1 parent 3053b35b84
commit cd2dac708d
14 files changed
+313 -18

No files matched your search

@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebCodeBuckets;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebRoles;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebZips;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -44,7 +45,7 @@ class CloudFormationLambdaWebIntegrationTest {
@Test
void stackProvisionsFunctionRevisionAndEndpoint() {
LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/cfn-web");
s3Service.createBucket(BUCKET, "us-east-1");
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
String suffix = Long.toString(System.nanoTime(), 36);
String functionName = "cfn-web-" + suffix;
@@ -110,7 +111,7 @@ class CloudFormationLambdaWebIntegrationTest {
@Test
void aRevisionOnCodeThatIsNotAZipFailsItsResource() {
LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/cfn-web");
s3Service.createBucket(BUCKET, "us-east-1");
LambdaWebCodeBuckets.create(s3Service, BUCKET);
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());
@@ -5,6 +5,7 @@ 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.iam.IamService;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebCodeBuckets;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebRoles;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebZips;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -89,7 +90,7 @@ class CloudFrontWebFunctionOriginServingTest {
static String createFunction(S3Service s3Service, IamService iamService, PartitionCleanup cleanup,
String functionName, String authType) {
LambdaWebRoles.trustLambda(iamService, ROLE);
s3Service.createBucket(BUCKET, "us-east-1");
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
String domain = given().contentType("application/json")
.body("""
@@ -0,0 +1,161 @@
package io.github.hectorvent.floci.services.lambdaweb;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.Map;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/** Under IAM enforcement the code bucket must be versioned and let Lambda read the object version. */
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class LambdaWebCodeBucketIntegrationTest {
private static final String BASE = "/2025-03-07";
private static final String ROOT = auth("000000000000", "lambda");
private static final String ROLE = "arn:aws:iam::000000000000:role/web";
private static final String VERSIONING = "You must enable S3 versioning for your S3 bucket when"
+ " S3ObjectStorageMode is set to REFERENCE.";
@TestHTTPResource("/")
static URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Inject
S3Service s3Service;
@Inject
IamService iamService;
private String functionName;
private String functionArn;
private String bucket;
@BeforeEach
void createFunction() {
functionName = "code-bucket-" + Long.toString(System.nanoTime(), 36);
functionArn = "arn:aws:lambda:us-east-1:000000000000:web-function/" + functionName;
bucket = functionName;
LambdaWebRoles.trustLambda(iamService, ROLE);
LambdaWebCodeBuckets.create(s3Service, "web-code-bucket");
put("web-code-bucket");
int port = baseUri.getPort();
String name = functionName;
cleanup.register(() -> given().port(port).header("Authorization", ROOT)
.delete(BASE + "/web-functions/" + name));
given().header("Authorization", ROOT).contentType("application/json")
.body("""
{"functionName": "%s",
"revisionConfig": {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s"}},
"endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",
"authType": "ApplicationManaged"}}
""".formatted(functionName, build("web-code-bucket", null), ROLE))
.when().put(BASE + "/web-functions")
.then().statusCode(202);
s3Service.createBucket(bucket, "us-east-1");
}
@Test
void theLatestVersionOfTheObjectMustNotBeTheNullVersion() {
LambdaWebCodeBuckets.allowLambda(s3Service, bucket);
put(bucket);
refused(null, VERSIONING);
s3Service.putBucketVersioning(bucket, "Enabled");
refused(null, VERSIONING);
accepted("null");
put(bucket);
accepted(null);
s3Service.putBucketVersioning(bucket, "Suspended");
accepted(null);
put(bucket);
refused(null, VERSIONING);
}
@Test
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.";
refused(null, refusal);
policy(allow("\"s3:GetObject\"", null));
refused(null, refusal);
policy(allow("\"s3:GetObjectVersion\"", null));
accepted(null);
policy(allow("\"s3:GetObjectVersion\"", "{\"ArnLike\":{\"aws:SourceArn\":\"" + functionArn + "/revision/*\"}}"));
accepted(null);
policy(allow("\"s3:GetObjectVersion\"", "{\"ArnLike\":{\"aws:SourceArn\":\"" + functionArn + "\"}}"));
refused(null, refusal);
policy(allow("\"s3:GetObjectVersion\"", "{\"StringEquals\":{\"aws:SourceAccount\":\"000000000000\"}}"));
accepted(null);
policy(allow("\"s3:GetObjectVersion\"", "{\"StringEquals\":{\"aws:SourceAccount\":\"111111111111\"}}"));
refused(null, refusal);
policy(allow("[\"s3:GetObject\",\"s3:GetObjectVersion\"]", null) + "," + deny("s3:GetObject"));
accepted(null);
policy(allow("[\"s3:GetObject\",\"s3:GetObjectVersion\"]", null) + "," + deny("s3:GetObjectVersion"));
refused(null, refusal);
}
private void put(String in) {
s3Service.putObject(in, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
}
private void policy(String statements) {
s3Service.putBucketPolicy(bucket, "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
private String allow(String actions, String condition) {
return "{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":" + actions
+ ",\"Resource\":\"arn:aws:s3:::" + bucket + "/*\"" + (condition == null ? "" : ",\"Condition\":"
+ condition) + "}";
}
private String deny(String action) {
return "{\"Effect\":\"Deny\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"" + action
+ "\",\"Resource\":\"arn:aws:s3:::" + bucket + "/*\"}";
}
private static String build(String in, String versionId) {
return """
{"codeConfig": {"s3Object": {"bucket": "%s", "key": "app.zip"%s}}, "runtimeConfig": {"runtime": "nodejs24.x"}}
""".formatted(in, versionId == null ? "" : ", \"versionId\": \"" + versionId + "\"");
}
private ValidatableResponse createRevision(String versionId) {
return given().header("Authorization", ROOT).contentType("application/json")
.body("""
{"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s"}}
""".formatted(build(bucket, versionId), ROLE))
.when().post(BASE + "/web-functions/" + functionName + "/revisions")
.then();
}
private void accepted(String versionId) {
createRevision(versionId).statusCode(202);
}
private void refused(String versionId, String message) {
createRevision(versionId).statusCode(400)
.header("X-Amzn-Errortype", "ValidationException")
.body("message", equalTo(message));
}
}
@@ -0,0 +1,26 @@
package io.github.hectorvent.floci.services.lambdaweb;
import io.github.hectorvent.floci.services.s3.S3Service;
/** Code buckets for tests that create Web Function revisions. */
public final class LambdaWebCodeBuckets {
private static final String LAMBDA_READ = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"lambda.amazonaws.com"},"Action":["s3:GetObject","s3:GetObjectVersion"],
"Resource":"arn:aws:s3:::%s/*"}]}""";
private LambdaWebCodeBuckets() {
}
/** Creates a versioned bucket that lets Lambda read the code, as AWS requires. */
public static void create(S3Service s3Service, String bucket) {
s3Service.createBucket(bucket, "us-east-1");
s3Service.putBucketVersioning(bucket, "Enabled");
allowLambda(s3Service, bucket);
}
public static void allowLambda(S3Service s3Service, String bucket) {
s3Service.putBucketPolicy(bucket, LAMBDA_READ.formatted(bucket));
}
}
@@ -631,7 +631,7 @@ class LambdaWebDataPlaneDockerIntegrationTest {
String mode, String authType, String nodeOptions) throws IOException {
functionName = "dp-docker-" + Long.toString(System.nanoTime(), 36);
LambdaWebRoles.trustLambda(iamService, ROLE);
s3Service.createBucket(BUCKET, "us-east-1");
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, functionName + ".zip", zip(APP), "application/zip", Map.of());
return given().contentType("application/json")
.body("""
@@ -383,7 +383,7 @@ class LambdaWebDataPlaneIntegrationTest {
private String createFunction(String region, String functionName, String authType, byte[] code, String role) {
LambdaWebRoles.trustLambda(iamService, role);
s3Service.createBucket(BUCKET, "us-east-1");
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, "app.zip", code, "application/zip", Map.of());
return given().header("Authorization", auth("test", region, "lambda")).contentType("application/json")
.body("""
@@ -70,7 +70,7 @@ class LambdaWebIamAuthIntegrationTest {
void createFunction() throws IOException {
functionName = "iam-auth-" + Long.toString(System.nanoTime(), 36);
LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/web");
s3Service.createBucket(BUCKET, "us-east-1");
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, functionName + ".zip", zip(), "application/zip", Map.of());
int port = baseUri.getPort();
String name = functionName;
@@ -56,7 +56,7 @@ class LambdaWebIntegrationTest {
@BeforeAll
void seedCode() {
LambdaWebRoles.trustLambda(iamService, ROLE);
s3Service.createBucket(BUCKET, "us-east-1");
LambdaWebCodeBuckets.create(s3Service, BUCKET);
s3Service.putObject(BUCKET, KEY, LambdaWebZips.indexJs(""), "application/zip", Map.of());
}
@@ -9,10 +9,12 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceCallAuthorizer;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionRevision;
@@ -40,6 +42,8 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -53,6 +57,7 @@ class LambdaWebServiceTest {
private static final byte[] NOT_A_ZIP = "this is not a zip\n".getBytes(StandardCharsets.UTF_8);
private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
private final ServiceCallAuthorizer serviceCalls = mock(ServiceCallAuthorizer.class);
@TempDir
Path storageDir;
@@ -78,7 +83,7 @@ class LambdaWebServiceTest {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.effectiveBaseUrl()).thenReturn(baseUrl);
LambdaWebService service = new LambdaWebService(new RegionResolver(REGION, ACCOUNT_ID), storage, config,
s3Service, new LambdaWebCode(storageDir.resolve("code")), mapper, null, executionRole);
s3Service, new LambdaWebCode(storageDir.resolve("code")), mapper, null, executionRole, serviceCalls);
service.initializeStorage();
return service;
}
@@ -915,6 +920,55 @@ class LambdaWebServiceTest {
}
}
@Test
void theNullVersionAsTheLatestIsRefusedBeforeTheSize() {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
byte[] zip = LambdaWebZips.indexJs("");
when(s3.openObject("code", "app.zip", null)).thenReturn(nullVersion(object(zip, LambdaWebCode.MAX_BYTES + 1)));
AwsException create = error(() -> service.createFunction(REGION, createRequest("app")));
assertEquals("ValidationException", create.getErrorCode());
assertEquals(400, create.getHttpStatus());
assertEquals("You must enable S3 versioning for your S3 bucket when S3ObjectStorageMode is set to REFERENCE.",
create.getMessage());
assertEquals("The function arn:aws:lambda:us-east-1:000000000000:web-function/app does not exist.",
message(() -> service.getFunction(REGION, "app")));
ObjectNode pinned = createRequest("app");
((ObjectNode) pinned.path("revisionConfig").path("buildConfig").path("codeConfig").path("s3Object"))
.put("versionId", "null");
when(s3.openObject("code", "app.zip", "null")).thenReturn(nullVersion(object(zip)));
assertNull(service.createFunction(REGION, pinned).revisions.values().iterator().next().failureReason);
}
@Test
void lambdaMustBeAllowedToReadTheObjectVersionAfterTheSizeCheck() throws IOException {
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);
when(s3.openObject("code", "app.zip", null)).thenReturn(object(new byte[0]));
AwsException create = error(() -> service.createFunction(REGION, createRequest("app")));
assertEquals("ValidationException", create.getErrorCode());
assertEquals(400, create.getHttpStatus());
assertEquals("Lambda service principal lambda.amazonaws.com does not have s3:GetObject and s3:GetObjectVersion"
+ " permission on s3://code/app.zip. Update the bucket policy to grant the Lambda service principal"
+ " access and retry.", create.getMessage());
assertEquals("The function arn:aws:lambda:us-east-1:000000000000:web-function/app does not exist.",
message(() -> service.getFunction(REGION, "app")));
Files.createDirectories(storageDir.resolve("code"));
try (Stream<Path> copies = Files.walk(storageDir.resolve("code"))) {
assertEquals(0, copies.filter(Files::isRegularFile).count());
}
when(s3.openObject("code", "app.zip", null))
.thenReturn(object(LambdaWebZips.indexJs(""), LambdaWebCode.MAX_BYTES + 1));
assertEquals("Zipped size must be smaller than 536870912 bytes",
message(() -> service.createFunction(REGION, createRequest("app"))));
}
private ObjectNode stateFilter(String state) {
ObjectNode request = mapper.createObjectNode();
request.putArray("filters").addObject().put("name", "state").putArray("values").add(state);
@@ -922,14 +976,22 @@ class LambdaWebServiceTest {
}
private static S3Service.ObjectRead object(byte[] bytes) {
return new S3Service.ObjectRead(new S3Object("code", "app.zip", bytes, "application/zip"),
new ByteArrayInputStream(bytes));
return versioned(new S3Object("code", "app.zip", bytes, "application/zip"), bytes);
}
/** An object S3 reports as {@code size} bytes, whatever its body. */
private static S3Service.ObjectRead object(byte[] bytes, long size) {
return new S3Service.ObjectRead(new S3Object("code", "app.zip", size, "application/zip", "etag"),
new ByteArrayInputStream(bytes));
return versioned(new S3Object("code", "app.zip", size, "application/zip", "etag"), bytes);
}
private static S3Service.ObjectRead versioned(S3Object object, byte[] bytes) {
object.setVersionId("v1");
return new S3Service.ObjectRead(object, new ByteArrayInputStream(bytes));
}
private static S3Service.ObjectRead nullVersion(S3Service.ObjectRead read) {
read.object().setVersionId(null);
return read;
}
private static final class MemoryStorageFactory extends StorageFactory {