fix(cloudformation): name an S3 bucket from BucketNamePrefix in the account regional namespace (#8467)

This commit is contained in:
Oleksandr Nikolaichuk authored and GitHub committed 2026-11-15 11:51:08 -04:00
1 parent 696eeda8e0
commit e3f18da59e
3 files changed
+121 -7

No files matched your search

@@ -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.
*
* <p>Covered on {@code AWS::S3::Bucket}: {@code BucketName}, {@code CorsConfiguration},
* <p>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 <prefix>-<accountId>-<region>-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<String, String> 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);
}
@@ -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 <prefix>-<account>-<region>-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<String> 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) {
@@ -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
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
622 AWS::S3::Bucket AccelerateConfiguration silently dropped, as the S3CfnProvisioner javadoc records
623 AWS::S3::Bucket AccessControl silently dropped, as the S3CfnProvisioner javadoc records
624 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
625 AWS::S3::Bucket IntelligentTieringConfigurations silently dropped, as the S3CfnProvisioner javadoc records
626 AWS::S3::Bucket InventoryConfigurations silently dropped, as the S3CfnProvisioner javadoc records
627 AWS::S3::Bucket LoggingConfiguration silently dropped, as the S3CfnProvisioner javadoc records