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 81b6eeb54f..096030f49e 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 @@ -119,8 +119,9 @@ public class CloudFormationResourceProvisioner { private static final String INLINE_CLEANUP_ROLE_TARGETS_ATTR = "__FlociInlineCleanupRoleTargets"; private static final String INLINE_CLEANUP_USER_TARGETS_ATTR = "__FlociInlineCleanupUserTargets"; private static final String INLINE_CLEANUP_GROUP_TARGETS_ATTR = "__FlociInlineCleanupGroupTargets"; - private static final String LAMBDA_NAME_MODE_EXPLICIT = "explicit"; - private static final String LAMBDA_NAME_MODE_GENERATED = "generated"; + private static final String NAME_MODE_EXPLICIT = "explicit"; + private static final String NAME_MODE_GENERATED = "generated"; + private static final String LOG_GROUP_NAME_MODE_ATTR = "FlociLogGroupNameMode"; private static final String SECRET_TARGET_MANAGED_KEYS_ATTR = "__FlociSecretTargetManagedKeys"; private static final String SECRET_TARGET_OWNER_ATTR = "__FlociSecretTargetOwner"; private static final List SECRET_TARGET_CONNECTION_KEYS = List.of( @@ -707,8 +708,32 @@ public class CloudFormationResourceProvisioner { private void provisionLogGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, String region, String accountId, String stackName) { - String name = resolveOptional(props, "LogGroupName", engine); - if (name == null || name.isBlank()) { + String explicitName = resolveOptional(props, "LogGroupName", engine); + boolean hasExplicitName = explicitName != null && !explicitName.isBlank(); + String previousNameMode = r.getAttributes().get(LOG_GROUP_NAME_MODE_ATTR); + if (previousNameMode == null && r.getPhysicalId() != null) { + // Stacks persisted before FlociLogGroupNameMode existed have no recorded mode, but an + // auto-generated name always has the deterministic --<12 hex chars> + // shape generatePhysicalName produces, so anything else must have been explicit. + previousNameMode = isGeneratedLogGroupName(r.getPhysicalId(), stackName, r.getLogicalId()) + ? NAME_MODE_GENERATED + : NAME_MODE_EXPLICIT; + } + // Going from an explicit name to none is itself a replacement-worthy change on real AWS, not + // something to silently keep reconciling under the old explicit name (mirrors the same check + // for Lambda's FunctionName above). + boolean explicitNameRemoved = r.getPhysicalId() != null && !hasExplicitName + && NAME_MODE_EXPLICIT.equals(previousNameMode); + + String name; + if (hasExplicitName) { + name = explicitName; + } else if (r.getPhysicalId() != null && !explicitNameRemoved) { + // No explicit name and the prior name was itself auto-generated: keep it across updates + // instead of generating a fresh random one each time, so the log group is reconciled in + // place rather than replaced on every no-op update. + name = r.getPhysicalId(); + } else { name = generatePhysicalName(stackName, r.getLogicalId(), 512, false); } Integer retentionInDays = null; @@ -729,11 +754,74 @@ public class CloudFormationResourceProvisioner { } } } - logsService.createLogGroup(name, retentionInDays, tags, region); + + // LogGroupName isn't updatable in place on real AWS (a change replaces the resource), so only + // reconcile in place when the name is unchanged and the group is still there; otherwise this is + // either a first create or a rename, both of which need a fresh createLogGroup call. On a rename, + // create the new group before deleting the old one: if the new name collides with something else + // and createLogGroup throws, the update rolls back without touching the old group, since rollback + // does not restore a resource this method already deleted. + String priorPhysicalId = r.getPhysicalId(); + if (priorPhysicalId != null && priorPhysicalId.equals(name) && logsService.logGroupExists(name, region)) { + reconcileLogGroup(name, retentionInDays, tags, region); + } else { + logsService.createLogGroup(name, retentionInDays, tags, region); + if (priorPhysicalId != null && !priorPhysicalId.equals(name) + && logsService.logGroupExists(priorPhysicalId, region)) { + logsService.deleteLogGroup(priorPhysicalId, region); + } + } + // Ref returns the log group name; GetAtt Arn is arn:aws:logs:::log-group::* r.setPhysicalId(name); r.getAttributes().put("Arn", AwsArnUtils.Arn.of("logs", region, accountId, "log-group:" + name + ":*").toString()); + r.getAttributes().put(LOG_GROUP_NAME_MODE_ATTR, + hasExplicitName ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED); + } + + /** + * Whether {@code physicalId} matches the exact shape {@link #generatePhysicalName} produces for + * this stack/logical id: {@code --} followed by exactly 12 lowercase hex + * characters. Doesn't account for the (practically unreachable at a 512-character limit) + * truncation path in {@link #generatePhysicalName}, so a truncated legacy name is conservatively + * treated as explicit rather than misdetected as generated. + */ + private boolean isGeneratedLogGroupName(String physicalId, String stackName, String logicalId) { + String prefix = stackName + "-" + logicalId + "-"; + if (!physicalId.startsWith(prefix)) { + return false; + } + String suffix = physicalId.substring(prefix.length()); + if (suffix.length() != 12) { + return false; + } + for (int i = 0; i < suffix.length(); i++) { + char c = suffix.charAt(i); + boolean hex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + if (!hex) { + return false; + } + } + return true; + } + + private void reconcileLogGroup(String name, Integer retentionInDays, Map tags, String region) { + if (retentionInDays != null) { + logsService.putRetentionPolicy(name, retentionInDays, region); + } else { + logsService.deleteRetentionPolicy(name, region); + } + Map existingTags = logsService.listTagsLogGroup(name, region); + List tagsToRemove = existingTags.keySet().stream() + .filter(key -> !tags.containsKey(key)) + .toList(); + if (!tagsToRemove.isEmpty()) { + logsService.untagLogGroup(name, tagsToRemove, region); + } + if (!tags.isEmpty()) { + logsService.tagLogGroup(name, tags, region); + } } // ── Kinesis ───────────────────────────────────────────────────────────────── @@ -1418,7 +1506,7 @@ public class CloudFormationResourceProvisioner { r.getAttributes().put("Arn", func.getFunctionArn()); r.getAttributes().put(LAMBDA_CODE_IDENTITY_ATTR, desired.code().identity()); r.getAttributes().put(LAMBDA_NAME_MODE_ATTR, - desired.explicitFunctionName() ? LAMBDA_NAME_MODE_EXPLICIT : LAMBDA_NAME_MODE_GENERATED); + desired.explicitFunctionName() ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED); r.getAttributes().put(LAMBDA_PACKAGE_TYPE_ATTR, desired.packageType()); } @@ -1436,7 +1524,7 @@ public class CloudFormationResourceProvisioner { && !Objects.equals(oldPackageType, packageType); boolean explicitRemoved = r.getPhysicalId() != null && !hasExplicitName - && LAMBDA_NAME_MODE_EXPLICIT.equals(previousNameMode); + && NAME_MODE_EXPLICIT.equals(previousNameMode); String functionName; if (hasExplicitName) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java index 3a7dda7f54..8416fc0be2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java @@ -167,6 +167,10 @@ public class CloudWatchLogsService { LOG.infov("Deleted log group: {0}", name); } + public boolean logGroupExists(String name, String region) { + return groupStore.get(groupKey(region, name)).isPresent(); + } + public List describeLogGroups(String prefix, String region) { String storagePrefix = groupKeyPrefix(region); List result = groupStore.scan(k -> { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java new file mode 100644 index 0000000000..81f769a7a4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java @@ -0,0 +1,108 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry; +import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Regression for the "Persisted Name Mode Is Lost" review finding on #1965: a log group persisted + * by a floci version before FlociLogGroupNameMode existed has no recorded mode, so the fix must + * infer explicit vs. generated from the physical id's shape rather than default to one or the other. + */ +class CloudFormationLogGroupProvisionerTest { + + private static final String ACCOUNT_ID = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String STACK_NAME = "test-stack"; + + private final ObjectMapper mapper = new ObjectMapper(); + private CloudWatchLogsService logsService; + private CloudFormationResourceProvisioner provisioner; + + @BeforeEach + void setUp() { + logsService = mock(CloudWatchLogsService.class); + provisioner = new CloudFormationResourceProvisioner( + null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, + mapper, + null, null, null, null, null, null, null, + null, null, logsService, null, null, null, null, + null, + new CloudFormationResourceRegistry(List.of())); + } + + @Test + void legacyExplicitNameWithNoRecordedMode_replacesWhenNameIsRemoved() { + // Simulates a log group created before FlociLogGroupNameMode was tracked: no attributes at + // all, and a physical id that does not match generatePhysicalName's shape, so it must have + // been an explicit LogGroupName the caller chose. + String legacyExplicitName = "my-hand-chosen-log-group"; + when(logsService.logGroupExists(legacyExplicitName, REGION)).thenReturn(true); + + StackResource result = provision("{}", legacyExplicitName, Map.of()); + + assertEquals("CREATE_COMPLETE", result.getStatus()); + assertNotEquals(legacyExplicitName, result.getPhysicalId()); + assertTrue(result.getPhysicalId().startsWith(STACK_NAME + "-LogGroup-"), + "expected a freshly generated name, got: " + result.getPhysicalId()); + verify(logsService).createLogGroup(eq(result.getPhysicalId()), isNull(), anyMap(), eq(REGION)); + verify(logsService).deleteLogGroup(legacyExplicitName, REGION); + } + + @Test + void legacyGeneratedNameWithNoRecordedMode_reconcilesInPlace() { + // A physical id matching the exact --<12 hex chars> shape must have + // been auto-generated, even with no recorded mode, so it should be reconciled, not replaced. + String legacyGeneratedName = STACK_NAME + "-LogGroup-abc123def456"; + when(logsService.logGroupExists(legacyGeneratedName, REGION)).thenReturn(true); + + StackResource result = provision("{}", legacyGeneratedName, Map.of()); + + assertEquals("CREATE_COMPLETE", result.getStatus()); + assertEquals(legacyGeneratedName, result.getPhysicalId()); + verify(logsService, never()).createLogGroup(eq(legacyGeneratedName), isNull(), anyMap(), eq(REGION)); + verify(logsService, never()).deleteLogGroup(legacyGeneratedName, REGION); + verify(logsService).deleteRetentionPolicy(legacyGeneratedName, REGION); + } + + private StackResource provision(String propertiesJson, String existingPhysicalId, + Map existingAttributes) { + return provisioner.provision("LogGroup", "AWS::Logs::LogGroup", props(propertiesJson), engine(), + REGION, ACCOUNT_ID, STACK_NAME, existingPhysicalId, existingAttributes); + } + + private CloudFormationTemplateEngine engine() { + return new CloudFormationTemplateEngine( + ACCOUNT_ID, REGION, STACK_NAME, "stack/id", + Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper, + (Function) name -> null); + } + + private JsonNode props(String json) { + try { + return mapper.readTree(json); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogsIntegrationTest.java index 094943e9ab..ed1d7ed070 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogsIntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.cloudformation; +import io.github.hectorvent.floci.core.common.XmlParser; import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; import io.restassured.config.EncoderConfig; @@ -8,6 +9,8 @@ import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * End-to-end check that CloudFormation provisions an AWS::Logs::LogGroup for real (into @@ -83,4 +86,364 @@ class CloudFormationLogsIntegrationTest { .statusCode(200) .body(containsString(logGroupName)); } + + @Test + void updateStackReconcilesExistingLogGroupInsteadOfFailing() { + // Regression for #1965: UpdateStack used to call CreateLogGroup unconditionally on every + // update, so a stack whose log group was untouched between deploys rolled back with + // "The specified log group already exists". + String suffix = Long.toString(System.nanoTime(), 36); + String logGroupName = "/cfn/test/" + suffix; + String stackName = "cfn-logs-update-stack-" + suffix; + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", logGroupTemplate(logGroupName, 7)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", logGroupTemplate(logGroupName, 14)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("UPDATE_COMPLETE")) + .body(not(containsString("ROLLBACK"))); + + given() + .config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig() + .encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT))) + .header("Authorization", LOGS_AUTH) + .header("X-Amz-Target", "Logs_20140328.DescribeLogGroups") + .contentType("application/x-amz-json-1.1") + .body("{\"logGroupNamePrefix\":\"" + logGroupName + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("\"retentionInDays\":14")); + } + + @Test + void updateStackKeepsAutoGeneratedLogGroupNameAcrossUpdates() { + // No explicit LogGroupName: the physical name must stay stable across updates (matching + // CloudFormation's real behavior for auto-generated resource names), not get replaced with a + // freshly generated random name on every no-op update. + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-logs-autoname-stack-" + suffix; + String templateNoRetention = """ + { + "Resources": { + "LogGroup": { + "Type": "AWS::Logs::LogGroup", + "Properties": {} + } + }, + "Outputs": { + "GroupArn": {"Value": {"Fn::GetAtt": ["LogGroup", "Arn"]}} + } + } + """; + String templateWithRetention = """ + { + "Resources": { + "LogGroup": { + "Type": "AWS::Logs::LogGroup", + "Properties": { + "RetentionInDays": 30 + } + } + }, + "Outputs": { + "GroupArn": {"Value": {"Fn::GetAtt": ["LogGroup", "Arn"]}} + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", templateNoRetention) + .when() + .post("/") + .then() + .statusCode(200); + + String beforeXml = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + String arnBefore = XmlParser.extractPairs(beforeXml, "Outputs", "OutputKey", "OutputValue") + .get("GroupArn"); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", templateWithRetention) + .when() + .post("/") + .then() + .statusCode(200); + + String afterXml = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("UPDATE_COMPLETE")) + .extract().asString(); + String arnAfter = XmlParser.extractPairs(afterXml, "Outputs", "OutputKey", "OutputValue") + .get("GroupArn"); + + assertEquals(arnBefore, arnAfter); + } + + @Test + void updateStackReplacesLogGroupWhenNameChanges() { + // LogGroupName isn't updatable in place on real AWS - changing it replaces the resource. The + // old group must actually be gone afterward, not just abandoned. + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-logs-rename-stack-" + suffix; + String oldName = "/cfn/test/old-" + suffix; + String newName = "/cfn/test/new-" + suffix; + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", logGroupTemplate(oldName, 7)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", logGroupTemplate(newName, 7)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("UPDATE_COMPLETE")) + .body(containsString("log-group:" + newName + ":*")); + + given() + .config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig() + .encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT))) + .header("Authorization", LOGS_AUTH) + .header("X-Amz-Target", "Logs_20140328.DescribeLogGroups") + .contentType("application/x-amz-json-1.1") + .body("{\"logGroupNamePrefix\":\"" + oldName + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString(oldName))); + } + + @Test + void updateStackRenameCollision_doesNotDeleteOldLogGroupBeforeVerifyingNewOneWorks() { + // If the new name is already taken, CreateLogGroup for it fails and the update rolls back. + // The old group must still be there afterward - deleting it before the new one is confirmed + // creatable would mean rollback can't restore what was already destroyed. + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-logs-collision-stack-" + suffix; + String oldName = "/cfn/test/collision-old-" + suffix; + String takenName = "/cfn/test/collision-taken-" + suffix; + + given() + .config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig() + .encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT))) + .header("Authorization", LOGS_AUTH) + .header("X-Amz-Target", "Logs_20140328.CreateLogGroup") + .contentType("application/x-amz-json-1.1") + .body("{\"logGroupName\":\"" + takenName + "\"}") + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", logGroupTemplate(oldName, 7)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", logGroupTemplate(takenName, 7)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("UPDATE_ROLLBACK_COMPLETE")); + + given() + .config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig() + .encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT))) + .header("Authorization", LOGS_AUTH) + .header("X-Amz-Target", "Logs_20140328.DescribeLogGroups") + .contentType("application/x-amz-json-1.1") + .body("{\"logGroupNamePrefix\":\"" + oldName + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString(oldName)); + } + + @Test + void updateStackRemovingExplicitName_generatesFreshNameInsteadOfKeepingOld() { + // Going from an explicit LogGroupName to none is a naming-mode change, which is itself a + // replacement on real AWS - the group must get a freshly generated name, not silently keep + // reconciling under the removed explicit name. + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-logs-name-removed-stack-" + suffix; + String explicitName = "/cfn/test/explicit-" + suffix; + String templateNoName = """ + { + "Resources": { + "LogGroup": { + "Type": "AWS::Logs::LogGroup", + "Properties": {} + } + }, + "Outputs": { + "GroupArn": {"Value": {"Fn::GetAtt": ["LogGroup", "Arn"]}} + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", logGroupTemplate(explicitName, 7)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", templateNoName) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("UPDATE_COMPLETE")) + .body(not(containsString("log-group:" + explicitName + ":*"))); + + given() + .config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig() + .encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT))) + .header("Authorization", LOGS_AUTH) + .header("X-Amz-Target", "Logs_20140328.DescribeLogGroups") + .contentType("application/x-amz-json-1.1") + .body("{\"logGroupNamePrefix\":\"" + explicitName + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString(explicitName))); + } + + private static String logGroupTemplate(String logGroupName, int retentionInDays) { + return """ + { + "Resources": { + "LogGroup": { + "Type": "AWS::Logs::LogGroup", + "Properties": { + "LogGroupName": "%s", + "RetentionInDays": %d + } + } + }, + "Outputs": { + "GroupArn": {"Value": {"Fn::GetAtt": ["LogGroup", "Arn"]}} + } + } + """.formatted(logGroupName, retentionInDays); + } }