mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): infer Lambda FunctionName mode for pre-fix persisted stacks (#2177)
* fix(cloudformation): infer Lambda FunctionName mode for pre-fix persisted stacks
Fixes #2163
A Lambda function persisted before FlociLambdaFunctionNameMode was
tracked has no recorded mode, so removing an explicit FunctionName
from the template silently kept reconciling under the old explicit
name instead of triggering the replacement AWS requires - the same
bug already fixed for AWS::Logs::LogGroup in #1965/#2152.
Generalizes the LogGroup fix's isGeneratedLogGroupName into a shared
isGeneratedName(physicalId, stackName, logicalId, maxLength), reused
by both resource types instead of duplicated. Made it properly
truncation-aware in the process: at Lambda's 64-character limit,
generatePhysicalName's truncation path is actually reachable (unlike
LogGroup's 512, where CloudFormation's 128+255 character stack
name/logical id limits make it provably unreachable), so the shared
helper now reconstructs the exact expected prefix generatePhysicalName
would produce, truncation included, rather than only matching the
untruncated shape.
* docs(cloudformation): document isGeneratedName's lowercase and maxLength assumptions
Found while re-verifying #2163: several other generatePhysicalName
callers use lowercase=true (S3 bucket, some IAM resources, ECR repo)
or could theoretically use a very small maxLength, neither of which
isGeneratedName accounts for. Not a live bug since both current
callers (LogGroup at 512, Lambda at 64) use lowercase=false and a
maxLength comfortably above the point where the truncated prefix could
go empty, but worth spelling out for whoever reuses this next.
* fix(cloudformation): warn when legacy Lambda name inference is ambiguous
greptile flagged a real gap in the legacy FunctionName mode backfill:
isGeneratedName() can't distinguish a legacy explicit name that
deliberately matches the generated-name shape (e.g. a name copied from
an earlier auto-generated deploy and then pinned) from one that really
was auto-generated all along. If Floci gets it wrong, removing
FunctionName from the template silently keeps the old name instead of
triggering the replacement AWS would perform.
Checked whether this is actually closeable: LAMBDA_NAME_MODE_ATTR is
already written on every successful provision based on that deploy's
real hasExplicitName, so from a resource's second update onward the
mode is exact, no heuristic involved. The heuristic only ever runs
once, on a legacy resource's first update after this attribute was
introduced - and for that one-time backfill, there's no stored history
of the previous template's actual FunctionName property to consult;
Floci never persisted it. No additional data captured now can recover
what was never recorded then, so this can't be made more accurate.
What it can be is observable. Adds a warning logged specifically when
the inference is consequential - a legacy resource, no recorded mode,
the physical ID matches the generated shape, and the current template
also has no FunctionName - so an operator relying on that removal to
trigger a replacement has a chance to notice it silently didn't,
instead of this being an invisible guess. The other inference
direction (name doesn't match the generated shape) isn't ambiguous -
an auto-generated name always has the deterministic shape, so anything
else genuinely was explicit - and correctly doesn't warn.
Verified: two new tests confirm the warning fires for the ambiguous
case and stays silent for the unambiguous one. Confirmed the positive
test fails with the warning temporarily disabled and passes with it
restored. Full cloudformation package regression is green (one
pre-existing, unrelated ECR/Docker-dependent failure, confirmed
against a clean upstream/main baseline earlier this session).
* fix(test): pass the CloudFront service argument in the legacy name mode test
CloudFormationLambdaLegacyNameModeTest calls the CloudFormationResourceProvisioner
constructor with the parameter list it had before #1831 added the CloudFrontService
store, so the merge with current main does not compile. The call goes straight from
the trailing nulls to CloudFormationResourceRegistry, missing CloudFrontService
between them.
This branch predates #1831 (merged as 5657e350) and its CI last ran on 2026-08-08,
so the failure only appears against current main. Same shape as #2261 and #2288.
Verified: full test-compile clean, and 1090 tests pass across the cloudformation,
lambda and cloudwatch.logs packages.
---------
Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
This commit is contained in:
1 parent
5156095f01
commit
0cbfba82dd
2 files changed
+265
-15
No files matched your search
+208
@@ -0,0 +1,208 @@
|
||||
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.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
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.anyString;
|
||||
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 #2163: the same "legacy resource with no recorded name mode" gap fixed for
|
||||
* AWS::Logs::LogGroup in #1965/PR #2152, applied to Lambda's FunctionName. Uses the same direct
|
||||
* provisioner + mocked service approach as CloudFormationLogGroupProvisionerTest, since simulating
|
||||
* "created by an older floci version" isn't reachable through the black-box HTTP integration tests.
|
||||
*/
|
||||
class CloudFormationLambdaLegacyNameModeTest {
|
||||
|
||||
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 LambdaService lambdaService;
|
||||
private CloudFormationResourceProvisioner provisioner;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lambdaService = mock(LambdaService.class);
|
||||
when(lambdaService.updateFunctionConfiguration(anyString(), anyString(), anyMap()))
|
||||
.thenAnswer(inv -> lambdaFunction(inv.getArgument(1)));
|
||||
when(lambdaService.updateFunctionCode(anyString(), anyString(), anyMap()))
|
||||
.thenAnswer(inv -> lambdaFunction(inv.getArgument(1)));
|
||||
provisioner = new CloudFormationResourceProvisioner(
|
||||
null, null, null, null, lambdaService, null, null, null, null, null,
|
||||
null, null, null, null, null, null,
|
||||
mapper,
|
||||
null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null,
|
||||
null, null,
|
||||
new CloudFormationResourceRegistry(List.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyExplicitFunctionNameWithNoRecordedMode_replacesWhenNameIsRemoved() {
|
||||
String legacyExplicitName = "my-hand-chosen-function";
|
||||
when(lambdaService.getFunction(REGION, legacyExplicitName)).thenReturn(lambdaFunction(legacyExplicitName));
|
||||
when(lambdaService.createFunction(anyString(), anyMap()))
|
||||
.thenAnswer(inv -> lambdaFunction((String) ((Map<?, ?>) inv.getArgument(1)).get("FunctionName")));
|
||||
|
||||
StackResource result = provision("{}", legacyExplicitName, Map.of());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", result.getStatus());
|
||||
assertNotEquals(legacyExplicitName, result.getPhysicalId());
|
||||
assertTrue(result.getPhysicalId().startsWith(STACK_NAME + "-Function-"),
|
||||
"expected a freshly generated name, got: " + result.getPhysicalId());
|
||||
verify(lambdaService).deleteFunction(REGION, legacyExplicitName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyGeneratedFunctionNameWithNoRecordedMode_reconcilesInPlace() {
|
||||
String legacyGeneratedName = STACK_NAME + "-Function-abc123def456";
|
||||
when(lambdaService.getFunction(REGION, legacyGeneratedName)).thenReturn(lambdaFunction(legacyGeneratedName));
|
||||
|
||||
StackResource result = provision("{}", legacyGeneratedName, Map.of());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", result.getStatus());
|
||||
assertEquals(legacyGeneratedName, result.getPhysicalId());
|
||||
verify(lambdaService, never()).createFunction(anyString(), anyMap());
|
||||
verify(lambdaService, never()).deleteFunction(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyTruncatedGeneratedFunctionNameWithNoRecordedMode_reconcilesInPlace() {
|
||||
// At Lambda's 64-character limit, truncation is actually reachable (unlike LogGroup's
|
||||
// 512), so a legacy truncated generated name must still be correctly recognized as
|
||||
// generated rather than misclassified as explicit and needlessly replaced. This name is
|
||||
// exactly what generatePhysicalName("test-stack", logicalId, 64, false) produces: the
|
||||
// 61-character "test-stack-<logicalId>" base truncated to the 51 characters that leave
|
||||
// room for "-" plus a 12-character suffix, giving exactly 64 characters total.
|
||||
String logicalId = "MyVeryLongLambdaFunctionLogicalIdForTruncationTest";
|
||||
String legacyGeneratedName = "test-stack-MyVeryLongLambdaFunctionLogicalIdForTrun-abc123def456";
|
||||
assertEquals(64, legacyGeneratedName.length());
|
||||
when(lambdaService.getFunction(REGION, legacyGeneratedName)).thenReturn(lambdaFunction(legacyGeneratedName));
|
||||
|
||||
StackResource result = provisioner.provision(logicalId, "AWS::Lambda::Function", props("{}"), engine(),
|
||||
REGION, ACCOUNT_ID, STACK_NAME, legacyGeneratedName, Map.of());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", result.getStatus());
|
||||
assertEquals(legacyGeneratedName, result.getPhysicalId());
|
||||
verify(lambdaService, never()).createFunction(anyString(), anyMap());
|
||||
verify(lambdaService, never()).deleteFunction(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyGeneratedFunctionNameWithNoRecordedMode_warnsAboutTheAmbiguousInference() {
|
||||
// Regression: inferring "generated" for a legacy name that happens to match the generated
|
||||
// shape is a guess Floci cannot verify - if the name was actually pinned explicitly, this
|
||||
// inference silently suppresses the replacement AWS would perform. There's no way to close
|
||||
// that gap (the raw historical property value was never persisted to check against), so this
|
||||
// instead verifies the guess is at least observable: a warning logged specifically when the
|
||||
// inference is consequential (current template also has no FunctionName).
|
||||
String legacyGeneratedName = STACK_NAME + "-Function-abc123def456";
|
||||
when(lambdaService.getFunction(REGION, legacyGeneratedName)).thenReturn(lambdaFunction(legacyGeneratedName));
|
||||
|
||||
List<String> messages = provisionerLogMessages(() -> provision("{}", legacyGeneratedName, Map.of()));
|
||||
|
||||
assertTrue(messages.stream().anyMatch(m ->
|
||||
m.contains("auto-generated because it matches the generated-name shape")),
|
||||
"expected a warning about the ambiguous legacy-name inference, got: " + messages);
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyExplicitFunctionNameWithNoRecordedMode_doesNotWarn() {
|
||||
// The other inference direction (legacy name does NOT match the generated shape, so it's
|
||||
// treated as explicit) has no real ambiguity - an auto-generated name always has the
|
||||
// deterministic shape, so anything else genuinely must have been explicit. No warning should
|
||||
// fire for what is actually the safe, unambiguous, common case.
|
||||
String legacyExplicitName = "my-hand-chosen-function";
|
||||
when(lambdaService.getFunction(REGION, legacyExplicitName)).thenReturn(lambdaFunction(legacyExplicitName));
|
||||
when(lambdaService.createFunction(anyString(), anyMap()))
|
||||
.thenAnswer(inv -> lambdaFunction((String) ((Map<?, ?>) inv.getArgument(1)).get("FunctionName")));
|
||||
|
||||
List<String> messages = provisionerLogMessages(() -> provision("{}", legacyExplicitName, Map.of()));
|
||||
|
||||
assertFalse(messages.stream().anyMatch(m ->
|
||||
m.contains("auto-generated because it matches the generated-name shape")),
|
||||
"did not expect a warning for the unambiguous explicit-name case, got: " + messages);
|
||||
}
|
||||
|
||||
/** Collects the messages CloudFormationResourceProvisioner logs while {@code action} runs. */
|
||||
private List<String> provisionerLogMessages(Runnable action) {
|
||||
java.util.logging.Logger logger =
|
||||
java.util.logging.Logger.getLogger(CloudFormationResourceProvisioner.class.getName());
|
||||
List<String> messages = new CopyOnWriteArrayList<>();
|
||||
java.util.logging.Handler handler = new java.util.logging.Handler() {
|
||||
@Override
|
||||
public void publish(java.util.logging.LogRecord logRecord) {
|
||||
messages.add(logRecord.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
};
|
||||
logger.addHandler(handler);
|
||||
try {
|
||||
action.run();
|
||||
} finally {
|
||||
logger.removeHandler(handler);
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
private StackResource provision(String propertiesJson, String existingPhysicalId,
|
||||
Map<String, String> existingAttributes) {
|
||||
return provisioner.provision("Function", "AWS::Lambda::Function", props(propertiesJson), engine(),
|
||||
REGION, ACCOUNT_ID, STACK_NAME, existingPhysicalId, existingAttributes);
|
||||
}
|
||||
|
||||
private static LambdaFunction lambdaFunction(String name) {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName(name);
|
||||
fn.setFunctionArn("arn:aws:lambda:" + REGION + ":" + ACCOUNT_ID + ":function:" + name);
|
||||
fn.setPackageType("Zip");
|
||||
fn.setRuntime("nodejs18.x");
|
||||
fn.setHandler("index.handler");
|
||||
fn.setRole("arn:aws:iam::" + ACCOUNT_ID + ":role/default");
|
||||
fn.setRevisionId("1");
|
||||
return fn;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user