Skip to content

armgit / floci

Public Imported from GitHub
0

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

refactor(cloudformation): move AWS::S3::* into its own provisioner (#2754) (#2794)

Hector Ventura8034c13106a0
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 956e3f466f..54a80422c0 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
@@ -271,8 +271,6 @@ public class CloudFormationResourceProvisioner {
"AWS::RDS::DBSubnetGroup",
"AWS::Route53::HostedZone",
"AWS::Route53::RecordSet",
- "AWS::S3::Bucket",
- "AWS::S3::BucketPolicy",
"AWS::SNS::Subscription",
"AWS::SNS::Topic",
"AWS::SecretsManager::Secret",
@@ -425,7 +423,6 @@ public class CloudFormationResourceProvisioner {
return resource;
}
switch (resourceType) {
- case "AWS::S3::Bucket" -> provisionS3Bucket(resource, properties, engine, region, accountId, stackName);
case "AWS::SNS::Topic" -> provisionSnsTopic(resource, properties, engine, region, accountId, stackName);
case "AWS::SNS::Subscription" -> provisionSnsSubscription(resource, properties, engine, region);
case "AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable" ->
@@ -442,7 +439,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::SecretsManager::Secret" -> provisionSecret(resource, properties, engine, region, accountId, stackName);
case "AWS::SecretsManager::SecretTargetAttachment" ->
provisionSecretTargetAttachment(resource, properties, engine, region, stackName);
- case "AWS::S3::BucketPolicy" -> provisionS3BucketPolicy(resource, properties, engine);
case "AWS::Route53::HostedZone" -> provisionRoute53HostedZone(resource, properties, engine);
case "AWS::Route53::RecordSet" -> provisionRoute53RecordSet(resource, properties, engine);
case "AWS::Events::Rule" -> provisionEventBridgeRule(resource, properties, engine, region, stackName);
@@ -713,7 +709,6 @@ public class CloudFormationResourceProvisioner {
return;
}
switch (resourceType) {
- case "AWS::S3::Bucket" -> s3Service.deleteBucket(physicalId);
case "AWS::SNS::Topic" -> snsService.deleteTopic(physicalId, region);
case "AWS::SNS::Subscription" -> snsService.unsubscribe(physicalId, region);
case "AWS::DynamoDB::Table" -> deleteDynamoTableSafe(physicalId, region);
@@ -775,23 +770,6 @@ public class CloudFormationResourceProvisioner {
// ── S3 ────────────────────────────────────────────────────────────────────
- private void provisionS3Bucket(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region, String accountId, String stackName) {
- String bucketName = resolveOptional(props, "BucketName", engine);
- if (bucketName == null || bucketName.isBlank()) {
- bucketName = generatePhysicalName(stackName, r.getLogicalId(), 63, true);
- }
- s3Service.createBucket(bucketName, region);
- applyBucketCorsConfiguration(bucketName, props, engine);
- applyBucketVersioningConfiguration(bucketName, props, engine);
- r.setPhysicalId(bucketName);
- r.getAttributes().put("Arn", AwsArnUtils.Arn.of("s3", "", "", bucketName).toString());
- r.getAttributes().put("DomainName", bucketName + ".s3.amazonaws.com");
- r.getAttributes().put("RegionalDomainName", bucketName + ".s3." + region + ".amazonaws.com");
- r.getAttributes().put("WebsiteURL", "http://" + bucketName + ".s3-website." + region + ".amazonaws.com");
- r.getAttributes().put("BucketName", bucketName);
- }
-
/**
* 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
@@ -801,61 +779,6 @@ public class CloudFormationResourceProvisioner {
* 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 applyBucketVersioningConfiguration(String bucketName, JsonNode props,
- CloudFormationTemplateEngine engine) {
- if (props == null || !props.has("VersioningConfiguration")
- || props.get("VersioningConfiguration").isNull()) {
- return;
- }
- String status = resolveOptional(props.get("VersioningConfiguration"), "Status", engine);
- if (status != null && !status.isBlank()) {
- s3Service.putBucketVersioning(bucketName, status);
- }
- }
-
- 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);
- }
- }
- }
- }
-
// ── EC2 networking ─────────────────────────────────────────────────────────
// Each method delegates to Ec2Service so the resource really exists (describe-subnets,
@@ -5129,10 +5052,6 @@ public class CloudFormationResourceProvisioner {
// ── Helpers ───────────────────────────────────────────────────────────────
- private void provisionS3BucketPolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
- r.setPhysicalId("bucket-policy-" + UUID.randomUUID().toString().substring(0, 8));
- }
-
private void provisionIamUser(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String stackName) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java
new file mode 100644
index 0000000000..3fbb59c201
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java
@@ -0,0 +1,128 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+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.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.s3.S3Service;
+import jakarta.enterprise.context.ApplicationScoped;
+
+import java.util.Set;
+import java.util.UUID;
+
+/**
+ * Provisions {@code AWS::S3::Bucket} and {@code AWS::S3::BucketPolicy}.
+ *
+ * <p>The bucket policy is accepted and given a physical id but not enforced: Floci does not
+ * evaluate S3 policies, and failing the resource would break every template that attaches one.
+ */
+@ApplicationScoped
+public class S3CfnProvisioner implements CfnResourceProvisioner {
+
+ private static final String BUCKET = "AWS::S3::Bucket";
+ private static final String BUCKET_POLICY = "AWS::S3::BucketPolicy";
+ private static final int BUCKET_NAME_MAX_LENGTH = 63;
+
+ private final S3Service s3Service;
+
+ public S3CfnProvisioner(S3Service s3Service) {
+ this.s3Service = s3Service;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(BUCKET, BUCKET_POLICY);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ switch (r.getResourceType()) {
+ case BUCKET -> provisionBucket(r, props, ctx);
+ case BUCKET_POLICY ->
+ r.setPhysicalId("bucket-policy-" + UUID.randomUUID().toString().substring(0, 8));
+ default -> throw new IllegalStateException(
+ "S3CfnProvisioner cannot provision " + r.getResourceType());
+ }
+ }
+
+ private void provisionBucket(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String bucketName = ctx.resolveOptional(props, "BucketName");
+ if (bucketName == null || bucketName.isBlank()) {
+ bucketName = ctx.generatePhysicalName(r.getLogicalId(), BUCKET_NAME_MAX_LENGTH, true);
+ }
+ s3Service.createBucket(bucketName, ctx.region());
+ applyBucketCorsConfiguration(bucketName, props, ctx);
+ applyBucketVersioningConfiguration(bucketName, props, ctx);
+ r.setPhysicalId(bucketName);
+ r.getAttributes().put("Arn", AwsArnUtils.Arn.of("s3", "", "", bucketName).toString());
+ r.getAttributes().put("DomainName", bucketName + ".s3.amazonaws.com");
+ r.getAttributes().put("RegionalDomainName", bucketName + ".s3." + ctx.region() + ".amazonaws.com");
+ r.getAttributes().put("WebsiteURL",
+ "http://" + bucketName + ".s3-website." + ctx.region() + ".amazonaws.com");
+ r.getAttributes().put("BucketName", bucketName);
+ }
+
+ private void applyBucketCorsConfiguration(String bucketName, JsonNode props, ProvisionContext ctx) {
+ 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", ctx.resolveOptional(rule, "Id"));
+ appendCorsRuleElements(xml, rule.get("AllowedHeaders"), "AllowedHeader", ctx);
+ appendCorsRuleElements(xml, rule.get("AllowedMethods"), "AllowedMethod", ctx);
+ appendCorsRuleElements(xml, rule.get("AllowedOrigins"), "AllowedOrigin", ctx);
+ appendCorsRuleElements(xml, rule.get("ExposedHeaders"), "ExposeHeader", ctx);
+ String maxAge = ctx.resolveOptional(rule, "MaxAge");
+ 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,
+ ProvisionContext ctx) {
+ if (values == null || !values.isArray()) {
+ return;
+ }
+ for (JsonNode value : values) {
+ if (value != null && !value.isNull()) {
+ String resolved = ctx.engine().resolve(value);
+ if (resolved != null && !resolved.isBlank()) {
+ xml.elem(elementName, resolved);
+ }
+ }
+ }
+ }
+
+ private void applyBucketVersioningConfiguration(String bucketName, JsonNode props,
+ ProvisionContext ctx) {
+ if (props == null || !props.has("VersioningConfiguration")
+ || props.get("VersioningConfiguration").isNull()) {
+ return;
+ }
+ String status = ctx.resolveOptional(props.get("VersioningConfiguration"), "Status");
+ if (status != null && !status.isBlank()) {
+ s3Service.putBucketVersioning(bucketName, status);
+ }
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ // A bucket policy has no backing resource to remove. Deleting a non-empty bucket raises
+ // BucketNotEmpty, which propagates so the stack reports DELETE_FAILED as AWS does.
+ if (BUCKET.equals(resourceType)) {
+ s3Service.deleteBucket(physicalId);
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java
new file mode 100644
index 0000000000..625fce9e3f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java
@@ -0,0 +1,184 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.s3.S3Service;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** {@code AWS::S3::Bucket} and {@code AWS::S3::BucketPolicy}. */
+class S3CfnProvisionerTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String REGION = "us-east-1";
+
+ private S3Service s3;
+ private S3CfnProvisioner provisioner;
+ private ProvisionContext ctx;
+
+ @BeforeEach
+ void setUp() {
+ s3 = mock(S3Service.class);
+ provisioner = new S3CfnProvisioner(s3);
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(i -> {
+ JsonNode node = i.getArgument(0);
+ return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0));
+ ctx = new ProvisionContext(engine, REGION, "000000000000", "my-stack");
+ }
+
+ private static JsonNode props(String json) {
+ try {
+ return MAPPER.readTree(json);
+ } catch (Exception e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+
+ private static StackResource resource(String logicalId, String type) {
+ StackResource r = new StackResource();
+ r.setLogicalId(logicalId);
+ r.setResourceType(type);
+ return r;
+ }
+
+ private StackResource provisionBucket(String json) {
+ StackResource r = resource("Bucket", "AWS::S3::Bucket");
+ provisioner.provision(r, props(json), ctx);
+ return r;
+ }
+
+ @Test
+ void refIsTheBucketNameAndGetAttExposesTheDocumentedAttributes() {
+ StackResource r = provisionBucket("""
+ {"BucketName": "my-bucket"}
+ """);
+
+ verify(s3).createBucket("my-bucket", REGION);
+ assertEquals("my-bucket", r.getPhysicalId(), "Ref is the bucket name");
+ // aws-s3-bucket.json readOnlyProperties, minus DualStackDomainName (see the PR follow-up),
+ // plus BucketName which the template engine resolves for Fn::GetAtt.
+ assertEquals(Map.of(
+ "Arn", "arn:aws:s3:::my-bucket",
+ "DomainName", "my-bucket.s3.amazonaws.com",
+ "RegionalDomainName", "my-bucket.s3.us-east-1.amazonaws.com",
+ "WebsiteURL", "http://my-bucket.s3-website.us-east-1.amazonaws.com",
+ "BucketName", "my-bucket"), r.getAttributes());
+ }
+
+ @Test
+ void anUnnamedBucketGetsALowerCasedStackScopedName() {
+ StackResource r = provisionBucket("{}");
+
+ String name = r.getPhysicalId();
+ assertTrue(name.startsWith("my-stack-bucket-"), name);
+ assertEquals(name.toLowerCase(), name, "S3 bucket names must be lower case");
+ assertTrue(name.length() <= 63, "bucket names cap at 63 characters: " + name);
+ }
+
+ /**
+ * A bucket with no CORS block has its configuration cleared rather than left alone, so an
+ * update that removes CorsConfiguration actually removes it from the bucket.
+ */
+ @Test
+ void absentCorsConfigurationClearsAnyExistingRules() {
+ provisionBucket("""
+ {"BucketName": "b"}
+ """);
+
+ verify(s3).deleteBucketCors("b");
+ verify(s3, never()).putBucketCors(anyString(), anyString());
+ }
+
+ @Test
+ void corsRulesBecomeS3CorsConfigurationXml() {
+ ArgumentCaptor<String> xml = ArgumentCaptor.forClass(String.class);
+
+ provisionBucket("""
+ {
+ "BucketName": "b",
+ "CorsConfiguration": {
+ "CorsRules": [
+ {
+ "Id": "rule-1",
+ "AllowedHeaders": ["*"],
+ "AllowedMethods": ["GET", "PUT"],
+ "AllowedOrigins": ["https://example.com"],
+ "ExposedHeaders": ["ETag"],
+ "MaxAge": "3600"
+ }
+ ]
+ }
+ }
+ """);
+
+ verify(s3).putBucketCors(anyString(), xml.capture());
+ String body = xml.getValue();
+ assertTrue(body.contains("<ID>rule-1</ID>"), body);
+ assertTrue(body.contains("<AllowedMethod>GET</AllowedMethod>"), body);
+ assertTrue(body.contains("<AllowedMethod>PUT</AllowedMethod>"), body);
+ assertTrue(body.contains("<AllowedOrigin>https://example.com</AllowedOrigin>"), body);
+ // The CFN property is ExposedHeaders but the S3 XML element is ExposeHeader.
+ assertTrue(body.contains("<ExposeHeader>ETag</ExposeHeader>"), body);
+ assertTrue(body.contains("<MaxAgeSeconds>3600</MaxAgeSeconds>"), body);
+ }
+
+ @Test
+ void anEmptyCorsRuleListIsTreatedAsNoCors() {
+ provisionBucket("""
+ {"BucketName": "b", "CorsConfiguration": {"CorsRules": []}}
+ """);
+
+ verify(s3).deleteBucketCors("b");
+ verify(s3, never()).putBucketCors(anyString(), anyString());
+ }
+
+ @Test
+ void versioningIsAppliedOnlyWhenAStatusIsGiven() {
+ provisionBucket("""
+ {"BucketName": "b", "VersioningConfiguration": {"Status": "Enabled"}}
+ """);
+ verify(s3).putBucketVersioning("b", "Enabled");
+
+ provisionBucket("""
+ {"BucketName": "c"}
+ """);
+ verify(s3, never()).putBucketVersioning("c", null);
+ }
+
+ @Test
+ void bucketPolicyIsAcceptedWithAPhysicalIdAndNoAttributes() {
+ StackResource r = resource("Policy", "AWS::S3::BucketPolicy");
+ provisioner.provision(r, props("""
+ {"Bucket": "b", "PolicyDocument": {"Version": "2012-10-17"}}
+ """), ctx);
+
+ assertTrue(r.getPhysicalId().startsWith("bucket-policy-"), r.getPhysicalId());
+ assertTrue(r.getAttributes().isEmpty());
+ }
+
+ @Test
+ void deletingABucketReachesTheServiceButAPolicyHasNothingToDelete() {
+ provisioner.delete("AWS::S3::Bucket", "b", REGION);
+ verify(s3).deleteBucket("b");
+
+ provisioner.delete("AWS::S3::BucketPolicy", "bucket-policy-abc", REGION);
+ verify(s3, never()).deleteBucket("bucket-policy-abc");
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index c75d1dcae5..6fb79a61af 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -98,8 +98,8 @@ AWS::RDS::DBProxyTargetGroup LEGACY_SWITCH
AWS::RDS::DBSubnetGroup LEGACY_SWITCH
AWS::Route53::HostedZone LEGACY_SWITCH
AWS::Route53::RecordSet LEGACY_SWITCH
-AWS::S3::Bucket LEGACY_SWITCH
-AWS::S3::BucketPolicy LEGACY_SWITCH
+AWS::S3::Bucket S3CfnProvisioner
+AWS::S3::BucketPolicy S3CfnProvisioner
AWS::SNS::Subscription LEGACY_SWITCH
AWS::SNS::Topic LEGACY_SWITCH
AWS::SQS::Queue SqsCfnProvisioner