diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/S3CfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/S3CfnProvisioner.java index bcea87e336..6c024b54ba 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/S3CfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/S3CfnProvisioner.java @@ -24,6 +24,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.regex.Pattern; /** * Provisions {@code AWS::S3::Bucket} and {@code AWS::S3::BucketPolicy}. @@ -33,7 +34,8 @@ import java.util.Set; * are validated here before the service stores their XML. A property the template does not declare is left alone, except that * an update removing {@code NotificationConfiguration} or {@code OwnershipControls} clears it. * - *

Covered on {@code AWS::S3::Bucket}: {@code BucketName}, {@code CorsConfiguration}, + *

Covered on {@code AWS::S3::Bucket}: {@code BucketName}, {@code BucketNamePrefix} in the + * {@code account-regional} {@code BucketNamespace}, {@code CorsConfiguration}, * {@code VersioningConfiguration}, {@code PublicAccessBlockConfiguration}, * {@code BucketEncryption}, {@code LifecycleConfiguration}, * {@code OwnershipControls}, {@code NotificationConfiguration} and @@ -60,6 +62,8 @@ 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 static final String ACCOUNT_REGIONAL_NAMESPACE = "account-regional"; + private static final Pattern BUCKET_NAME_PREFIX_CHARS = Pattern.compile("[a-z0-9][a-z0-9.-]*"); private final S3Service s3Service; @@ -88,14 +92,51 @@ public class S3CfnProvisioner implements CfnResourceProvisioner { } } + /** + * The name the template fixes: {@code BucketName}, or {@code BucketNamePrefix} expanded in the + * account regional namespace to {@code ---an}. Null when it fixes none. + */ + private static String templateBucketName(JsonNode props, ProvisionContext ctx) { + String name = ctx.resolveOptional(props, "BucketName"); + String prefix = ctx.resolveOptional(props, "BucketNamePrefix"); + if (prefix == null || prefix.isBlank()) { + return name; + } + if (name != null && !name.isBlank()) { + throw new AwsException("ValidationError", + BUCKET + " cannot set both BucketName and BucketNamePrefix", 400); + } + if (!ACCOUNT_REGIONAL_NAMESPACE.equals(ctx.resolveOptional(props, "BucketNamespace"))) { + throw new AwsException("ValidationError", + BUCKET + " BucketNamePrefix requires BucketNamespace " + ACCOUNT_REGIONAL_NAMESPACE, 400); + } + // AWS: "The name can only consist of lowercase letters, numbers, periods (.), and hyphens (-). + // Bucket names must begin and end with a letter or number and cannot contain two adjacent periods." + if (!BUCKET_NAME_PREFIX_CHARS.matcher(prefix).matches() || prefix.contains("..")) { + throw new AwsException("ValidationError", BUCKET + " BucketNamePrefix " + prefix + + " must use only lowercase letters, numbers, periods and hyphens, start with a letter" + + " or number and not contain two adjacent periods", 400); + } + String derived = prefix + "-" + ctx.accountId() + "-" + ctx.region() + "-an"; + if (derived.length() > BUCKET_NAME_MAX_LENGTH) { + throw new AwsException("ValidationError", BUCKET + " BucketNamePrefix " + prefix + " makes the name " + + derived + ", longer than " + BUCKET_NAME_MAX_LENGTH + " characters", 400); + } + return derived; + } + private void provisionBucket(StackResource r, JsonNode props, ProvisionContext ctx) { Map attributesBefore = Map.copyOf(r.getAttributes()); - String explicitName = ctx.resolveOptional(props, "BucketName"); // The engine's change decides, as it does for the change set's Replacement: BucketName, // BucketNamePrefix and BucketNamespace are create-only in the registry. A bucket named in the // template cannot be replaced under that name; an unnamed one gets a fresh generated name. - boolean replaces = ctx.isUpdate() && ctx.priorPhysicalId() != null - && ctx.changes(BUCKET, props).requiresReplacement(); + boolean updatesExisting = ctx.isUpdate() && ctx.priorPhysicalId() != null; + boolean replaces = updatesExisting && ctx.changes(BUCKET, props).requiresReplacement(); + // An update that keeps the bucket does not decide its name, so a prefix it carries is not + // derived or refused: one created before the prefix was read has a generated name. + String explicitName = updatesExisting && !replaces + ? ctx.resolveOptional(props, "BucketName") + : templateBucketName(props, ctx); if (replaces && explicitName != null && explicitName.equals(ctx.priorPhysicalId())) { throw CfnExceptions.customNamedReplacement(explicitName); } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationS3BucketReplacementIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationS3BucketReplacementIntegrationTest.java index 0bcc4d586e..ff78a07665 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationS3BucketReplacementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationS3BucketReplacementIntegrationTest.java @@ -1,11 +1,19 @@ package io.floci.aws.services.cloudformation; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.CfnStackWaits; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static io.floci.aws.services.cloudformation.CfnStackTestSupport.createUpdateChangeSet; +import static io.floci.aws.services.cloudformation.CfnStackTestSupport.executeAndAwaitUpdate; +import static io.floci.aws.services.cloudformation.CfnStackTestSupport.replacement; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -154,6 +162,69 @@ class CloudFormationS3BucketReplacementIntegrationTest { deleteStack(stackName); } + /** + * In the account regional namespace the bucket is named {@code ---an} + * and that name is its physical id and {@code Ref}; changing the prefix replaces the bucket and + * deletes the one under the old derived name once the update commits. + */ + @Test + void anAccountRegionalPrefixNamesTheBucketAndChangingItReplacesTheBucket() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "s3-nsp-" + suffix; + String oldBucket = "nsp-a-" + suffix + "-000000000000-us-east-1-an"; + String newBucket = "nsp-b-" + suffix + "-000000000000-us-east-1-an"; + + createStack(stackName, prefixTemplate("\"BucketNamePrefix\": \"nsp-a-" + suffix + "\", " + + "\"BucketNamespace\": \"account-regional\"")); + assertEquals(oldBucket, output(describeStack(stackName), "BucketRef")); + assertBucketPresent(oldBucket); + + try (CloudFormationClient client = AwsTestClients.create( + CloudFormationClient.builder(), "test", Region.US_EAST_1)) { + createUpdateChangeSet(client, stackName, "prefix", prefixTemplate("\"BucketNamePrefix\": \"nsp-b-" + + suffix + "\", \"BucketNamespace\": \"account-regional\"")); + assertEquals(List.of("True"), replacement(client, stackName, "prefix", "Bucket")); + executeAndAwaitUpdate(client, stackName, "prefix"); + } + + assertEquals(newBucket, output(describeStack(stackName), "BucketRef")); + assertBucketPresent(newBucket); + assertBucketMissing(oldBucket); + + deleteStack(stackName); + } + + /** + * A prefix together with {@code BucketName}, a prefix without the account regional namespace + * and a prefix with an uppercase letter are all rejected: the resource fails and the stack + * rolls back. S3 names "can only consist of lowercase letters, numbers, periods (.), and + * hyphens (-)". + */ + @Test + void aPrefixWithABucketNameOrOutsideTheAccountRegionalNamespaceFailsTheCreate() { + String suffix = Long.toString(System.nanoTime(), 36); + List invalid = List.of( + "\"BucketName\": \"nsp-both-" + suffix + "\", \"BucketNamePrefix\": \"nsp-both\", " + + "\"BucketNamespace\": \"account-regional\"", + "\"BucketNamePrefix\": \"nsp-global-" + suffix + "\"", + "\"BucketNamePrefix\": \"Repl-Upper\", \"BucketNamespace\": \"account-regional\""); + for (int i = 0; i < invalid.size(); i++) { + String stackName = "s3-nsp-bad-" + i + "-" + suffix; + sendCreateStack(stackName, prefixTemplate(invalid.get(i))); + CfnStackWaits.awaitStatus(stackName, "ROLLBACK_COMPLETE"); + deleteStack(stackName); + } + } + + private static String prefixTemplate(String properties) { + return """ + { + "Resources": { "Bucket": { "Type": "AWS::S3::Bucket", "Properties": { %s } } }, + "Outputs": { "BucketRef": { "Value": { "Ref": "Bucket" } } } + } + """.formatted(properties); + } + private static String inPlaceTemplate(String bucketName, String versioningStatus, String extraResources) { return """ { @@ -182,11 +253,15 @@ class CloudFormationS3BucketReplacementIntegrationTest { } private static void createStack(String stackName, String body) { + sendCreateStack(stackName, body); + await(stackName, "CREATE_COMPLETE"); + } + + private static void sendCreateStack(String stackName, String body) { given().contentType("application/x-www-form-urlencoded") .formParam("Action", "CreateStack").formParam("Version", "2010-05-15") .formParam("StackName", stackName).formParam("TemplateBody", body) .when().post("/").then().statusCode(200); - await(stackName, "CREATE_COMPLETE"); } private static void updateStack(String stackName, String body) { diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index 1e87197253..c7d203c80a 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -622,8 +622,6 @@ AWS::S3::Bucket AbacStatus accepted and ignored AWS::S3::Bucket AccelerateConfiguration silently dropped, as the S3CfnProvisioner javadoc records AWS::S3::Bucket AccessControl silently dropped, as the S3CfnProvisioner javadoc records AWS::S3::Bucket AnalyticsConfigurations silently dropped, as the S3CfnProvisioner javadoc records -AWS::S3::Bucket BucketNamePrefix accepted and ignored -AWS::S3::Bucket BucketNamespace accepted and ignored AWS::S3::Bucket IntelligentTieringConfigurations silently dropped, as the S3CfnProvisioner javadoc records AWS::S3::Bucket InventoryConfigurations silently dropped, as the S3CfnProvisioner javadoc records AWS::S3::Bucket LoggingConfiguration silently dropped, as the S3CfnProvisioner javadoc records