fix(cloudformation): reconcile AWS::Logs::LogGroup in place on UpdateStack (#2152)

* fix(cloudformation): reconcile AWS::Logs::LogGroup in place on UpdateStack

Fixes #1965

Root cause: provisionLogGroup called CreateLogGroup unconditionally on
every provision, including updates to a stack whose log group already
existed and was untouched. CloudWatchLogsService.createLogGroup throws
ResourceAlreadyExistsException in that case, so any UpdateStack on a
stack with a log group resource rolled back with "The specified log
group already exists", even when nothing about the resource changed.

Fix: on update, reconcile retention and tags in place instead of
recreating, matching the pattern already used for Lambda functions.
LogGroupName isn't updatable in place on real AWS, so a name change
still deletes the old group and creates a new one (replacement).

Also fixed a related gap: auto-generated LogGroupName (no explicit
name in the template) called generatePhysicalName, which mints a new
random name on every call, so an auto-named log group was replaced on
every single update even when unchanged. It now reuses the existing
physical name across updates, matching how auto-generated Lambda
function names are handled.

* fix(cloudformation): fix LogGroup replacement ordering and name-mode tracking

Addresses two review findings on the reconciliation fix:

- A LogGroupName rename deleted the old log group before confirming
  the new name could actually be created. If the new name collided
  with an existing group, CreateLogGroup failed and the update rolled
  back, but the old group was already gone and rollback does not
  restore it - permanent data loss. Now creates the new group first,
  matching the existing create-before-delete pattern already used for
  Lambda function replacement, and only deletes the old group once the
  new one exists.
- Removing an explicit LogGroupName from the template fell through to
  the "no explicit name" branch, which reused the prior physical id -
  the old explicit name - instead of generating a fresh name for the
  new auto-generated mode. Now tracks whether the current name is
  explicit or generated (mirroring FlociLambdaFunctionNameMode) and
  forces a fresh generated name when an explicit name is removed.

* fix(cloudformation): infer LogGroup name mode for pre-fix persisted stacks

A log group persisted by a floci version before FlociLogGroupNameMode
was tracked has no recorded mode, so explicitNameRemoved could never
be detected for it even when it should be.

Fixes it by backfilling the mode from the physical id's shape:
generatePhysicalName always produces <stackName>-<logicalId>-<12 hex
chars>, so anything else must have been an explicit LogGroupName.
Doesn't attempt to un-truncate the (practically unreachable at a
512-character limit) truncation path, conservatively treating that
edge case as explicit.

Added a dedicated unit test exercising both legacy cases directly
against the provisioner, since simulating "created by an older floci
version" isn't reachable through the black-box HTTP integration tests.

* refactor(cloudformation): rename shared name-mode constants off the Lambda prefix

NAME_MODE_EXPLICIT/NAME_MODE_GENERATED are generic mode-value labels
shared by both the Lambda and LogGroup name-mode tracking, not
Lambda-specific, so the LAMBDA_ prefix was misleading now that a
second resource type uses them. LAMBDA_NAME_MODE_ATTR is unchanged,
since that one is a genuinely Lambda-specific attribute key.
This commit is contained in:
Olamide Kosile authored and GitHub committed 2026-08-07 16:10:54 -04:00
1 parent f6faf0ffe5
commit 76b264f667
4 files changed
+570 -7

No files matched your search

@@ -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 <stackName>-<logicalId>-<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<String, String> 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<String, String>) name -> null);
}
private JsonNode props(String json) {
try {
return mapper.readTree(json);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -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("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.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("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.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("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.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("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.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);
}
}