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 7efafb3e5c..5776d49340 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 @@ -61,34 +61,35 @@ public class CloudFormationResourceProvisioner { * Returns null and logs a warning for unsupported types. */ public StackResource provision(String logicalId, String resourceType, JsonNode properties, - CloudFormationTemplateEngine engine, String region, String accountId) { + CloudFormationTemplateEngine engine, String region, String accountId, + String stackName) { StackResource resource = new StackResource(); resource.setLogicalId(logicalId); resource.setResourceType(resourceType); try { switch (resourceType) { - case "AWS::S3::Bucket" -> provisionS3Bucket(resource, properties, engine, region, accountId); - case "AWS::SQS::Queue" -> provisionSqsQueue(resource, properties, engine, region, accountId); - case "AWS::SNS::Topic" -> provisionSnsTopic(resource, properties, engine, region, accountId); + case "AWS::S3::Bucket" -> provisionS3Bucket(resource, properties, engine, region, accountId, stackName); + case "AWS::SQS::Queue" -> provisionSqsQueue(resource, properties, engine, region, accountId, stackName); + case "AWS::SNS::Topic" -> provisionSnsTopic(resource, properties, engine, region, accountId, stackName); case "AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable" -> - provisionDynamoTable(resource, properties, engine, region, accountId); - case "AWS::Lambda::Function" -> provisionLambda(resource, properties, engine, region, accountId); - case "AWS::IAM::Role" -> provisionIamRole(resource, properties, engine, accountId); - case "AWS::IAM::User" -> provisionIamUser(resource, properties, engine); + provisionDynamoTable(resource, properties, engine, region, accountId, stackName); + case "AWS::Lambda::Function" -> provisionLambda(resource, properties, engine, region, accountId, stackName); + case "AWS::IAM::Role" -> provisionIamRole(resource, properties, engine, accountId, stackName); + case "AWS::IAM::User" -> provisionIamUser(resource, properties, engine, stackName); case "AWS::IAM::AccessKey" -> provisionIamAccessKey(resource, properties, engine); case "AWS::IAM::Policy", "AWS::IAM::ManagedPolicy" -> - provisionIamPolicy(resource, properties, engine, accountId); - case "AWS::IAM::InstanceProfile" -> provisionInstanceProfile(resource, properties, engine, accountId); - case "AWS::SSM::Parameter" -> provisionSsmParameter(resource, properties, engine, region); + provisionIamPolicy(resource, properties, engine, accountId, stackName); + case "AWS::IAM::InstanceProfile" -> provisionInstanceProfile(resource, properties, engine, accountId, stackName); + case "AWS::SSM::Parameter" -> provisionSsmParameter(resource, properties, engine, region, stackName); case "AWS::KMS::Key" -> provisionKmsKey(resource, properties, engine, region, accountId); case "AWS::KMS::Alias" -> provisionKmsAlias(resource, properties, engine, region); - case "AWS::SecretsManager::Secret" -> provisionSecret(resource, properties, engine, region, accountId); + case "AWS::SecretsManager::Secret" -> provisionSecret(resource, properties, engine, region, accountId, stackName); case "AWS::CloudFormation::Stack" -> provisionNestedStack(resource, properties, engine, region); case "AWS::CDK::Metadata" -> provisionCdkMetadata(resource); case "AWS::S3::BucketPolicy" -> provisionS3BucketPolicy(resource, properties, engine); case "AWS::SQS::QueuePolicy" -> provisionSqsQueuePolicy(resource, properties, engine); - case "AWS::ECR::Repository" -> provisionEcrRepository(resource, properties, engine); + case "AWS::ECR::Repository" -> provisionEcrRepository(resource, properties, engine, stackName); case "AWS::Route53::HostedZone" -> provisionRoute53HostedZone(resource, properties, engine); case "AWS::Route53::RecordSet" -> provisionRoute53RecordSet(resource, properties, engine); default -> { @@ -133,10 +134,10 @@ public class CloudFormationResourceProvisioner { // ── S3 ──────────────────────────────────────────────────────────────────── private void provisionS3Bucket(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region, String accountId) { + String region, String accountId, String stackName) { String bucketName = resolveOptional(props, "BucketName", engine); if (bucketName == null || bucketName.isBlank()) { - bucketName = "cfn-" + UUID.randomUUID().toString().substring(0, 12).toLowerCase(); + bucketName = generatePhysicalName(stackName, r.getLogicalId(), 63, true); } s3Service.createBucket(bucketName, region); r.setPhysicalId(bucketName); @@ -150,10 +151,10 @@ public class CloudFormationResourceProvisioner { // ── SQS ─────────────────────────────────────────────────────────────────── private void provisionSqsQueue(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region, String accountId) { + String region, String accountId, String stackName) { String queueName = resolveOptional(props, "QueueName", engine); if (queueName == null || queueName.isBlank()) { - queueName = "cfn-" + UUID.randomUUID().toString().substring(0, 12); + queueName = generatePhysicalName(stackName, r.getLogicalId(), 80, false); } Map attrs = new HashMap<>(); if (props != null && props.has("VisibilityTimeout")) { @@ -170,10 +171,10 @@ public class CloudFormationResourceProvisioner { // ── SNS ─────────────────────────────────────────────────────────────────── private void provisionSnsTopic(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region, String accountId) { + String region, String accountId, String stackName) { String topicName = resolveOptional(props, "TopicName", engine); if (topicName == null || topicName.isBlank()) { - topicName = "cfn-" + UUID.randomUUID().toString().substring(0, 12); + topicName = generatePhysicalName(stackName, r.getLogicalId(), 256, false); } var topic = snsService.createTopic(topicName, Map.of(), Map.of(), region); r.setPhysicalId(topic.getTopicArn()); @@ -184,10 +185,10 @@ public class CloudFormationResourceProvisioner { // ── DynamoDB ────────────────────────────────────────────────────────────── private void provisionDynamoTable(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region, String accountId) { + String region, String accountId, String stackName) { String tableName = resolveOptional(props, "TableName", engine); if (tableName == null || tableName.isBlank()) { - tableName = "cfn-" + UUID.randomUUID().toString().substring(0, 12); + tableName = generatePhysicalName(stackName, r.getLogicalId(), 255, false); } List keySchema = new ArrayList<>(); @@ -264,10 +265,10 @@ public class CloudFormationResourceProvisioner { // ── Lambda ──────────────────────────────────────────────────────────────── private void provisionLambda(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region, String accountId) { + String region, String accountId, String stackName) { String funcName = resolveOptional(props, "FunctionName", engine); if (funcName == null || funcName.isBlank()) { - funcName = "cfn-func-" + UUID.randomUUID().toString().substring(0, 8); + funcName = generatePhysicalName(stackName, r.getLogicalId(), 64, false); } Map req = new HashMap<>(); req.put("FunctionName", funcName); @@ -287,10 +288,10 @@ public class CloudFormationResourceProvisioner { // ── IAM Role ────────────────────────────────────────────────────────────── private void provisionIamRole(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String accountId) { + String accountId, String stackName) { String roleName = resolveOptional(props, "RoleName", engine); if (roleName == null || roleName.isBlank()) { - roleName = "cfn-role-" + UUID.randomUUID().toString().substring(0, 8); + roleName = generatePhysicalName(stackName, r.getLogicalId(), 64, false); } String assumeDoc = props != null && props.has("AssumeRolePolicyDocument") ? props.get("AssumeRolePolicyDocument").toString() @@ -328,10 +329,10 @@ public class CloudFormationResourceProvisioner { // ── IAM Policy ──────────────────────────────────────────────────────────── private void provisionIamPolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String accountId) { + String accountId, String stackName) { String policyName = resolveOptional(props, "PolicyName", engine); if (policyName == null || policyName.isBlank()) { - policyName = "cfn-policy-" + UUID.randomUUID().toString().substring(0, 8); + policyName = generatePhysicalName(stackName, r.getLogicalId(), 128, false); } String document = props != null && props.has("PolicyDocument") ? props.get("PolicyDocument").toString() @@ -353,17 +354,17 @@ public class CloudFormationResourceProvisioner { } private void provisionIamManagedPolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String accountId) { - provisionIamPolicy(r, props, engine, accountId); + String accountId, String stackName) { + provisionIamPolicy(r, props, engine, accountId, stackName); } // ── IAM Instance Profile ────────────────────────────────────────────────── private void provisionInstanceProfile(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String accountId) { + String accountId, String stackName) { String name = resolveOptional(props, "InstanceProfileName", engine); if (name == null || name.isBlank()) { - name = "cfn-profile-" + UUID.randomUUID().toString().substring(0, 8); + name = generatePhysicalName(stackName, r.getLogicalId(), 128, false); } try { var profile = iamService.createInstanceProfile(name, "/"); @@ -378,10 +379,10 @@ public class CloudFormationResourceProvisioner { // ── SSM Parameter ───────────────────────────────────────────────────────── private void provisionSsmParameter(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region) { + String region, String stackName) { String name = resolveOptional(props, "Name", engine); if (name == null || name.isBlank()) { - name = "/cfn/" + UUID.randomUUID().toString().substring(0, 12); + name = generatePhysicalName(stackName, r.getLogicalId(), 2048, false); } String value = resolveOptional(props, "Value", engine); if (value == null) { @@ -419,10 +420,10 @@ public class CloudFormationResourceProvisioner { // ── Secrets Manager ─────────────────────────────────────────────────────── private void provisionSecret(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region, String accountId) { + String region, String accountId, String stackName) { String name = resolveOptional(props, "Name", engine); if (name == null || name.isBlank()) { - name = "cfn-secret-" + UUID.randomUUID().toString().substring(0, 8); + name = generatePhysicalName(stackName, r.getLogicalId(), 512, false); } String value = resolveOptional(props, "SecretString", engine); if (value == null) { @@ -460,10 +461,11 @@ public class CloudFormationResourceProvisioner { r.setPhysicalId("queue-policy-" + UUID.randomUUID().toString().substring(0, 8)); } - private void provisionIamUser(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) { + private void provisionIamUser(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, + String stackName) { String userName = resolveOptional(props, "UserName", engine); if (userName == null || userName.isBlank()) { - userName = "cfn-user-" + UUID.randomUUID().toString().substring(0, 8); + userName = generatePhysicalName(stackName, r.getLogicalId(), 64, false); } var user = iamService.createUser(userName, "/"); r.setPhysicalId(userName); @@ -479,10 +481,11 @@ public class CloudFormationResourceProvisioner { } } - private void provisionEcrRepository(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) { + private void provisionEcrRepository(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, + String stackName) { String repoName = resolveOptional(props, "RepositoryName", engine); if (repoName == null || repoName.isBlank()) { - repoName = "cfn-repo-" + UUID.randomUUID().toString().substring(0, 8); + repoName = generatePhysicalName(stackName, r.getLogicalId(), 256, true); } r.setPhysicalId(repoName); r.getAttributes().put("Arn", "arn:aws:ecr:us-east-1:000000000000:repository/" + repoName); @@ -527,4 +530,20 @@ public class CloudFormationResourceProvisioner { LOG.debugv("Could not delete policy {0}: {1}", policyArn, e.getMessage()); } } + + /** + * Generate an AWS-like physical name: {stackName}-{logicalId}-{randomSuffix}. + * Mirrors the naming pattern AWS CloudFormation uses when no explicit name is provided. + */ + private String generatePhysicalName(String stackName, String logicalId, int maxLength, boolean lowercase) { + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + String name = stackName + "-" + logicalId + "-" + suffix; + if (lowercase) { + name = name.toLowerCase(); + } + if (maxLength > 0 && name.length() > maxLength) { + name = name.substring(0, maxLength); + } + return name; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index 4330cfc448..e72f93beaf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -240,7 +240,7 @@ public class CloudFormationService { addEvent(stack, logicalId, null, type, "CREATE_IN_PROGRESS", null); resource = provisioner.provision(logicalId, type, props.isMissingNode() ? null : props, - engine, region, config.defaultAccountId()); + engine, region, config.defaultAccountId(), stack.getStackName()); stack.getResources().put(logicalId, resource); physicalIds.put(logicalId, resource.getPhysicalId()); 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 de0374469b..e9145fd701 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 @@ -10,18 +10,22 @@ import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.matchesRegex; import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; @QuarkusTest class CloudFormationIntegrationTest { private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0"; + private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1"; @BeforeAll static void configureRestAssured() { RestAssured.config = RestAssured.config().encoderConfig( EncoderConfig.encoderConfig() - .encodeContentTypeAs(DYNAMODB_CONTENT_TYPE, ContentType.TEXT)); + .encodeContentTypeAs(DYNAMODB_CONTENT_TYPE, ContentType.TEXT) + .encodeContentTypeAs(SSM_CONTENT_TYPE, ContentType.TEXT)); } @Test @@ -292,4 +296,495 @@ class CloudFormationIntegrationTest { .statusCode(400) .body(containsString("ChangeSetNotFoundException")); } + + @Test + void createStack_autoGeneratedName_crossResourceRef() { + // DynamoDB table without explicit TableName → auto-generated name + // SSM Parameter uses !Ref to get the auto-generated table name as its Value + String template = """ + { + "Resources": { + "MyTable": { + "Type": "AWS::DynamoDB::Table", + "Properties": { + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"} + ], + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"} + ] + } + }, + "TableNameParam": { + "Type": "AWS::SSM::Parameter", + "Properties": { + "Name": "/app/auto-table-name", + "Type": "String", + "Value": {"Ref": "MyTable"} + } + } + } + } + """; + + // 1. Create Stack + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "auto-name-stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + // 2. Verify stack completed and the auto-generated table name follows the pattern + var describeResponse = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", "auto-name-stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("AWS::DynamoDB::Table")) + .body(containsString("auto-name-stack-MyTable-")) + .extract().asString(); + + // 3. Verify SSM Parameter was created with the auto-generated table name as value + given() + .header("X-Amz-Target", "AmazonSSM.GetParameter") + .contentType(SSM_CONTENT_TYPE) + .body(""" + {"Name": "/app/auto-table-name", "WithDecryption": true} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("Parameter.Name", equalTo("/app/auto-table-name")) + .body("Parameter.Value", startsWith("auto-name-stack-MyTable-")); + } + + @Test + void createStack_explicitNamesPreserved() { + // When explicit names are provided, CloudFormation uses them as-is. + // See: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-name.html + String template = """ + { + "Resources": { + "Bucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": "my-explicit-bucket-name" + } + }, + "Queue": { + "Type": "AWS::SQS::Queue", + "Properties": { + "QueueName": "MyExplicitQueueName" + } + }, + "Table": { + "Type": "AWS::DynamoDB::Table", + "Properties": { + "TableName": "MyExplicitTableName", + "AttributeDefinitions": [ + {"AttributeName": "id", "AttributeType": "S"} + ], + "KeySchema": [ + {"AttributeName": "id", "KeyType": "HASH"} + ] + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "explicit-names-stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + // Verify explicit names are used as-is in DescribeStackResources + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", "explicit-names-stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("my-explicit-bucket-name")) + .body(containsString("MyExplicitQueueName")) + .body(containsString("MyExplicitTableName")) + // Must NOT contain auto-generated pattern + .body(not(containsString("explicit-names-stack-Bucket-"))) + .body(not(containsString("explicit-names-stack-Queue-"))) + .body(not(containsString("explicit-names-stack-Table-"))); + } + + @Test + void createStack_s3AutoName_isLowercase() { + // S3 bucket names must be lowercase letters, numbers, periods, and hyphens (max 63 chars). + // See: https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html + String template = """ + { + "Resources": { + "MyUpperCaseBucket": { + "Type": "AWS::S3::Bucket", + "Properties": {} + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "S3LowerCase-Stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + // The auto-generated name should be all lowercase: s3lowercase-stack-myuppercasebucket-... + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", "S3LowerCase-Stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("s3lowercase-stack-myuppercasebucket-")) + // Must not contain uppercase variants + .body(not(containsString("S3LowerCase-Stack-MyUpperCaseBucket-"))); + } + + @Test + void createStack_sqsAutoName_preservesCase() { + // SQS queue names preserve case. AWS example: mystack-myqueue-1VF9BKQH5BJVI + // See: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-sqs-queue.html + String template = """ + { + "Resources": { + "MyMixedCaseQueue": { + "Type": "AWS::SQS::Queue", + "Properties": {} + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "CaseSensitive-Stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + // The SQS auto-generated name should preserve case: CaseSensitive-Stack-MyMixedCaseQueue-... + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", "CaseSensitive-Stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CaseSensitive-Stack-MyMixedCaseQueue-")); + } + + @Test + void createStack_multipleUnnamedResources_uniqueNames() { + // Multiple resources of same type without names get unique auto-generated names + String template = """ + { + "Resources": { + "TableA": { + "Type": "AWS::DynamoDB::Table", + "Properties": { + "AttributeDefinitions": [ + {"AttributeName": "id", "AttributeType": "S"} + ], + "KeySchema": [ + {"AttributeName": "id", "KeyType": "HASH"} + ] + } + }, + "TableB": { + "Type": "AWS::DynamoDB::Table", + "Properties": { + "AttributeDefinitions": [ + {"AttributeName": "id", "AttributeType": "S"} + ], + "KeySchema": [ + {"AttributeName": "id", "KeyType": "HASH"} + ] + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "multi-table-stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + // Both tables should have distinct names derived from their logical IDs + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", "multi-table-stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("multi-table-stack-TableA-")) + .body(containsString("multi-table-stack-TableB-")); + } + + @Test + void createStack_ssmAutoName_followsAwsPattern() { + // AWS SSM Parameter auto-name pattern: {stackName}-{logicalId}-{suffix} + // See: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ssm-parameter.html + String template = """ + { + "Resources": { + "MyParam": { + "Type": "AWS::SSM::Parameter", + "Properties": { + "Type": "String", + "Value": "test-value" + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "ssm-auto-stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + // SSM Parameter physical ID should follow {stackName}-{logicalId}-{suffix} pattern + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", "ssm-auto-stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("ssm-auto-stack-MyParam-")); + + // Verify SSM Parameter name via SSM API using DescribeStackResources physical ID + // We extract the auto-generated name from the stack resource and verify it's accessible + var ssmResourceXml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", "ssm-auto-stack") + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + + // Extract the auto-generated parameter name from the XML response + String paramName = ssmResourceXml + .split("")[1] + .split("")[0]; + + given() + .header("X-Amz-Target", "AmazonSSM.GetParameter") + .contentType(SSM_CONTENT_TYPE) + .body("{\"Name\": \"" + paramName + "\", \"WithDecryption\": true}") + .when() + .post("/") + .then() + .statusCode(200) + .body("Parameter.Value", equalTo("test-value")); + } + + @Test + void createStack_getAttOnAutoNamedResource() { + // Fn::GetAtt should work on auto-named resources (e.g. DynamoDB Arn) + String template = """ + { + "Resources": { + "AutoTable": { + "Type": "AWS::DynamoDB::Table", + "Properties": { + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"} + ], + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"} + ] + } + }, + "ArnParam": { + "Type": "AWS::SSM::Parameter", + "Properties": { + "Name": "/app/auto-table-arn", + "Type": "String", + "Value": {"Fn::GetAtt": ["AutoTable", "Arn"]} + } + } + }, + "Outputs": { + "TableArn": { + "Value": {"Fn::GetAtt": ["AutoTable", "Arn"]} + }, + "TableName": { + "Value": {"Ref": "AutoTable"} + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "getatt-stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + // Verify Outputs contain the auto-generated name and ARN + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "getatt-stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("TableArn")) + .body(containsString("TableName")) + .body(containsString("getatt-stack-AutoTable-")); + + // Verify SSM Parameter received the Arn via GetAtt + given() + .header("X-Amz-Target", "AmazonSSM.GetParameter") + .contentType(SSM_CONTENT_TYPE) + .body(""" + {"Name": "/app/auto-table-arn", "WithDecryption": true} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("Parameter.Value", startsWith("arn:aws:dynamodb:")); + } + + @Test + void createStack_snsAutoName_refReturnsArn() { + // SNS Ref returns TopicArn. AWS example: arn:aws:sns:us-east-1:123456789012:mystack-mytopic-NZJ5JSMVGFIE + // See: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-sns-topic.html + String template = """ + { + "Resources": { + "MyTopic": { + "Type": "AWS::SNS::Topic", + "Properties": {} + } + }, + "Outputs": { + "TopicRef": { + "Value": {"Ref": "MyTopic"} + }, + "TopicArn": { + "Value": {"Fn::GetAtt": ["MyTopic", "TopicName"]} + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "sns-auto-stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + // SNS Ref returns ARN (which contains the auto-generated topic name) + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "sns-auto-stack") + .when() + .post("/") + .then() + .statusCode(200) + // Ref returns ARN containing the auto-generated name + .body(containsString("arn:aws:sns:")) + .body(containsString("sns-auto-stack-MyTopic-")); + } + + @Test + void createStack_ecrAutoName_isLowercase() { + // ECR repository names must be lowercase. + // See: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ecr-repository.html + String template = """ + { + "Resources": { + "MyRepo": { + "Type": "AWS::ECR::Repository", + "Properties": {} + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "ECR-Upper-Stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + // ECR auto-name should be lowercase + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", "ECR-Upper-Stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("ecr-upper-stack-myrepo-")) + .body(not(containsString("ECR-Upper-Stack-MyRepo-"))); + } }