Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudformation): apply S3 Bucket CorsConfiguration (#1617)

Dixit R Jaina25aa0e59f7b
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index 4e4e065a5c..8bc0d37a89 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsNamespaces;
+import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
@@ -461,6 +463,7 @@ public class CloudFormationResourceProvisioner {
bucketName = generatePhysicalName(stackName, r.getLogicalId(), 63, true);
}
s3Service.createBucket(bucketName, region);
+ applyBucketCorsConfiguration(bucketName, props, engine);
r.setPhysicalId(bucketName);
r.getAttributes().put("Arn", AwsArnUtils.Arn.of("s3", "", "", bucketName).toString());
r.getAttributes().put("DomainName", bucketName + ".s3.amazonaws.com");
@@ -469,7 +472,57 @@ public class CloudFormationResourceProvisioner {
r.getAttributes().put("BucketName", bucketName);
}
- // ── SQS ───────────────────────────────────────────────────────────────────
+ /**
+ * Applies the optional {@code CorsConfiguration} property of {@code AWS::S3::Bucket} by translating
+ * the CloudFormation {@code CorsRules} list into the S3 CORS XML document the bucket stores and
+ * serves from its {@code ?cors} subresource.
+ *
+ * <p>This reconciles to the template on every provision (create and update): when the property is
+ * absent or has no rules, any existing CORS configuration is cleared so the bucket matches the
+ * template. Clearing is a harmless no-op on create since a freshly created bucket has none.
+ */
+ private void applyBucketCorsConfiguration(String bucketName, JsonNode props,
+ CloudFormationTemplateEngine engine) {
+ JsonNode corsRules = null;
+ if (props != null && props.has("CorsConfiguration") && !props.get("CorsConfiguration").isNull()) {
+ corsRules = props.get("CorsConfiguration").get("CorsRules");
+ }
+ if (corsRules == null || !corsRules.isArray() || corsRules.isEmpty()) {
+ s3Service.deleteBucketCors(bucketName);
+ return;
+ }
+ XmlBuilder xml = new XmlBuilder().start("CORSConfiguration", AwsNamespaces.S3);
+ for (JsonNode rule : corsRules) {
+ xml.start("CORSRule");
+ xml.elem("ID", resolveOptional(rule, "Id", engine));
+ appendCorsRuleElements(xml, rule.get("AllowedHeaders"), "AllowedHeader", engine);
+ appendCorsRuleElements(xml, rule.get("AllowedMethods"), "AllowedMethod", engine);
+ appendCorsRuleElements(xml, rule.get("AllowedOrigins"), "AllowedOrigin", engine);
+ appendCorsRuleElements(xml, rule.get("ExposedHeaders"), "ExposeHeader", engine);
+ String maxAge = resolveOptional(rule, "MaxAge", engine);
+ if (maxAge != null && !maxAge.isBlank()) {
+ xml.elem("MaxAgeSeconds", maxAge);
+ }
+ xml.end("CORSRule");
+ }
+ xml.end("CORSConfiguration");
+ s3Service.putBucketCors(bucketName, xml.build());
+ }
+
+ private void appendCorsRuleElements(XmlBuilder xml, JsonNode values, String elementName,
+ CloudFormationTemplateEngine engine) {
+ if (values == null || !values.isArray()) {
+ return;
+ }
+ for (JsonNode value : values) {
+ if (value != null && !value.isNull()) {
+ String resolved = engine.resolve(value);
+ if (resolved != null && !resolved.isBlank()) {
+ xml.elem(elementName, resolved);
+ }
+ }
+ }
+ }
private void provisionSqsQueue(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String region, String accountId, String stackName) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
index b50b3dbaf1..c167e336ab 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
@@ -172,6 +172,217 @@ class CloudFormationIntegrationTest {
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
}
+ @Test
+ void createStack_s3BucketWithCorsConfiguration() {
+ String template = """
+ {
+ "Resources": {
+ "MyBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {
+ "BucketName": "cfn-cors-test-bucket",
+ "CorsConfiguration": {
+ "CorsRules": [
+ {
+ "Id": "allow-app",
+ "AllowedHeaders": ["*"],
+ "AllowedMethods": ["GET", "PUT"],
+ "AllowedOrigins": ["https://app.example.com"],
+ "ExposedHeaders": ["x-amz-request-id"],
+ "MaxAge": 3000
+ }
+ ]
+ }
+ }
+ }
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", "cfn-cors-stack")
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackId>"));
+
+ // The bucket's ?cors subresource should reflect the CloudFormation CorsConfiguration.
+ given()
+ .when()
+ .get("/cfn-cors-test-bucket?cors")
+ .then()
+ .statusCode(200)
+ .body(containsString("<CORSRule>"))
+ .body(containsString("<ID>allow-app</ID>"))
+ .body(containsString("<AllowedMethod>GET</AllowedMethod>"))
+ .body(containsString("<AllowedMethod>PUT</AllowedMethod>"))
+ .body(containsString("<AllowedOrigin>https://app.example.com</AllowedOrigin>"))
+ .body(containsString("<AllowedHeader>*</AllowedHeader>"))
+ .body(containsString("<ExposeHeader>x-amz-request-id</ExposeHeader>"))
+ .body(containsString("<MaxAgeSeconds>3000</MaxAgeSeconds>"));
+ }
+
+ @Test
+ void createStack_s3BucketCorsConfigurationSkipsBlankListValues() {
+ String template = """
+ {
+ "Resources": {
+ "MyBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {
+ "BucketName": "cfn-cors-blank-bucket",
+ "CorsConfiguration": {
+ "CorsRules": [
+ {
+ "AllowedHeaders": ["x-real-header", ""],
+ "AllowedMethods": ["GET"],
+ "AllowedOrigins": ["https://app.example.com"]
+ }
+ ]
+ }
+ }
+ }
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", "cfn-cors-blank-stack")
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackId>"));
+
+ // A blank list entry must be skipped rather than emitted as an empty (invalid) element.
+ given()
+ .when()
+ .get("/cfn-cors-blank-bucket?cors")
+ .then()
+ .statusCode(200)
+ .body(containsString("<AllowedHeader>x-real-header</AllowedHeader>"))
+ .body(not(containsString("<AllowedHeader></AllowedHeader>")));
+ }
+
+ @Test
+ void updateStack_s3BucketCorsConfigurationIsReconciled() {
+ String stackName = "cfn-cors-update-stack";
+ String bucketName = "cfn-cors-update-bucket";
+ String withCors = """
+ {
+ "Resources": {
+ "MyBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {
+ "BucketName": "%s",
+ "CorsConfiguration": {
+ "CorsRules": [
+ {
+ "AllowedMethods": ["GET"],
+ "AllowedOrigins": ["https://old.example.com"]
+ }
+ ]
+ }
+ }
+ }
+ }
+ }
+ """.formatted(bucketName);
+ String changedCors = """
+ {
+ "Resources": {
+ "MyBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {
+ "BucketName": "%s",
+ "CorsConfiguration": {
+ "CorsRules": [
+ {
+ "AllowedMethods": ["POST"],
+ "AllowedOrigins": ["https://new.example.com"]
+ }
+ ]
+ }
+ }
+ }
+ }
+ }
+ """.formatted(bucketName);
+ String withoutCors = """
+ {
+ "Resources": {
+ "MyBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {
+ "BucketName": "%s"
+ }
+ }
+ }
+ }
+ """.formatted(bucketName);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", withCors)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/" + bucketName + "?cors")
+ .then()
+ .statusCode(200)
+ .body(containsString("<AllowedOrigin>https://old.example.com</AllowedOrigin>"));
+
+ // Update: rules change → CORS document is replaced, no stale rule left behind.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", changedCors)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/" + bucketName + "?cors")
+ .then()
+ .statusCode(200)
+ .body(containsString("<AllowedOrigin>https://new.example.com</AllowedOrigin>"))
+ .body(not(containsString("https://old.example.com")));
+
+ // Update: property dropped → CORS is cleared, ?cors returns NoSuchCORSConfiguration.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", withoutCors)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/" + bucketName + "?cors")
+ .then()
+ .statusCode(404)
+ .body(containsString("NoSuchCORSConfiguration"));
+ }
+
@Test
void createStack_lambdaWithS3Code() {
byte[] zipBytes = buildHandlerZip();