mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -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
+57
-15
@@ -800,9 +800,9 @@ public class CloudFormationResourceProvisioner {
|
||||
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 <stackName>-<logicalId>-<12 hex chars>
|
||||
// shape generatePhysicalName produces, so anything else must have been explicit.
|
||||
previousNameMode = isGeneratedLogGroupName(r.getPhysicalId(), stackName, r.getLogicalId())
|
||||
// auto-generated name always has the deterministic shape generatePhysicalName produces,
|
||||
// so anything else must have been explicit.
|
||||
previousNameMode = isGeneratedName(r.getPhysicalId(), stackName, r.getLogicalId(), 512)
|
||||
? NAME_MODE_GENERATED
|
||||
: NAME_MODE_EXPLICIT;
|
||||
}
|
||||
@@ -878,20 +878,20 @@ public class CloudFormationResourceProvisioner {
|
||||
|
||||
/**
|
||||
* Whether {@code physicalId} matches the exact shape {@link #generatePhysicalName} produces for
|
||||
* this stack/logical id: {@code <stackName>-<logicalId>-} 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.
|
||||
* this stack/logical id/maxLength: its base-and-truncation logic (minus the random suffix itself)
|
||||
* followed by exactly 12 lowercase hex characters. Used to infer a legacy resource's name mode
|
||||
* (explicit vs. generated) when it predates whatever attribute would otherwise record that.
|
||||
*
|
||||
* <p>Assumes the {@code generatePhysicalName} call this mirrors used {@code lowercase=false} (true
|
||||
* of both current callers, LogGroup and Lambda) and a {@code maxLength} large enough that the
|
||||
* truncated prefix is never empty, i.e. {@code maxLength > 13} (also true of both: 512 and 64). A
|
||||
* future caller with {@code lowercase=true} or a smaller limit would need this generalized further.
|
||||
*/
|
||||
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) {
|
||||
private boolean isGeneratedName(String physicalId, String stackName, String logicalId, int maxLength) {
|
||||
if (physicalId == null || physicalId.length() < 13) {
|
||||
return false;
|
||||
}
|
||||
String suffix = physicalId.substring(physicalId.length() - 12);
|
||||
for (int i = 0; i < suffix.length(); i++) {
|
||||
char c = suffix.charAt(i);
|
||||
boolean hex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
|
||||
@@ -899,7 +899,25 @@ public class CloudFormationResourceProvisioner {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
if (physicalId.charAt(physicalId.length() - 13) != '-') {
|
||||
return false;
|
||||
}
|
||||
String actualPrefix = physicalId.substring(0, physicalId.length() - 13);
|
||||
return actualPrefix.equals(expectedGeneratedNamePrefix(stackName, logicalId, maxLength));
|
||||
}
|
||||
|
||||
/** Mirrors {@link #generatePhysicalName}'s base-and-truncation logic, without the random suffix. */
|
||||
private String expectedGeneratedNamePrefix(String stackName, String logicalId, int maxLength) {
|
||||
String base = stackName + "-" + logicalId;
|
||||
if (maxLength <= 0 || base.length() + 1 + 12 <= maxLength) {
|
||||
return base;
|
||||
}
|
||||
int keep = Math.max(0, maxLength - 12 - 1);
|
||||
String prefix = base.length() > keep ? base.substring(0, keep) : base;
|
||||
while (prefix.endsWith("-")) {
|
||||
prefix = prefix.substring(0, prefix.length() - 1);
|
||||
}
|
||||
return prefix;
|
||||
}
|
||||
|
||||
private void reconcileLogGroup(String name, Integer retentionInDays, Map<String, String> tags, String region) {
|
||||
@@ -1630,6 +1648,30 @@ public class CloudFormationResourceProvisioner {
|
||||
boolean hasExplicitName = explicitName != null && !explicitName.isBlank();
|
||||
String packageType = resolveOrDefault(props, "PackageType", engine, "Zip");
|
||||
String previousNameMode = r.getAttributes().get(LAMBDA_NAME_MODE_ATTR);
|
||||
if (previousNameMode == null && r.getPhysicalId() != null) {
|
||||
// Functions persisted before LAMBDA_NAME_MODE_ATTR existed have no recorded mode, but an
|
||||
// auto-generated name always has the deterministic shape generatePhysicalName produces,
|
||||
// so anything else must have been explicit (see #1965/#2152 for the LogGroup precedent
|
||||
// this mirrors, and #2163 for this gap).
|
||||
previousNameMode = isGeneratedName(r.getPhysicalId(), stackName, r.getLogicalId(), 64)
|
||||
? NAME_MODE_GENERATED
|
||||
: NAME_MODE_EXPLICIT;
|
||||
if (NAME_MODE_GENERATED.equals(previousNameMode) && !hasExplicitName) {
|
||||
// This inference is what decides explicitRemoved below, and it's the one direction
|
||||
// that can be wrong with no way for Floci to tell: a legacy FunctionName that was
|
||||
// actually pinned explicitly, but happens to exactly match generatePhysicalName's
|
||||
// shape (e.g. a user who deliberately reused a name Floci had previously generated),
|
||||
// is indistinguishable from a name that really was auto-generated all along - the raw
|
||||
// property value from that far back was never persisted to check against. Logged so
|
||||
// an operator relying on this FunctionName removal to trigger a replacement has a
|
||||
// chance to notice it silently didn't, rather than this being an invisible guess.
|
||||
LOG.warnv("Lambda {0} in stack {1}: inferring legacy FunctionName ''{2}'' as "
|
||||
+ "auto-generated because it matches the generated-name shape; if it "
|
||||
+ "was actually set explicitly, removing FunctionName here will not "
|
||||
+ "trigger the replacement AWS would perform",
|
||||
r.getLogicalId(), stackName, r.getPhysicalId());
|
||||
}
|
||||
}
|
||||
String oldPackageType = r.getAttributes().get(LAMBDA_PACKAGE_TYPE_ATTR);
|
||||
boolean packageTypeReplacement = r.getPhysicalId() != null
|
||||
&& oldPackageType != null
|
||||
|
||||
+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