mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): resolve FunctionResponseTypes through whole-property intrinsics (#2996)
* fix(cloudformation): resolve FunctionResponseTypes through whole-property intrinsics Greptile review on #2964 (merged): resolveStringList checked isArray() on the raw, unresolved property node, so a whole-property intrinsic like Fn::If, Fn::Split, or a Ref to a CommaDelimitedList parameter was silently rejected instead of evaluated, leaving FunctionResponseTypes empty for otherwise-valid templates. hectorvent merged #2964 anyway, treating this as an acceptable known limitation given the property's narrow value domain, but it turned out to be a self-correction I should have caught: this same file already has resolveStringListOrEmpty, which resolves the whole property through resolveNode first, and swapping to it is a straight improvement with no downside for the plain-array case. That still needed a real fix underneath it: resolveNode treated Fn::If as a scalar-collapsing intrinsic like Ref/Fn::Sub, so it stringified a chosen array or object branch instead of preserving it. This is the same engine gap Greptile flagged on PR #2796 (ScheduleGroup Tags), which hectorvent asked to be raised separately rather than fixed in that PR. Since a real fix was needed here to close this issue's gap for good, resolveNode now special-cases Fn::If: it picks the branch the same way resolve() does, then resolves that branch recursively instead of collapsing it, so the result keeps whatever shape the chosen branch actually has. resolve() itself is unchanged. Verified by disabling each fix independently and confirming the corresponding test fails with the exact expected error before restoring it. Full cloudformation package regression (1272 tests) passes clean. * fix(cloudformation): use resolveList for FunctionResponseTypes, not resolveStringListOrEmpty Greptile review on this PR: resolveStringListOrEmpty routes through resolveNode, so it now sees an Fn::If-wrapped list, but resolveNode never implemented real list-splitting logic - it just special-cases which intrinsics collapse to a scalar. Fn::Split and a Ref to a CommaDelimitedList parameter still resolved to a bare string there, so resolveStringListOrEmpty's isArray() check still rejected them. The engine already has a purpose-built method for exactly this, resolveList, which correctly handles a literal array, Fn::GetAZs, Fn::Cidr, Fn::Split (with its actual delimiter), and a comma-delimited scalar (a Ref to a CommaDelimitedList parameter). It only needed Fn::If added, the same way resolveNode gained it: pick the branch, then resolve that branch through resolveList itself rather than collapsing it, so a list-shaped branch (a literal array or another Fn::Split) stays list-shaped. Made resolveList public and switched provisionLambdaEventSourceMapping to call it directly for FunctionResponseTypes, closing the gap for Fn::If, Fn::Split, and CommaDelimitedList Refs in one pass instead of leaving Fn::Split and CommaDelimitedList as a known follow-up gap. Verified by disabling the new Fn::If branch in resolveList and confirming the test fails with the exact expected wrong value before restoring it - the first version of that test used comma-friendly data that passed either way, so it was rewritten with a non-comma delimiter to actually discriminate. Full cloudformation package regression (1276 tests) passes clean. * fix(cloudformation): route FunctionResponseTypes through resolveStringList, not resolveList hectorvent (review): since #2946, the provisioner's resolveStringList helper already delegates to engine.resolveStringList, which handles Fn::If/Fn::Split/CommaDelimitedList and drops blank entries - making the resolveList hunk from this PR redundant, and worse: resolveList keeps blanks, so a conditional element resolving to AWS::NoValue was forwarded as an invalid empty-string response type (also flagged by Greptile). Drops the resolveList call in favor of the existing resolveStringList helper, makes resolveList private again (its only external caller was this now-removed hunk), and points the engine tests at resolveStringList. Adds a test pinning the NoValue-drops-the-entry behavior Greptile flagged.
This commit is contained in:
1 parent
50836bbdc8
commit
9eb4fc82cd
3 files changed
+237
-13
No files matched your search
+29
-13
@@ -120,8 +120,17 @@ public class CloudFormationTemplateEngine {
|
||||
return node;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
if (node.has("Fn::If")) {
|
||||
// Unlike the other intrinsics below, Fn::If's two branches can be any JSON shape
|
||||
// (array, object, or scalar) - it just forwards one of them verbatim. Collapsing it
|
||||
// through resolve() like the scalar-only intrinsics would stringify a chosen array or
|
||||
// object instead of preserving it, so a conditional list (e.g. a Tags property) reads
|
||||
// as unresolvable everywhere a caller checks isArray() on the result.
|
||||
JsonNode branch = selectIfBranch(node.get("Fn::If"));
|
||||
return branch == null ? TextNode.valueOf("") : resolveNode(branch);
|
||||
}
|
||||
if (node.has("Ref") || node.has("Fn::Sub") || node.has("Fn::Join") ||
|
||||
node.has("Fn::Select") || node.has("Fn::If") || node.has("Fn::Base64") ||
|
||||
node.has("Fn::Select") || node.has("Fn::Base64") ||
|
||||
node.has("Fn::GetAtt") || node.has("Fn::ImportValue") || node.has("Fn::Split") ||
|
||||
node.has("Fn::GetAZs") || node.has("Fn::Cidr") || node.has("Fn::FindInMap")) {
|
||||
return TextNode.valueOf(resolve(node));
|
||||
@@ -261,8 +270,8 @@ public class CloudFormationTemplateEngine {
|
||||
|
||||
/**
|
||||
* Resolves a node that represents a list — a literal array, a list-producing intrinsic
|
||||
* ({@code Fn::GetAZs}, {@code Fn::Cidr}, {@code Fn::Split}), or a comma-delimited scalar
|
||||
* (e.g. a {@code Ref} to a {@code List<>} parameter).
|
||||
* ({@code Fn::GetAZs}, {@code Fn::Cidr}, {@code Fn::Split}), an {@code Fn::If} choosing between
|
||||
* two such lists, or a comma-delimited scalar (e.g. a {@code Ref} to a {@code List<>} parameter).
|
||||
*/
|
||||
private List<String> resolveList(JsonNode node) {
|
||||
List<String> out = new ArrayList<>();
|
||||
@@ -273,6 +282,14 @@ public class CloudFormationTemplateEngine {
|
||||
return resolveListElements(node);
|
||||
}
|
||||
if (node.isObject()) {
|
||||
if (node.has("Fn::If")) {
|
||||
// Fn::If's branch can itself be any of the shapes this method already handles
|
||||
// (literal array, Fn::Split, ...), so recurse into it rather than falling through
|
||||
// to the scalar branch below, which would stringify a list-shaped branch instead
|
||||
// of splitting it.
|
||||
JsonNode branch = selectIfBranch(node.get("Fn::If"));
|
||||
return branch == null ? out : resolveList(branch);
|
||||
}
|
||||
if (node.has("Fn::GetAZs")) {
|
||||
return resolveAvailabilityZones(node.get("Fn::GetAZs"));
|
||||
}
|
||||
@@ -282,14 +299,6 @@ public class CloudFormationTemplateEngine {
|
||||
if (node.has("Fn::Split")) {
|
||||
return resolveSplit(node.get("Fn::Split"));
|
||||
}
|
||||
if (node.has("Fn::If")) {
|
||||
JsonNode ifNode = node.get("Fn::If");
|
||||
if (ifNode.isArray() && ifNode.size() >= 3) {
|
||||
String conditionName = ifNode.get(0).asText();
|
||||
boolean condValue = conditions.getOrDefault(conditionName, false);
|
||||
return resolveList(condValue ? ifNode.get(1) : ifNode.get(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
String scalar = resolve(node);
|
||||
if (!scalar.isEmpty()) {
|
||||
@@ -448,12 +457,19 @@ public class CloudFormationTemplateEngine {
|
||||
}
|
||||
|
||||
private String resolveIf(JsonNode ifNode) {
|
||||
JsonNode branch = selectIfBranch(ifNode);
|
||||
return branch == null ? "" : resolve(branch);
|
||||
}
|
||||
|
||||
/** Picks Fn::If's true/false branch without resolving it further, so the caller decides
|
||||
* whether to collapse it to a scalar ({@link #resolve}) or preserve its shape ({@link #resolveNode}). */
|
||||
private JsonNode selectIfBranch(JsonNode ifNode) {
|
||||
if (!ifNode.isArray() || ifNode.size() < 3) {
|
||||
return "";
|
||||
return null;
|
||||
}
|
||||
String conditionName = ifNode.get(0).asText();
|
||||
boolean condValue = conditions.getOrDefault(conditionName, false);
|
||||
return resolve(condValue ? ifNode.get(1) : ifNode.get(2));
|
||||
return condValue ? ifNode.get(1) : ifNode.get(2);
|
||||
}
|
||||
|
||||
private String resolveGetAtt(JsonNode getAtt) {
|
||||
|
||||
+84
@@ -4769,6 +4769,90 @@ class CloudFormationIntegrationTest {
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_lambdaEventSourceMappingWithConditionalFunctionResponseTypes() throws Exception {
|
||||
// github.com/floci-io/floci/issues/2848 follow-up (Greptile review on the fix): a
|
||||
// whole-property intrinsic such as Fn::If must still resolve FunctionResponseTypes, not
|
||||
// just a plain array. resolveStringList (via the engine's resolveList) now resolves
|
||||
// Fn::If, Fn::Split and a CommaDelimitedList Ref, and drops any resulting blank entries.
|
||||
String stackName = "cfn-esm-conditional-stack";
|
||||
String funcName = "cfn-esm-conditional-func";
|
||||
String queueName = "cfn-esm-conditional-queue";
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"ReportBatchFailures": { "Type": "String", "Default": "true" }
|
||||
},
|
||||
"Conditions": {
|
||||
"ShouldReportBatchFailures": { "Fn::Equals": [{ "Ref": "ReportBatchFailures" }, "true"] }
|
||||
},
|
||||
"Resources": {
|
||||
"MyQueue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": { "QueueName": "%s" }
|
||||
},
|
||||
"MyFunction": {
|
||||
"Type": "AWS::Lambda::Function",
|
||||
"Properties": {
|
||||
"FunctionName": "%s",
|
||||
"Runtime": "nodejs20.x",
|
||||
"Handler": "index.handler",
|
||||
"Role": "arn:aws:iam::000000000000:role/lambda-role",
|
||||
"Code": {
|
||||
"ZipFile": "exports.handler = async (e) => ({ statusCode: 200 });"
|
||||
}
|
||||
}
|
||||
},
|
||||
"MyESM": {
|
||||
"Type": "AWS::Lambda::EventSourceMapping",
|
||||
"Properties": {
|
||||
"FunctionName": { "Ref": "MyFunction" },
|
||||
"EventSourceArn": { "Fn::GetAtt": ["MyQueue", "Arn"] },
|
||||
"BatchSize": 5,
|
||||
"FunctionResponseTypes": {
|
||||
"Fn::If": ["ShouldReportBatchFailures", ["ReportBatchItemFailures"], []]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(queueName, funcName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
|
||||
|
||||
String esmJson = given()
|
||||
.when()
|
||||
.get("/2015-03-31/event-source-mappings?FunctionName=" + funcName)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().body().asString();
|
||||
|
||||
JsonNode esmList = OBJECT_MAPPER.readTree(esmJson);
|
||||
JsonNode responseTypes = esmList.path("EventSourceMappings").get(0).path("FunctionResponseTypes");
|
||||
assertTrue(responseTypes.isArray() && responseTypes.size() == 1
|
||||
&& "ReportBatchItemFailures".equals(responseTypes.get(0).asText()),
|
||||
"expected the Fn::If-selected branch to carry through but was: " + responseTypes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_lambdaEventSourceMappingKafka() throws Exception {
|
||||
String stackName = "cfn-esm-kafka-stack";
|
||||
|
||||
+124
@@ -4,11 +4,13 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class CloudFormationTemplateEngineTest {
|
||||
|
||||
@@ -102,6 +104,128 @@ class CloudFormationTemplateEngineTest {
|
||||
assertNull(engine().resolveJsonAttribute(mapper.createArrayNode().path("nope")));
|
||||
}
|
||||
|
||||
private CloudFormationTemplateEngine engineWithCondition(String name, boolean value) {
|
||||
return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
|
||||
"stack/id", Map.of(), Map.of(), Map.of(), Map.of(name, value), Map.of(), mapper,
|
||||
(Function<String, String>) n -> null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveFnIfPicksTheTrueBranchScalar() {
|
||||
assertEquals("prod", engineWithCondition("UseProd", true)
|
||||
.resolve(json("{\"Fn::If\": [\"UseProd\", \"prod\", \"dev\"]}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveFnIfPicksTheFalseBranchScalar() {
|
||||
assertEquals("dev", engineWithCondition("UseProd", false)
|
||||
.resolve(json("{\"Fn::If\": [\"UseProd\", \"prod\", \"dev\"]}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveNodePreservesArrayShapeThroughFnIf() {
|
||||
// github.com/floci-io/floci/issues/2396 (PR #2796 review): resolveNode treated Fn::If the
|
||||
// same as every other intrinsic and collapsed it to a stringified scalar, so a conditional
|
||||
// array (e.g. a Tags property choosing between two tag lists) resolved to text instead of
|
||||
// the chosen branch's actual array - every caller checking isArray() on the result then
|
||||
// read a resolvable conditional list as unresolvable.
|
||||
JsonNode ifNode = json("""
|
||||
{"Fn::If": ["UseProdTags",
|
||||
[{"Key": "Env", "Value": "prod"}],
|
||||
[{"Key": "Env", "Value": "dev"}]]}
|
||||
""");
|
||||
|
||||
JsonNode trueResolved = engineWithCondition("UseProdTags", true).resolveNode(ifNode);
|
||||
assertTrue(trueResolved.isArray(), "true branch must resolve to a real array: " + trueResolved);
|
||||
assertEquals("prod", trueResolved.get(0).get("Value").asText());
|
||||
|
||||
JsonNode falseResolved = engineWithCondition("UseProdTags", false).resolveNode(ifNode);
|
||||
assertTrue(falseResolved.isArray(), "false branch must resolve to a real array: " + falseResolved);
|
||||
assertEquals("dev", falseResolved.get(0).get("Value").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveNodeResolvesIntrinsicsInsideTheChosenFnIfBranch() {
|
||||
// The chosen branch is passed back through resolveNode, not returned verbatim, so a nested
|
||||
// intrinsic inside it (e.g. a Ref-valued tag) still resolves.
|
||||
JsonNode ifNode = json("""
|
||||
{"Fn::If": ["UseProdTags", [{"Key": "Env", "Value": {"Ref": "AWS::Region"}}], []]}
|
||||
""");
|
||||
|
||||
JsonNode resolved = engineWithCondition("UseProdTags", true).resolveNode(ifNode);
|
||||
|
||||
assertEquals("us-east-1", resolved.get(0).get("Value").asText());
|
||||
}
|
||||
|
||||
private CloudFormationTemplateEngine engineWithParameter(String name, String value) {
|
||||
return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
|
||||
"stack/id", Map.of(name, value), Map.of(), Map.of(), Map.of(), Map.of(), mapper,
|
||||
(Function<String, String>) n -> null);
|
||||
}
|
||||
|
||||
// github.com/floci-io/floci/issues/2848 (Greptile review on the follow-up fix): "List
|
||||
// intrinsics remain scalar" - resolveNode's Fn::If fix alone does not make Fn::Split or a Ref
|
||||
// to a CommaDelimitedList parameter list-shaped, since resolveNode never split anything to
|
||||
// begin with. resolveStringList already handled Fn::Split and comma-delimited scalars
|
||||
// correctly (and drops blank entries, unlike the private resolveList it delegates to); it
|
||||
// only needed Fn::If added, which is what these exercise.
|
||||
|
||||
@Test
|
||||
void resolveStringListSplitsFnSplitWithItsActualDelimiter() {
|
||||
assertEquals(List.of("a", "b", "c"),
|
||||
engine().resolveStringList(json("{\"Fn::Split\": [\"|\", \"a|b|c\"]}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveStringListSplitsACommaDelimitedListParameterRef() {
|
||||
assertEquals(List.of("a", "b", "c"),
|
||||
engineWithParameter("Csv", "a,b,c").resolveStringList(json("{\"Ref\": \"Csv\"}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveStringListResolvesFnIfChoosingBetweenTwoFnSplitLists() {
|
||||
// The delimiter is deliberately not a comma: falling through to the pre-existing
|
||||
// scalar-then-comma-split fallback (rather than actually recursing into the Fn::Split
|
||||
// branch) would return the whole unsplit "a|b|c" source as a single element instead of
|
||||
// the three pipe-split ones, so this only passes if resolveList's own Fn::If handling
|
||||
// is what runs.
|
||||
JsonNode node = json("""
|
||||
{"Fn::If": ["UseReportBatch",
|
||||
{"Fn::Split": ["|", "a|b|c"]},
|
||||
{"Fn::Split": ["|", "x|y"]}]}
|
||||
""");
|
||||
|
||||
assertEquals(List.of("a", "b", "c"),
|
||||
engineWithCondition("UseReportBatch", true).resolveStringList(node));
|
||||
assertEquals(List.of("x", "y"),
|
||||
engineWithCondition("UseReportBatch", false).resolveStringList(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveStringListResolvesFnIfChoosingBetweenACommaDelimitedRefAndALiteralArray() {
|
||||
JsonNode node = json("{\"Fn::If\": [\"UseParam\", {\"Ref\": \"Csv\"}, [\"fallback\"]]}");
|
||||
|
||||
CloudFormationTemplateEngine trueEngine = new CloudFormationTemplateEngine(
|
||||
"000000000000", "us-east-1", "my-stack", "stack/id",
|
||||
Map.of("Csv", "x,y"), Map.of(), Map.of(), Map.of("UseParam", true), Map.of(), mapper,
|
||||
(Function<String, String>) n -> null);
|
||||
assertEquals(List.of("x", "y"), trueEngine.resolveStringList(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveStringListDropsAConditionalElementThatResolvesToNoValue() {
|
||||
// github.com/floci-io/floci/pull/2996 (Greptile review): a list element that resolves to
|
||||
// AWS::NoValue must be omitted, not forwarded as an invalid empty-string list entry. This
|
||||
// is exactly why FunctionResponseTypes must go through resolveStringList (which drops
|
||||
// blanks) rather than the private resolveList it delegates to (which keeps them).
|
||||
JsonNode node = json("""
|
||||
["ReportBatchItemFailures", {"Fn::If": ["UseExtra", "ExtraType", {"Ref": "AWS::NoValue"}]}]
|
||||
""");
|
||||
|
||||
assertEquals(List.of("ReportBatchItemFailures"),
|
||||
engineWithCondition("UseExtra", false).resolveStringList(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveStringListSplitsListValuedIntrinsicNode() {
|
||||
CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000",
|
||||
|
||||
Reference in new issue
Block a user