From f2140508679488fa786bcb65a4bb496eae3c46d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Sun, 6 Sep 2026 00:40:23 +0700 Subject: [PATCH] fix(cloudformation): resolve list-valued intrinsics for DBSubnetGroup SubnetIds (#2946) * feat(cloudformation): add list-aware resolveStringList to template engine (#2937) * fix(cloudformation): resolve cross-stack SubnetIds for DBSubnetGroup (#2937) * fix(cloudformation): resolve list-valued intrinsics for every list property (#2937) * fix(rds): name the missing subnet ids in DBSubnetGroup error (#2937) * fix(cloudformation): evaluate Fn::If list-valued branches in resolveStringList (#2937) * fix(cloudformation): route ProvisionContext.resolveStringList through the list-aware engine (#2937) ProvisionContext.resolveStringList was a scalar-only copy of the monolith helper that CloudFormationResourceProvisioner already reroutes, and it is the one the extracted per-service provisioners call (IamRoleCfnProvisioner ManagedPolicyArns, OrganizationsCfnProvisioner ParentIds and TargetIds). Delegate to engine.resolveStringList so a list-valued intrinsic (Fn::Split / Fn::GetAZs / Fn::Cidr, including one selected by Fn::If) expands to its real values instead of collapsing to one comma-joined string, keeping "every list property" true and stopping the two helpers from drifting. The mock engines in IamRoleCfnProvisionerTest and OrganizationsCfnProvisionerTest now delegate resolveStringList to the real method (literal arrays still resolve each element through the existing resolve(...) stub). * fix(cloudformation): expand nested list-valued intrinsics in array branches selected by Fn::If (#2937) * chore: remove accidentally committed docs/superpowers/ from the merge These are local planning notes from an unrelated task, never meant to be tracked; git add -A during the second/main merge conflict resolution swept them in along with it, and their em-dashes tripped the Documentation Style CI check. * fix(cloudformation): stop Fn::Select from dropping blank list entries resolveList's array branch delegated to resolveStringList, which drops blank entries for its provisioner-facing contract (SubnetIds, VPCZoneIdentifier, ...). Fn::Select is positional, so a blank entry ahead of the selected index shifted every later index instead of being treated as a real element. Extracted the shared array-expansion logic (recursing into nested list-valued intrinsics like Fn::Split) into resolveListElements, used by resolveList without the blank-drop and by resolveStringList with it. * test(cloudformation): stub engine.resolveStringList in AcmCfnProvisionerTest ProvisionContext.resolveStringList now routes through engine.resolveStringList (2cea55bd), but AcmCfnProvisionerTest's mock engine never stubbed it, so Mockito's default answer (an empty list) made every SubjectAlternativeNames resolve to []. Same fix already applied to IamRoleCfnProvisionerTest and OrganizationsCfnProvisionerTest. --- .../CloudFormationResourceProvisioner.java | 26 ++-- .../CloudFormationTemplateEngine.java | 81 ++++++++++++- .../provisioners/ProvisionContext.java | 22 ++-- .../floci/services/rds/RdsService.java | 12 +- .../CloudFormationTemplateEngineTest.java | 112 ++++++++++++++++++ .../cloudformation/RdsCfnProvisionerTest.java | 112 +++++++++++++++++- .../provisioners/AcmCfnProvisionerTest.java | 3 + .../IamRoleCfnProvisionerTest.java | 4 + .../OrganizationsCfnProvisionerTest.java | 3 + .../provisioners/ProvisionContextTest.java | 33 ++++++ .../floci/services/rds/RdsServiceTest.java | 15 +++ 11 files changed, 391 insertions(+), 32 deletions(-) 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 ac59e2a45b..a3ade4a491 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 @@ -1175,16 +1175,12 @@ public class CloudFormationResourceProvisioner { } private List resolveStringList(JsonNode props, String field, CloudFormationTemplateEngine engine) { - List values = new ArrayList<>(); - if (props != null && props.has(field) && props.get(field).isArray()) { - for (JsonNode element : props.get(field)) { - String resolved = engine.resolve(element); - if (resolved != null && !resolved.isBlank()) { - values.add(resolved); - } - } + if (props == null || !props.has(field)) { + return new ArrayList<>(); } - return values; + // engine.resolveStringList accepts both a literal array and a list-valued intrinsic + // (Fn::Split / Fn::GetAZs / Fn::Cidr) and drops blank entries (issue #2937). + return new ArrayList<>(engine.resolveStringList(props.get(field))); } private String blankToNull(String value) { @@ -1299,12 +1295,12 @@ public class CloudFormationResourceProvisioner { } String description = firstNonBlank(resolveOptional(props, "DBSubnetGroupDescription", engine), "Managed by CloudFormation"); - List subnetIds = new ArrayList<>(); - if (props != null && props.has("SubnetIds") && props.get("SubnetIds").isArray()) { - for (JsonNode subnet : props.get("SubnetIds")) { - subnetIds.add(engine.resolve(subnet)); - } - } + // SubnetIds may be a literal array, or a list-valued intrinsic — e.g. CDK's + // Fn::Split over a cross-stack Fn::ImportValue when the source VPC exports its + // subnet ids as one comma-joined value (issue #2937). + List subnetIds = props != null && props.has("SubnetIds") + ? engine.resolveStringList(props.get("SubnetIds")) + : new ArrayList<>(); // On UpdateStack, provision() is re-invoked for every resource regardless of whether its // properties actually changed, so a same-named group already on file must be reconciled in diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java index 22e0fa0c9b..19a68b5bf1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java @@ -270,10 +270,7 @@ public class CloudFormationTemplateEngine { return out; } if (node.isArray()) { - for (JsonNode item : node) { - out.add(resolve(item)); - } - return out; + return resolveListElements(node); } if (node.isObject()) { if (node.has("Fn::GetAZs")) { @@ -285,6 +282,14 @@ 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()) { @@ -293,6 +298,74 @@ public class CloudFormationTemplateEngine { return out; } + /** + * Expands a literal array's elements, recursing into any element that is itself a + * list-valued intrinsic ({@code Fn::Split}, {@code Fn::GetAZs}, {@code Fn::Cidr}, or an + * {@code Fn::If} evaluating to one) so it contributes its own elements rather than one + * comma-joined string. Unlike {@link #resolveStringList}, this keeps blank entries: a + * literal array is positional (consumed by {@code Fn::Select} via {@link #resolveList}), + * so dropping a blank element ahead of the selected index would shift every later index. + */ + private List resolveListElements(JsonNode node) { + List out = new ArrayList<>(); + for (JsonNode element : node) { + if (isListValuedIntrinsic(element)) { + out.addAll(resolveList(element)); + } else { + out.add(resolve(element)); + } + } + return out; + } + + /** + * Resolves a node to a flat list of strings, expanding list-valued intrinsics + * ({@code Fn::Split}, {@code Fn::GetAZs}, {@code Fn::Cidr}, or an {@code Fn::If} evaluating + * to one) whether the node itself is one or they appear as elements of a literal array, + * and dropping blank entries. + * + *

Provisioners read list properties (SubnetIds, VPCZoneIdentifier, …) with this so a + * cross-stack {@code Fn::Split} over {@code Fn::ImportValue} — the shape CDK emits when a + * VPC exports its subnet ids as one comma-joined value — resolves to the real ids instead + * of a single comma-joined string or an empty list (issue #2937). + */ + public List resolveStringList(JsonNode node) { + List out = new ArrayList<>(); + if (node == null || node.isNull() || node.isMissingNode()) { + return out; + } + if (node.isArray()) { + out.addAll(resolveListElements(node)); + } else { + out.addAll(resolveList(node)); + } + out.removeIf(value -> value == null || value.isBlank()); + return out; + } + + private boolean isListValuedIntrinsic(JsonNode node) { + if (node == null) { + return false; + } + if (node.isArray()) { + return true; + } + if (node.isObject()) { + if (node.has("Fn::Split") || node.has("Fn::GetAZs") || node.has("Fn::Cidr")) { + return true; + } + 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 isListValuedIntrinsic(condValue ? ifNode.get(1) : ifNode.get(2)); + } + } + } + return false; + } + private List resolveSplit(JsonNode split) { if (!split.isArray() || split.size() < 2) { return List.of(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java index dd33a20961..fa617a92a5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java @@ -80,18 +80,20 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio return engine.resolve(props.get(name)); } - /** Resolves an array property to its non-blank elements, or an empty list when absent. */ + /** + * Resolves a list property to its non-blank elements, or an empty list when absent. + * + *

Routes through {@code engine.resolveStringList} so a list-valued intrinsic + * ({@code Fn::Split} / {@code Fn::GetAZs} / {@code Fn::Cidr}, including one selected by an + * {@code Fn::If}) expands to its real values instead of collapsing to a single comma-joined + * string — the shape CDK emits for cross-stack references (issue #2937). Kept in lockstep + * with the monolith helper the per-service provisioners were split from. + */ public List resolveStringList(JsonNode props, String name) { - List values = new ArrayList<>(); - if (props != null && props.has(name) && props.get(name).isArray()) { - for (JsonNode element : props.get(name)) { - String resolved = engine.resolve(element); - if (resolved != null && !resolved.isBlank()) { - values.add(resolved); - } - } + if (props == null || !props.has(name)) { + return new ArrayList<>(); } - return values; + return new ArrayList<>(engine.resolveStringList(props.get(name))); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index 136a30a8b7..d1064998f0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -5264,8 +5264,18 @@ public class RdsService implements Resettable, ResourceProvider { private DbSubnetGroup buildSubnetGroup(String name, String description, List subnetIds, String region) { List resolvedSubnets = ec2Service.describeSubnets(region, subnetIds, Map.of()); if (resolvedSubnets.size() != subnetIds.size()) { + Set found = resolvedSubnets.stream() + .map(Subnet::getSubnetId) + .collect(java.util.stream.Collectors.toSet()); + List missing = subnetIds.stream() + .filter(id -> !found.contains(id)) + .distinct() + .toList(); + String detail = missing.isEmpty() + ? " do not exist." + : " do not exist: " + missing + "."; throw new AwsException("InvalidSubnet", - "One or more subnets for DB subnet group " + name + " do not exist.", 400); + "One or more subnets for DB subnet group " + name + detail, 400); } String vpcId = resolvedSubnets.getFirst().getVpcId(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java index 9e7b5a077a..cf14c2a7f1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java @@ -60,6 +60,19 @@ class CloudFormationTemplateEngineTest { engine().resolve(json("{\"Fn::Select\": [2, {\"Fn::Cidr\": [\"10.0.0.0/16\", 4, 8]}]}"))); } + /** + * Fn::Select is positional: a blank entry ahead of the selected index is still a real list + * element and must not shift the elements after it, unlike resolveStringList's provisioner- + * facing contract of dropping blanks (issue found in PR #2946 review). + */ + @Test + void selectFromLiteralArrayKeepsBlankEntriesAtTheirPosition() { + CloudFormationTemplateEngine e = engine(); + assertEquals("", e.resolve(json("{\"Fn::Select\": [0, [\"\", \"subnet-b\", \"subnet-c\"]]}"))); + assertEquals("subnet-b", e.resolve(json("{\"Fn::Select\": [1, [\"\", \"subnet-b\", \"subnet-c\"]]}"))); + assertEquals("subnet-c", e.resolve(json("{\"Fn::Select\": [2, [\"\", \"subnet-b\", \"subnet-c\"]]}"))); + } + @Test void resolveJsonAttributeUnwrapsAlreadySerializedStringFromFnJoin() { // Reproduces #2317: CDK emits RedrivePolicy / FilterPolicy / Definition as an Fn::Join @@ -88,4 +101,103 @@ class CloudFormationTemplateEngineTest { assertNull(engine().resolveJsonAttribute(json("null"))); assertNull(engine().resolveJsonAttribute(mapper.createArrayNode().path("nope"))); } + + @Test + void resolveStringListSplitsListValuedIntrinsicNode() { + CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000", + "us-east-1", "my-stack", "stack/id", Map.of(), Map.of(), Map.of(), Map.of(), + Map.of(), mapper, (Function) name -> + "Subnets".equals(name) ? "subnet-a,subnet-b" : null); + + assertEquals(java.util.List.of("subnet-a", "subnet-b"), + e.resolveStringList(json("{\"Fn::Split\":[\",\",{\"Fn::ImportValue\":\"Subnets\"}]}"))); + } + + @Test + void resolveStringListFlattensListValuedArrayElements() { + CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000", + "us-east-1", "my-stack", "stack/id", Map.of(), Map.of(), Map.of(), Map.of(), + Map.of(), mapper, (Function) name -> + "Subnets".equals(name) ? "subnet-a,subnet-b" : null); + + assertEquals(java.util.List.of("subnet-a", "subnet-b"), + e.resolveStringList(json( + "[{\"Fn::Split\":[\",\",{\"Fn::ImportValue\":\"Subnets\"}]}]"))); + } + + @Test + void resolveStringListKeepsLiteralArrayOfScalars() { + assertEquals(java.util.List.of("subnet-a", "subnet-b"), + engine().resolveStringList(json("[\"subnet-a\",\"subnet-b\"]"))); + } + + @Test + void resolveStringListDropsBlankEntries() { + assertEquals(java.util.List.of("subnet-a"), + engine().resolveStringList(json("[\"subnet-a\",\"\",\" \"]"))); + } + + @Test + void resolveStringListReturnsEmptyForNullOrMissing() { + assertEquals(java.util.List.of(), engine().resolveStringList(json("null"))); + assertEquals(java.util.List.of(), + engine().resolveStringList(mapper.createArrayNode().path("nope"))); + } + + @Test + void resolveStringListExpandsFnIfWithListValuedBranch() { + CloudFormationTemplateEngine eTrue = new CloudFormationTemplateEngine("000000000000", + "us-east-1", "my-stack", "stack/id", Map.of(), Map.of(), Map.of(), + Map.of("UseCustom", true), Map.of(), mapper, (Function) name -> + "Subnets".equals(name) ? "subnet-a,subnet-b" : null); + + assertEquals(java.util.List.of("subnet-a", "subnet-b"), + eTrue.resolveStringList(json("{\"Fn::If\":[\"UseCustom\",{\"Fn::Split\":[\",\",{\"Fn::ImportValue\":\"Subnets\"}]},\"subnet-default\"]}"))); + + CloudFormationTemplateEngine eFalse = new CloudFormationTemplateEngine("000000000000", + "us-east-1", "my-stack", "stack/id", Map.of(), Map.of(), Map.of(), + Map.of("UseCustom", false), Map.of(), mapper, (Function) name -> + "Subnets".equals(name) ? "subnet-a,subnet-b" : null); + + assertEquals(java.util.List.of("subnet-default"), + eFalse.resolveStringList(json("{\"Fn::If\":[\"UseCustom\",{\"Fn::Split\":[\",\",{\"Fn::ImportValue\":\"Subnets\"}]},\"subnet-default\"]}"))); + } + + @Test + void resolveStringListFlattensFnIfInsideArrayElements() { + CloudFormationTemplateEngine eTrue = new CloudFormationTemplateEngine("000000000000", + "us-east-1", "my-stack", "stack/id", Map.of(), Map.of(), Map.of(), + Map.of("UseCustom", true), Map.of(), mapper, (Function) name -> + "Subnets".equals(name) ? "subnet-a,subnet-b" : null); + + assertEquals(java.util.List.of("subnet-a", "subnet-b"), + eTrue.resolveStringList(json("[{\"Fn::If\":[\"UseCustom\",{\"Fn::Split\":[\",\",{\"Fn::ImportValue\":\"Subnets\"}]},\"subnet-default\"]}]"))); + + CloudFormationTemplateEngine eFalse = new CloudFormationTemplateEngine("000000000000", + "us-east-1", "my-stack", "stack/id", Map.of(), Map.of(), Map.of(), + Map.of("UseCustom", false), Map.of(), mapper, (Function) name -> + "Subnets".equals(name) ? "subnet-a,subnet-b" : null); + + assertEquals(java.util.List.of("subnet-default"), + eFalse.resolveStringList(json("[{\"Fn::If\":[\"UseCustom\",{\"Fn::Split\":[\",\",{\"Fn::ImportValue\":\"Subnets\"}]},\"subnet-default\"]}]"))); + } + + @Test + void resolveStringListExpandsFnIfSelectingArrayWithNestedSplit() { + CloudFormationTemplateEngine eTrue = new CloudFormationTemplateEngine("000000000000", + "us-east-1", "my-stack", "stack/id", Map.of(), Map.of(), Map.of(), + Map.of("UseCustom", true), Map.of(), mapper, (Function) name -> + "Subnets".equals(name) ? "subnet-a,subnet-b" : null); + + assertEquals(java.util.List.of("subnet-prefix", "subnet-a", "subnet-b"), + eTrue.resolveStringList(json("{\"Fn::If\":[\"UseCustom\",[\"subnet-prefix\",{\"Fn::Split\":[\",\",{\"Fn::ImportValue\":\"Subnets\"}]}],[\"subnet-default\"]]}"))); + + CloudFormationTemplateEngine eFalse = new CloudFormationTemplateEngine("000000000000", + "us-east-1", "my-stack", "stack/id", Map.of(), Map.of(), Map.of(), + Map.of("UseCustom", false), Map.of(), mapper, (Function) name -> + "Subnets".equals(name) ? "subnet-a,subnet-b" : null); + + assertEquals(java.util.List.of("subnet-default"), + eFalse.resolveStringList(json("{\"Fn::If\":[\"UseCustom\",[\"subnet-prefix\",{\"Fn::Split\":[\",\",{\"Fn::ImportValue\":\"Subnets\"}]}],[\"subnet-default\"]]}"))); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java index 868b1f4ee6..9224b2b656 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java @@ -58,12 +58,16 @@ class RdsCfnProvisionerTest { private SecretsManagerService secretsManagerService; private SsmService ssmService; private CloudFormationResourceProvisioner provisioner; + private Function importResolver; + private Map conditions; @BeforeEach void setUp() { rdsService = mock(RdsService.class); secretsManagerService = mock(SecretsManagerService.class); ssmService = mock(SsmService.class); + importResolver = name -> null; + conditions = Map.of(); provisioner = CfnProvisionerFixture.builder() .ssm(ssmService) .secretsManager(secretsManagerService) @@ -74,8 +78,8 @@ class RdsCfnProvisionerTest { private CloudFormationTemplateEngine engine() { return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack", - "stack/id", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper, - (Function) name -> null); + "stack/id", Map.of(), Map.of(), Map.of(), conditions, Map.of(), mapper, + importResolver); } private JsonNode props(String json) { @@ -836,6 +840,88 @@ class RdsCfnProvisionerTest { List.of("subnet-a"), "us-west-2"); } + /** + * Repro for issue #2937: a CDK cross-stack VPC exposes its subnet ids as one comma-joined + * export, so the consuming stack passes {@code SubnetIds} as a list-valued intrinsic + * ({@code Fn::Split} over {@code Fn::ImportValue}) rather than a literal JSON array. The + * provisioner must still forward the two real subnet ids. + */ + @Test + void provisionsDbSubnetGroupFromCrossStackSplitImport() { + importResolver = name -> "VpcPrivateSubnetIds".equals(name) ? "subnet-a,subnet-b" : null; + DbSubnetGroup group = mock(DbSubnetGroup.class); + when(group.getDbSubnetGroupName()).thenReturn("my-subnet-group"); + when(rdsService.createDbSubnetGroup(any(), any(), anyList(), any())).thenReturn(group); + + provision("Sg", "AWS::RDS::DBSubnetGroup", """ + {"DBSubnetGroupName":"my-subnet-group", + "SubnetIds":{"Fn::Split":[",",{"Fn::ImportValue":"VpcPrivateSubnetIds"}]}} + """); + + verify(rdsService).createDbSubnetGroup("my-subnet-group", "Managed by CloudFormation", + List.of("subnet-a", "subnet-b"), "us-east-1"); + } + + /** + * Repro for issue #2937: when {@code SubnetIds} is a literal array whose {@code Fn::Select} + * index runs past the imported list, the element resolves to "" and must be dropped rather + * than forwarded as a phantom id that {@code describeSubnets} then reports as non-existent. + */ + @Test + void provisionsDbSubnetGroupDropsBlankResolvedSubnetIds() { + importResolver = name -> "VpcPrivateSubnetIds".equals(name) ? "subnet-a,subnet-b" : null; + DbSubnetGroup group = mock(DbSubnetGroup.class); + when(group.getDbSubnetGroupName()).thenReturn("my-subnet-group"); + when(rdsService.createDbSubnetGroup(any(), any(), anyList(), any())).thenReturn(group); + + provision("Sg", "AWS::RDS::DBSubnetGroup", """ + {"DBSubnetGroupName":"my-subnet-group","SubnetIds":[ + {"Fn::Select":[0,{"Fn::Split":[",",{"Fn::ImportValue":"VpcPrivateSubnetIds"}]}]}, + {"Fn::Select":[5,{"Fn::Split":[",",{"Fn::ImportValue":"VpcPrivateSubnetIds"}]}]}]} + """); + + verify(rdsService).createDbSubnetGroup("my-subnet-group", "Managed by CloudFormation", + List.of("subnet-a"), "us-east-1"); + } + + /** + * Repro for issue #2937: an array element that is itself a list-valued intrinsic + * ({@code Fn::Split}) collapses to one comma-joined string under scalar resolution, which + * {@code describeSubnets} then cannot match — surfacing as "subnets do not exist". + */ + @Test + void provisionsDbSubnetGroupExpandsSplitElementInsideArray() { + importResolver = name -> "VpcPrivateSubnetIds".equals(name) ? "subnet-a,subnet-b" : null; + DbSubnetGroup group = mock(DbSubnetGroup.class); + when(group.getDbSubnetGroupName()).thenReturn("my-subnet-group"); + when(rdsService.createDbSubnetGroup(any(), any(), anyList(), any())).thenReturn(group); + + provision("Sg", "AWS::RDS::DBSubnetGroup", """ + {"DBSubnetGroupName":"my-subnet-group","SubnetIds":[ + {"Fn::Split":[",",{"Fn::ImportValue":"VpcPrivateSubnetIds"}]}]} + """); + + verify(rdsService).createDbSubnetGroup("my-subnet-group", "Managed by CloudFormation", + List.of("subnet-a", "subnet-b"), "us-east-1"); + } + + @Test + void provisionsDbSubnetGroupExpandsFnIfInsideArray() { + importResolver = name -> "VpcPrivateSubnetIds".equals(name) ? "subnet-a,subnet-b" : null; + conditions = Map.of("UseVpcSubnets", true); + DbSubnetGroup group = mock(DbSubnetGroup.class); + when(group.getDbSubnetGroupName()).thenReturn("my-subnet-group"); + when(rdsService.createDbSubnetGroup(any(), any(), anyList(), any())).thenReturn(group); + + provision("Sg", "AWS::RDS::DBSubnetGroup", """ + {"DBSubnetGroupName":"my-subnet-group","SubnetIds":[ + {"Fn::If":["UseVpcSubnets",{"Fn::Split":[",",{"Fn::ImportValue":"VpcPrivateSubnetIds"}]},"subnet-default"]}]} + """); + + verify(rdsService).createDbSubnetGroup("my-subnet-group", "Managed by CloudFormation", + List.of("subnet-a", "subnet-b"), "us-east-1"); + } + @Test void provisionsDbParameterGroup() { DbParameterGroup group = mock(DbParameterGroup.class); @@ -1195,4 +1281,26 @@ class RdsCfnProvisionerTest { "AWS::RDS::DBProxyTargetGroup", targetGroupArn, "us-east-1")); verify(rdsService).clearDbProxyTargetGroupByArn(targetGroupArn, "us-east-1"); } + + @Test + void provisionsDbProxyFromCrossStackSplitSubnetImport() { + importResolver = name -> "VpcSubnets".equals(name) ? "subnet-a,subnet-b" : null; + DbProxy proxy = mock(DbProxy.class); + when(proxy.getDbProxyName()).thenReturn("my-proxy"); + when(proxy.getDbProxyArn()).thenReturn("arn:aws:rds:us-east-1:000000000000:db-proxy:my-proxy"); + when(rdsService.createDbProxy(any(), any(), anyBoolean(), anyBoolean(), any(), any(), + anyList(), anyList(), anyList(), anyInt(), anyBoolean(), anyMap(), any())).thenReturn(proxy); + + provision("Proxy", "AWS::RDS::DBProxy", """ + {"DBProxyName":"my-proxy","EngineFamily":"POSTGRESQL", + "RoleArn":"arn:aws:iam::000000000000:role/proxy", + "Auth":[{"AuthScheme":"SECRETS","SecretArn":"arn:aws:secretsmanager:us-east-1:000000000000:secret:db"}], + "VpcSubnetIds":{"Fn::Split":[",",{"Fn::ImportValue":"VpcSubnets"}]}} + """); + + ArgumentCaptor> subnets = ArgumentCaptor.forClass(List.class); + verify(rdsService).createDbProxy(eq("my-proxy"), eq("POSTGRESQL"), anyBoolean(), anyBoolean(), + any(), any(), subnets.capture(), anyList(), anyList(), anyInt(), anyBoolean(), anyMap(), any()); + assertEquals(List.of("subnet-a", "subnet-b"), subnets.getValue()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AcmCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AcmCfnProvisionerTest.java index e1c92dbac9..ca377466ea 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AcmCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AcmCfnProvisionerTest.java @@ -54,6 +54,9 @@ class AcmCfnProvisionerTest { return node == null || node.isMissingNode() || node.isNull() ? null : node.asText(); }); when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + // resolveStringList delegates to the real engine method; for the literal arrays these + // tests use it just walks the array and calls resolve(...) per element, stubbed above. + when(engine.resolveStringList(any())).thenCallRealMethod(); return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java index 140057bf23..bca004c66e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java @@ -53,6 +53,10 @@ class IamRoleCfnProvisionerTest { when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + // resolveStringList delegates to the real engine method; for the literal arrays these + // tests use it just walks the array and calls resolve(...) per element, stubbed above. + when(engine.resolveStringList(any())).thenCallRealMethod(); + when(engine.resolveJsonAttribute(any())).thenAnswer(inv -> { JsonNode node = inv.getArgument(0); return node != null && node.isTextual() ? node.asText() : node.toString(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OrganizationsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OrganizationsCfnProvisionerTest.java index fd7912cb49..26d8e7f6a1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OrganizationsCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OrganizationsCfnProvisionerTest.java @@ -62,6 +62,9 @@ class OrganizationsCfnProvisionerTest { return node == null ? null : node.asText(); }); when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + // resolveStringList delegates to the real engine method; for the literal arrays these + // tests use it just walks the array and calls resolve(...) per element, stubbed above. + when(engine.resolveStringList(any())).thenCallRealMethod(); when(engine.resolveJsonAttribute(any())).thenAnswer(inv -> { JsonNode node = inv.getArgument(0); return node.isTextual() ? node.asText() : node.toString(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java index 0d8ea5a427..a9fd815b8e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java @@ -15,6 +15,8 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** The shared helpers on {@link ProvisionContext} that extracted provisioners build on. */ @@ -178,6 +180,37 @@ class ProvisionContextTest { } + /** + * The whole property node is handed to {@code engine.resolveStringList}, so a list-valued + * intrinsic ({@code Fn::Split} over a cross-stack {@code Fn::ImportValue}) expands to its real + * values instead of collapsing to one comma-joined string (issue #2937). Resolving each element + * in isolation, as the old copy did, would have yielded a single unusable entry. + */ + @Test + void resolveStringListRoutesListValuedIntrinsicsThroughTheEngine() { + JsonNode props = props(""" + { + "SubnetIds": { + "Fn::Split": [",", {"Fn::ImportValue": "vpc-stack:PrivateSubnetIds"}] + } + } + """); + when(engine.resolveStringList(props.get("SubnetIds"))) + .thenReturn(List.of("subnet-a", "subnet-b", "subnet-c")); + + assertEquals(List.of("subnet-a", "subnet-b", "subnet-c"), + context(null).resolveStringList(props, "SubnetIds")); + } + + @Test + void resolveStringListReturnsAMutableEmptyListForAnAbsentPropertyWithoutCallingTheEngine() { + List values = context(null).resolveStringList(props("{}"), "ManagedPolicyArns"); + + assertEquals(List.of(), values); + values.add("still-mutable"); + verify(engine, never()).resolveStringList(any()); + } + @Test void staleTagKeysListsTheCurrentKeysTheTemplateDropped() { Map current = new java.util.LinkedHashMap<>(); diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java index 1212f54bd8..4d4582828c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java @@ -5059,6 +5059,21 @@ class RdsServiceTest { rdsService.getDbSubnetGroup("tagged", "us-east-1").getTags()); } + @Test + void createDbSubnetGroupErrorNamesMissingSubnetIds() { + String subnetA = "subnet-default-a"; + + AwsException ex = assertThrows(AwsException.class, () -> + rdsService.createDbSubnetGroup("grp", "desc", + List.of(subnetA, "subnet-missing"), "us-east-1")); + + assertEquals("InvalidSubnet", ex.getErrorCode()); + assertTrue(ex.getMessage().contains("subnet-missing"), + "message should name the missing id, was: " + ex.getMessage()); + assertFalse(ex.getMessage().contains(subnetA), + "message should not list the id that does exist, was: " + ex.getMessage()); + } + @Test void createDbInstanceKeepsTheEngineNameTheRequestGave() { rdsService.createDbCluster("aurora", "aurora-postgresql", null, "admin", "secret99password",