mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(cloudformation): preserve numeric GetAtt attributes (#6564)
This commit is contained in:
1 parent
47226f76d1
commit
d903074d75
8 files changed
+401
-20
No files matched your search
@@ -646,6 +646,13 @@ when it starts with `{` and ends with `}`, and `Template format error: YAML not
|
||||
L, column C)` otherwise, at the position where the parser stopped. A body that reads as a scalar or
|
||||
a list is `Template format error: unsupported structure.`
|
||||
|
||||
## Attribute types
|
||||
|
||||
`AWS::EC2::PrefixList` `Version` remains numeric when used as another resource's property.
|
||||
Numeric attributes are rejected in string outputs and `Fn::Join`, `Fn::Sub`,
|
||||
`Fn::Split`, and `Fn::Base64`, including selected `Fn::If` and `Fn::Select` values.
|
||||
Literal numbers and Number-parameter references retain their existing string coercion.
|
||||
|
||||
## Null values
|
||||
|
||||
As on AWS, a template holding a `null` anywhere (JSON `null`, YAML `~` or a key with no value) is
|
||||
|
||||
+8
-9
@@ -2021,7 +2021,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
value -> dynamicReferences.resolveDynamicReferences(value, region, false),
|
||||
(name, output, outputRegion, roleArn) ->
|
||||
resolveStackOutput(accountId, name, output, outputRegion, roleArn),
|
||||
parameterTypes);
|
||||
parameterTypes,
|
||||
(id, attribute, value) -> dispatcher.attributeValue(
|
||||
resources.path(id).path("Type").asText(), attribute, value));
|
||||
|
||||
StackResource resource = stack.getResources().get(logicalId);
|
||||
StackResource previousResource = resource;
|
||||
@@ -2192,7 +2194,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
value -> dynamicReferences.resolveDynamicReferences(value, region, false),
|
||||
(name, output, outputRegion, roleArn) ->
|
||||
resolveStackOutput(accountId, name, output, outputRegion, roleArn),
|
||||
parameterTypes);
|
||||
parameterTypes,
|
||||
(id, attribute, value) -> dispatcher.attributeValue(
|
||||
resources.path(id).path("Type").asText(), attribute, value));
|
||||
|
||||
// Resolve outputs before mutating stack/global export state, so failed updates do not
|
||||
// leave stale or partially registered exports behind.
|
||||
@@ -2212,14 +2216,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
Map<String, String> outputValues = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, JsonNode> output : outputs.entrySet()) {
|
||||
try {
|
||||
outputValues.put(output.getKey(), finalEngine.resolve(output.getValue().path("Value")));
|
||||
outputValues.put(output.getKey(), finalEngine.resolveString(output.getValue().path("Value"),
|
||||
"Template format error: Every Value member must be a string."));
|
||||
} catch (AwsException e) {
|
||||
if (!CloudFormationTemplateEngine.containsGetStackOutput(output.getValue())) {
|
||||
throw e;
|
||||
}
|
||||
// An output whose Fn::GetStackOutput cannot be read fails the operation once the
|
||||
// resources exist, and the stack rolls back as for a resource that failed
|
||||
// (measured: a create deletes them and ends ROLLBACK_COMPLETE).
|
||||
LOG.warnv("Stack {0} output {1} failed: {2}", stack.getStackName(), output.getKey(),
|
||||
e.getMessage());
|
||||
rollbackFailedExecution(stack, region, isCreate, e.getMessage(), previousState,
|
||||
|
||||
+134
-11
@@ -58,6 +58,11 @@ public class CloudFormationTemplateEngine {
|
||||
*/
|
||||
public static final String SERVICE_DISABLED_ATTR = "__FlociServiceDisabled";
|
||||
|
||||
@FunctionalInterface
|
||||
public interface AttributeValueResolver {
|
||||
JsonNode resolve(String logicalId, String attributeName, String value);
|
||||
}
|
||||
|
||||
private final String accountId;
|
||||
private final String region;
|
||||
private final String stackName;
|
||||
@@ -72,6 +77,7 @@ public class CloudFormationTemplateEngine {
|
||||
private final UnaryOperator<String> dynamicReferenceResolver;
|
||||
private final StackOutputResolver stackOutputResolver;
|
||||
private final Map<String, String> parameterTypes;
|
||||
private final AttributeValueResolver attributeValueResolver;
|
||||
private final List<String> unresolvedIntrinsics = new ArrayList<>();
|
||||
/**
|
||||
* Above zero while {@code Fn::GetStackOutput}'s arguments resolve: CloudFormation hands them on
|
||||
@@ -163,6 +169,23 @@ public class CloudFormationTemplateEngine {
|
||||
UnaryOperator<String> dynamicReferenceResolver,
|
||||
StackOutputResolver stackOutputResolver,
|
||||
Map<String, String> parameterTypes) {
|
||||
this(accountId, region, stackName, stackId, parameters, physicalIds, resourceAttributes,
|
||||
conditions, mappings, objectMapper, importValueResolver, dynamicReferenceResolver,
|
||||
stackOutputResolver, parameterTypes, (logicalId, attributeName, value) -> TextNode.valueOf(value));
|
||||
}
|
||||
|
||||
CloudFormationTemplateEngine(String accountId, String region, String stackName, String stackId,
|
||||
Map<String, String> parameters,
|
||||
Map<String, String> physicalIds,
|
||||
Map<String, Map<String, String>> resourceAttributes,
|
||||
Map<String, Boolean> conditions,
|
||||
Map<String, JsonNode> mappings,
|
||||
ObjectMapper objectMapper,
|
||||
Function<String, String> importValueResolver,
|
||||
UnaryOperator<String> dynamicReferenceResolver,
|
||||
StackOutputResolver stackOutputResolver,
|
||||
Map<String, String> parameterTypes,
|
||||
AttributeValueResolver attributeValueResolver) {
|
||||
this.accountId = accountId;
|
||||
this.region = region;
|
||||
this.stackName = stackName;
|
||||
@@ -177,6 +200,7 @@ public class CloudFormationTemplateEngine {
|
||||
this.dynamicReferenceResolver = dynamicReferenceResolver;
|
||||
this.stackOutputResolver = stackOutputResolver;
|
||||
this.parameterTypes = parameterTypes;
|
||||
this.attributeValueResolver = attributeValueResolver;
|
||||
}
|
||||
|
||||
/** The id of the stack this engine resolves for, as {@code AWS::StackId} returns it. */
|
||||
@@ -195,6 +219,12 @@ public class CloudFormationTemplateEngine {
|
||||
return resolveDynamicReferences(resolveIntrinsic(node)).asText();
|
||||
}
|
||||
|
||||
/** Resolves a string-only context, preserving literal and parameter coercion. */
|
||||
public String resolveString(JsonNode node, String errorMessage) {
|
||||
requireStringAttribute(node, errorMessage);
|
||||
return resolve(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves intrinsics only, leaving any {@code {{resolve:...}}} dynamic reference syntax in the
|
||||
* result untouched. For the one property family where {@code ssm-secure} is a valid dynamic
|
||||
@@ -237,6 +267,8 @@ public class CloudFormationTemplateEngine {
|
||||
return resolveIf(node.get("Fn::If"));
|
||||
}
|
||||
if (node.has("Fn::Base64")) {
|
||||
requireStringAttribute(node.get("Fn::Base64"),
|
||||
"Template error: every Fn::Base64 object must have a String-typed value.");
|
||||
return Base64.getEncoder().encodeToString(resolve(node.get("Fn::Base64")).getBytes());
|
||||
}
|
||||
if (node.has("Fn::Split")) {
|
||||
@@ -287,6 +319,13 @@ public class CloudFormationTemplateEngine {
|
||||
if (node.has("Fn::Split") || node.has("Fn::GetAZs") || node.has("Fn::Cidr")) {
|
||||
return objectMapper.valueToTree(resolveList(node));
|
||||
}
|
||||
if (node.has("Fn::GetAtt")) {
|
||||
JsonNode attribute = resolveGetAttNode(node.get("Fn::GetAtt"));
|
||||
return attribute.isTextual() ? resolveDynamicReferences(attribute.textValue()) : attribute;
|
||||
}
|
||||
if (node.has("Fn::Select")) {
|
||||
return resolveNode(selectedElement(node.get("Fn::Select")));
|
||||
}
|
||||
if (callsIntrinsic(node)) {
|
||||
return TextNode.valueOf(resolve(node));
|
||||
}
|
||||
@@ -463,7 +502,12 @@ public class CloudFormationTemplateEngine {
|
||||
template = sub.get(0).textValue();
|
||||
JsonNode varMap = sub.get(1);
|
||||
if (varMap.isObject()) {
|
||||
varMap.fields().forEachRemaining(e -> vars.put(e.getKey(), resolve(e.getValue())));
|
||||
varMap.fields().forEachRemaining(e -> {
|
||||
requireStringAttribute(e.getValue(),
|
||||
"Template error: every value of the context object of every Fn::Sub object"
|
||||
+ " must be a string or a function that returns a string.");
|
||||
vars.put(e.getKey(), resolve(e.getValue()));
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return sub.asText();
|
||||
@@ -489,6 +533,10 @@ public class CloudFormationTemplateEngine {
|
||||
// Fn::GetAtt shorthand: ${LogicalId.Attr}. A logical id and a parameter name
|
||||
// are both alphanumeric, so a dot can only mean an attribute reference.
|
||||
String[] parts = varName.split("\\.", 2);
|
||||
JsonNode attribute = objectMapper.createArrayNode().add(parts[0]).add(parts[1]);
|
||||
requireStringAttribute(objectMapper.createObjectNode().set("Fn::GetAtt", attribute),
|
||||
"Template error: variable " + varName
|
||||
+ " in Fn::Sub expression does not resolve to a string.");
|
||||
result.append(resolveGetAttParts(parts[0], parts.length > 1 ? parts[1] : ""));
|
||||
} else {
|
||||
result.append(resolveRef(varName));
|
||||
@@ -507,6 +555,10 @@ public class CloudFormationTemplateEngine {
|
||||
return "";
|
||||
}
|
||||
String delimiter = join.get(0).asText("");
|
||||
requireStringAttribute(join.get(1),
|
||||
"Template error: every Fn::Join object requires two parameters, (1) a string delimiter"
|
||||
+ " and (2) a list of strings to be joined or a function that returns a list"
|
||||
+ " of strings (such as Fn::GetAZs) to be joined.");
|
||||
// CDK splices a dynamic reference across fragments, for example
|
||||
// ["{{resolve:secretsmanager:", {"Ref": "Secret"}, ":SecretString:password::}}"], so the
|
||||
// fragments are only intrinsic-resolved here and the caller resolves dynamic references on
|
||||
@@ -514,16 +566,61 @@ public class CloudFormationTemplateEngine {
|
||||
return String.join(delimiter, resolveList(join.get(1), false));
|
||||
}
|
||||
|
||||
private void requireStringAttribute(JsonNode node, String message) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
if (node.has("Fn::GetAtt") && !isStringAttribute(node.get("Fn::GetAtt"))) {
|
||||
throw new AwsException("ValidationError", message, 400);
|
||||
}
|
||||
if (node.has("Fn::If")) {
|
||||
requireStringAttribute(selectIfBranch(node.get("Fn::If")), message);
|
||||
} else if (node.has("Fn::Select")) {
|
||||
requireStringAttribute(selectedElement(node.get("Fn::Select")), message);
|
||||
} else if (node.isArray()) {
|
||||
node.forEach(item -> requireStringAttribute(item, message));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isStringAttribute(JsonNode getAtt) {
|
||||
String[] parts = getAttParts(getAtt);
|
||||
if (parts == null) {
|
||||
return true;
|
||||
}
|
||||
Map<String, String> attributes = findAttributeSource(parts[0], parts[1]);
|
||||
return attributes == null
|
||||
|| attributeValueResolver.resolve(parts[0], parts[1], attributes.get(parts[1])).isTextual();
|
||||
}
|
||||
|
||||
private String resolveSelect(JsonNode select) {
|
||||
return resolve(selectedElement(select));
|
||||
}
|
||||
|
||||
private JsonNode selectedElement(JsonNode select) {
|
||||
if (!select.isArray() || select.size() < 2) {
|
||||
return "";
|
||||
return TextNode.valueOf("");
|
||||
}
|
||||
int index = parseInt(resolve(select.get(0)), 0);
|
||||
List<String> items = resolveList(select.get(1));
|
||||
JsonNode source = select.get(1);
|
||||
while (source != null && source.has("Fn::If")) {
|
||||
source = selectIfBranch(source.get("Fn::If"));
|
||||
}
|
||||
List<JsonNode> items = new ArrayList<>();
|
||||
if (source != null && source.isArray()) {
|
||||
for (JsonNode element : source) {
|
||||
if (isListValuedIntrinsic(element)) {
|
||||
resolveList(element).forEach(value -> items.add(TextNode.valueOf(value)));
|
||||
} else {
|
||||
items.add(element);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
resolveList(source).forEach(value -> items.add(TextNode.valueOf(value)));
|
||||
}
|
||||
if (index >= 0 && index < items.size()) {
|
||||
return items.get(index);
|
||||
}
|
||||
return "";
|
||||
return TextNode.valueOf("");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -695,6 +792,8 @@ public class CloudFormationTemplateEngine {
|
||||
if (!split.isArray() || split.size() < 2) {
|
||||
return List.of();
|
||||
}
|
||||
requireStringAttribute(split.get(1), "Template error: every Fn::Split object requires two parameters, "
|
||||
+ "(1) a string delimiter and (2) a string to be split or a function that returns a string to be split.");
|
||||
String delimiter = resolve(split.get(0));
|
||||
String source = resolve(split.get(1));
|
||||
if (delimiter.isEmpty()) {
|
||||
@@ -789,22 +888,46 @@ public class CloudFormationTemplateEngine {
|
||||
}
|
||||
|
||||
private String resolveGetAtt(JsonNode getAtt) {
|
||||
return resolveGetAttNode(getAtt).asText();
|
||||
}
|
||||
|
||||
private JsonNode resolveGetAttNode(JsonNode getAtt) {
|
||||
String[] parts = getAttParts(getAtt);
|
||||
return parts == null ? TextNode.valueOf("") : resolveGetAttNodeParts(parts[0], parts[1]);
|
||||
}
|
||||
|
||||
private static String[] getAttParts(JsonNode getAtt) {
|
||||
if (getAtt.isArray() && getAtt.size() == 2) {
|
||||
return resolveGetAttParts(getAtt.get(0).asText(), getAtt.get(1).asText());
|
||||
return new String[] {getAtt.get(0).asText(), getAtt.get(1).asText()};
|
||||
}
|
||||
if (getAtt.isTextual()) {
|
||||
String[] parts = getAtt.textValue().split("\\.", 2);
|
||||
return resolveGetAttParts(parts[0], parts.length > 1 ? parts[1] : "");
|
||||
return new String[] {parts[0], parts.length > 1 ? parts[1] : ""};
|
||||
}
|
||||
return "";
|
||||
return null;
|
||||
}
|
||||
|
||||
private Map<String, String> findAttributeSource(String logicalId, String attrName) {
|
||||
Map<String, String> attributes = resourceAttributes.get(logicalId);
|
||||
// Provisioners keep private state under __Floci keys; AWS resolves no such attribute.
|
||||
return attributes != null && attributes.containsKey(attrName) && !attrName.startsWith("__Floci")
|
||||
? attributes : null;
|
||||
}
|
||||
|
||||
private JsonNode resolveGetAttNodeParts(String logicalId, String attrName) {
|
||||
String value = resolveGetAttParts(logicalId, attrName);
|
||||
if (findAttributeSource(logicalId, attrName) != null) {
|
||||
return attributeValueResolver.resolve(logicalId, attrName, value);
|
||||
}
|
||||
return TextNode.valueOf(value);
|
||||
}
|
||||
|
||||
private String resolveGetAttParts(String logicalId, String attrName) {
|
||||
Map<String, String> attrs = resourceAttributes.get(logicalId);
|
||||
// Provisioners keep private state under __Floci keys; AWS resolves no such attribute.
|
||||
if (attrs != null && attrs.containsKey(attrName) && !attrName.startsWith("__Floci")) {
|
||||
return attrs.get(attrName);
|
||||
Map<String, String> attributes = findAttributeSource(logicalId, attrName);
|
||||
if (attributes != null) {
|
||||
return attributes.get(attrName);
|
||||
}
|
||||
Map<String, String> attrs = resourceAttributes.get(logicalId);
|
||||
if (attrs != null && attrs.containsKey(SERVICE_DISABLED_ATTR)) {
|
||||
throw new AwsException("ValidationError", "Template error: " + logicalId
|
||||
+ " was stubbed because its service is disabled, so attribute " + attrName
|
||||
|
||||
+7
@@ -58,6 +58,13 @@ public class CfnResourceDispatcher {
|
||||
return registry.isCustomResourceType(resourceType);
|
||||
}
|
||||
|
||||
/** Resolve an attribute using its resource owner's declared type. */
|
||||
public JsonNode attributeValue(String resourceType, String attributeName, String value) {
|
||||
return registry.forType(resourceType)
|
||||
.map(owner -> owner.attributeValue(resourceType, attributeName, value))
|
||||
.orElseGet(() -> objectMapper.getNodeFactory().textNode(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Provisions a single resource and returns the populated StackResource (physical id and
|
||||
* attributes set).
|
||||
|
||||
+6
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
|
||||
@@ -21,6 +22,11 @@ public interface CfnResourceProvisioner {
|
||||
|
||||
Set<String> resourceTypes();
|
||||
|
||||
/** The JSON type of a stored GetAtt value; most resource attributes are strings. */
|
||||
default JsonNode attributeValue(String resourceType, String attributeName, String value) {
|
||||
return TextNode.valueOf(value);
|
||||
}
|
||||
|
||||
void provision(StackResource resource, JsonNode properties, ProvisionContext ctx);
|
||||
|
||||
/**
|
||||
|
||||
+9
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.LongNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.CidrCanonicalizer;
|
||||
@@ -86,6 +87,14 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
|
||||
SUBNET_ROUTE_TABLE_ASSOCIATION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonNode attributeValue(String resourceType, String attributeName, String value) {
|
||||
if (PREFIX_LIST.equals(resourceType) && "Version".equals(attributeName)) {
|
||||
return LongNode.valueOf(Long.parseLong(value));
|
||||
}
|
||||
return CfnResourceProvisioner.super.attributeValue(resourceType, attributeName, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
|
||||
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.CfnStackWaits;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationNumericAttributeIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261020/us-east-1/cloudformation/aws4_request";
|
||||
private static final String EC2_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261020/us-east-1/ec2/aws4_request";
|
||||
|
||||
@Test
|
||||
void aNumericGetAttCanConfigureAnotherResourcesNumericProperty() {
|
||||
String stack = "numeric-attribute-" + UUID.randomUUID();
|
||||
String template = """
|
||||
{"Parameters":{"Number":{"Type":"Number","Default":1}},
|
||||
"Resources":{"First":{"Type":"AWS::EC2::PrefixList","Properties":{
|
||||
"PrefixListName":"%1$s-first","AddressFamily":"IPv4","MaxEntries":1}},
|
||||
"Second":{"Type":"AWS::EC2::PrefixList","Properties":{
|
||||
"PrefixListName":"%1$s-second","AddressFamily":"IPv4",
|
||||
"MaxEntries":{"Fn::GetAtt":["First","Version"]}}}},
|
||||
"Outputs":{"Id":{"Value":{"Fn::GetAtt":["Second","PrefixListId"]}},
|
||||
"Arn":{"Value":{"Fn::Sub":"${Second.Arn}"}},
|
||||
"Literal":{"Value":1},"Parameter":{"Value":{"Ref":"Number"}},
|
||||
"Join":{"Value":{"Fn::Join":["",[1]]}},
|
||||
"SubMap":{"Value":{"Fn::Sub":["${Value}",{"Value":1}]}}}}
|
||||
""".formatted(stack);
|
||||
try {
|
||||
cloudFormation(stack, "CreateStack", template);
|
||||
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
|
||||
String prefixes = describePrefixLists();
|
||||
assertTrue(prefixes.contains(stack + "-second") && prefixes.contains("<maxEntries>1</maxEntries>"),
|
||||
prefixes);
|
||||
String described = given().contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH).formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stack).post("/").then().statusCode(200).extract().asString();
|
||||
Map<String, String> outputs = XmlParser.extractPairs(
|
||||
described, "Outputs", "OutputKey", "OutputValue");
|
||||
for (String key : new String[]{"Literal", "Parameter", "Join", "SubMap"}) {
|
||||
assertEquals("1", outputs.get(key), key);
|
||||
}
|
||||
} finally {
|
||||
deleteStack(stack);
|
||||
}
|
||||
assertFalse(describePrefixLists().contains(stack));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"{\"Fn::GetAtt\":[\"First\",\"Version\"]}",
|
||||
"{\"Fn::Join\":[\"\",[{\"Fn::GetAtt\":[\"First\",\"Version\"]}]]}",
|
||||
"{\"Fn::Sub\":\"${First.Version}\"}",
|
||||
"{\"Fn::Sub\":[\"${Value}\",{\"Value\":{\"Fn::GetAtt\":[\"First\",\"Version\"]}}]}",
|
||||
"{\"Fn::Join\":[\"\",[{\"Fn::Select\":[0,[{\"Fn::GetAtt\":[\"First\",\"Version\"]}]]}]]}",
|
||||
"{\"Fn::Select\":[0,{\"Fn::Split\":[\",\",{\"Fn::GetAtt\":[\"First\",\"Version\"]}]}]}",
|
||||
"{\"Fn::Base64\":{\"Fn::GetAtt\":[\"First\",\"Version\"]}}"
|
||||
})
|
||||
void numericStringOutputsFailAndRollBackOwnedResources(String value) {
|
||||
String stack = "numeric-output-" + UUID.randomUUID();
|
||||
String template = """
|
||||
{"Resources":{"First":{"Type":"AWS::EC2::PrefixList","Properties":{
|
||||
"PrefixListName":"%s","AddressFamily":"IPv4","MaxEntries":1}}},
|
||||
"Outputs":{"Version":{"Value":%s}}}
|
||||
""".formatted(stack, value);
|
||||
try {
|
||||
cloudFormation(stack, "CreateStack", template);
|
||||
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack, CFN_AUTH);
|
||||
assertEquals("ROLLBACK_COMPLETE", state.status(), state.reason());
|
||||
assertFalse(describePrefixLists().contains(stack));
|
||||
} finally {
|
||||
deleteStack(stack);
|
||||
}
|
||||
}
|
||||
|
||||
private static void cloudFormation(String stack, String action, String template) {
|
||||
RequestSpecification request = given().contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH).formParam("Action", action).formParam("StackName", stack);
|
||||
if (template != null) {
|
||||
request.formParam("TemplateBody", template);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void deleteStack(String stack) {
|
||||
cloudFormation(stack, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack, CFN_AUTH);
|
||||
}
|
||||
|
||||
private static String describePrefixLists() {
|
||||
return given().contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", EC2_AUTH).formParam("Action", "DescribeManagedPrefixLists")
|
||||
.formParam("Version", "2016-11-15")
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
}
|
||||
}
|
||||
+120
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkCfnProvisioner;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
@@ -57,6 +58,27 @@ class CloudFormationTemplateEngineTest {
|
||||
assertEquals("Thing.Missing", e.resolve(json("{\"Fn::GetAtt\": [\"Thing\", \"Missing\"]}")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"{\"Fn::Sub\":\"${Bucket.Missing}/*\"}",
|
||||
"{\"Fn::Join\":[\"\",[{\"Fn::GetAtt\":[\"Bucket\",\"Missing\"]},\"/*\"]]}",
|
||||
"{\"Fn::Sub\":[\"${Value}/*\",{\"Value\":{\"Fn::GetAtt\":\"Bucket.Missing\"}}]}",
|
||||
"{\"Fn::Base64\":{\"Fn::GetAtt\":\"Bucket.Missing\"}}",
|
||||
"{\"Fn::Split\":[\",\",{\"Fn::GetAtt\":\"Bucket.Missing\"}]}",
|
||||
"{\"Fn::Join\":[\"\",[{\"Fn::If\":[\"Absent\",\"unused\",{\"Fn::GetAtt\":\"Bucket.Missing\"}]}]]}",
|
||||
"{\"Fn::Join\":[\"\",[{\"Fn::Select\":[0,[{\"Fn::GetAtt\":\"Bucket.Missing\"}]]}]]}"
|
||||
})
|
||||
void stringTypeChecksRecordMissingAttributesOnce(String intrinsic) {
|
||||
CloudFormationTemplateEngine e = engineWithAttributes(Map.of("Bucket", Map.of("Arn", "bucket-arn")));
|
||||
JsonNode policy = mapper.createObjectNode().set("Resource", json(intrinsic));
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> e.resolveJsonAttributeStrict(policy));
|
||||
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
assertEquals("Policy document contains unresolved CloudFormation intrinsics: Fn::GetAtt Bucket.Missing. "
|
||||
+ "Storing them would silently void the statements that use them.", failure.getMessage());
|
||||
}
|
||||
|
||||
private JsonNode json(String s) {
|
||||
try {
|
||||
return mapper.readTree(s);
|
||||
@@ -65,6 +87,72 @@ class CloudFormationTemplateEngineTest {
|
||||
}
|
||||
}
|
||||
|
||||
private CloudFormationTemplateEngine engineWithNumericAttribute() {
|
||||
Ec2NetworkCfnProvisioner provisioner = new Ec2NetworkCfnProvisioner(null);
|
||||
return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack", "stack/id",
|
||||
Map.of(), Map.of(), Map.of("Prefix", Map.of("Version", "1", "PrefixListId", "pl-example")),
|
||||
Map.of("Include", true), Map.of(), mapper, name -> null, null, null, Map.of(),
|
||||
(id, attribute, value) -> provisioner.attributeValue("AWS::EC2::PrefixList", attribute, value));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"{\"Fn::GetAtt\":[\"Prefix\",\"Version\"]}",
|
||||
"{\"Fn::GetAtt\":\"Prefix.Version\"}",
|
||||
"{\"Fn::If\":[\"Include\",{\"Fn::GetAtt\":[\"Prefix\",\"Version\"]},0]}",
|
||||
"{\"Fn::Select\":[0,[{\"Fn::GetAtt\":[\"Prefix\",\"Version\"]}]]}"
|
||||
})
|
||||
void getAttPreservesItsNumericType(String intrinsic) {
|
||||
JsonNode result = engineWithNumericAttribute().resolveNode(json(intrinsic));
|
||||
assertTrue(result.isIntegralNumber());
|
||||
assertEquals(1, result.intValue());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"{\"Fn::Join\":[\"\",[{\"Fn::GetAtt\":[\"Prefix\",\"Version\"]}]]}",
|
||||
"{\"Fn::Join\":[\"\",[{\"Fn::If\":[\"Include\",{\"Fn::GetAtt\":[\"Prefix\",\"Version\"]},\"ok\"]}]]}",
|
||||
"{\"Fn::Sub\":\"${Prefix.Version}\"}",
|
||||
"{\"Fn::Sub\":[\"${Version}\",{\"Version\":{\"Fn::GetAtt\":[\"Prefix\",\"Version\"]}}]}",
|
||||
"{\"Fn::Join\":[\"\",[{\"Fn::Select\":[0,[{\"Fn::GetAtt\":[\"Prefix\",\"Version\"]}]]}]]}",
|
||||
"{\"Fn::Select\":[0,{\"Fn::Split\":[\",\",{\"Fn::GetAtt\":[\"Prefix\",\"Version\"]}]}]}",
|
||||
"{\"Fn::Base64\":{\"Fn::GetAtt\":[\"Prefix\",\"Version\"]}}"
|
||||
})
|
||||
void numericAttributesCannotBeUsedAsStringFragments(String intrinsic) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> engineWithNumericAttribute().resolve(json(intrinsic)));
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"{\"Fn::Join\":[\"\",[{\"Fn::GetAtt\":[\"Prefix\",\"PrefixListId\"]}]]}",
|
||||
"{\"Fn::Sub\":\"${Prefix.PrefixListId}\"}",
|
||||
"{\"Fn::Sub\":[\"${Id}\",{\"Id\":{\"Fn::GetAtt\":[\"Prefix\",\"PrefixListId\"]}}]}",
|
||||
"{\"Fn::Select\":[0,{\"Fn::Split\":[\",\",{\"Fn::GetAtt\":[\"Prefix\",\"PrefixListId\"]}]}]}",
|
||||
"{\"Fn::If\":[\"Missing\",{\"Fn::GetAtt\":[\"Prefix\",\"Version\"]},\"pl-example\"]}"
|
||||
})
|
||||
void stringAttributesAndUnselectedNumericBranchesRemainValid(String intrinsic) {
|
||||
assertEquals("pl-example", engineWithNumericAttribute().resolve(json(intrinsic)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void literalsNumberParametersAndUnselectedNumericAttributesKeepStringCoercion() {
|
||||
CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000",
|
||||
"us-east-1", "stack", "stack/id", Map.of("Number", "1"), Map.of(), Map.of(),
|
||||
Map.of(), Map.of(), mapper, name -> null, null, null, Map.of("Number", "Number"));
|
||||
assertEquals("1", e.resolveString(json("1"), "must be a string"));
|
||||
assertEquals("1", e.resolveString(json("{\"Ref\":\"Number\"}"), "must be a string"));
|
||||
assertEquals("1", e.resolve(json("{\"Fn::Join\":[\"\",[1]]}")));
|
||||
assertEquals("1", e.resolve(json("{\"Fn::Join\":[\"\",[{\"Ref\":\"Number\"}]]}")));
|
||||
assertEquals("1", e.resolve(json("{\"Fn::Select\":[0,{\"Fn::Split\":[\",\",1]}]}")));
|
||||
assertEquals("1", e.resolve(json("{\"Fn::Select\":[0,{\"Fn::Split\":[\",\",{\"Ref\":\"Number\"}]}]}")));
|
||||
assertEquals("1", e.resolve(json("{\"Fn::Sub\":[\"${Value}\",{\"Value\":1}]}")));
|
||||
assertEquals("pl-example", engineWithNumericAttribute().resolve(json("""
|
||||
{"Fn::Join":["",[{"Fn::Select":[1,[{"Fn::GetAtt":["Prefix","Version"]},"pl-example"]]}]]}
|
||||
""")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void selectedNoValueOmitsTheOptionalPropertyWhileKeepingLiteralEmptyText() {
|
||||
JsonNode source = json("""
|
||||
@@ -541,6 +629,38 @@ class CloudFormationTemplateEngineTest {
|
||||
e.resolveNode(json("\"{{resolve:ssm:/demo/url}}\"")).asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"{\"Fn::GetAtt\":[\"Custom\",\"Url\"]}",
|
||||
"{\"Fn::GetAtt\":\"Custom.Url\"}",
|
||||
"{\"Fn::If\":[\"Include\",{\"Fn::GetAtt\":[\"Custom\",\"Url\"]},\"unused\"]}",
|
||||
"{\"Fn::Select\":[0,[{\"Fn::GetAtt\":[\"Custom\",\"Url\"]}]]}"
|
||||
})
|
||||
void getAttResolvesTextualDynamicReferencesOnce(String intrinsic) {
|
||||
List<String> calls = new ArrayList<>();
|
||||
CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000",
|
||||
"us-east-1", "my-stack", "stack/id", Map.of(), Map.of(),
|
||||
Map.of("Custom", Map.of("Url", "{{resolve:ssm:/demo/url}}")),
|
||||
Map.of("Include", true), Map.of(), mapper, name -> null, value -> {
|
||||
calls.add(value);
|
||||
return "{{resolve:ssm:/literal-result}}";
|
||||
});
|
||||
|
||||
assertEquals("{{resolve:ssm:/literal-result}}", e.resolveNode(json(intrinsic)).textValue());
|
||||
assertEquals(List.of("{{resolve:ssm:/demo/url}}"), calls);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"{\"Fn::GetAtt\":[\"Custom\",\"Url\"]}", "{\"Fn::GetAtt\":\"Custom.Url\"}"})
|
||||
void getAttWithoutDynamicReferencesLeavesTextUnchanged(String intrinsic) {
|
||||
CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000",
|
||||
"us-east-1", "my-stack", "stack/id", Map.of(), Map.of(),
|
||||
Map.of("Custom", Map.of("Url", "{{resolve:ssm:/demo/url}}")), Map.of(), Map.of(), mapper,
|
||||
name -> null, value -> fail("dynamic reference must not be resolved here: " + value));
|
||||
|
||||
assertEquals("{{resolve:ssm:/demo/url}}", e.resolveWithoutDynamicReferences(json(intrinsic)));
|
||||
}
|
||||
|
||||
/**
|
||||
* CDK emits an RDS master credential as an {@code Fn::Join} whose fragments split one dynamic
|
||||
* reference: {@code ["{{resolve:secretsmanager:", {"Ref": "Secret"}, ":SecretString:password::}}"]}.
|
||||
|
||||
Reference in new issue
Block a user