fix(cloudformation): expand a SAM function's EventInvokeConfig (#5524)

* fix(cloudformation): expand a SAM function's EventInvokeConfig

SAM's EventInvokeConfig was dropped, so a function declaring retries, a maximum
event age or invoke destinations deployed with Lambda's defaults and no
destination at all. It now expands as AWS's SAM translator expands it: an
AWS::Lambda::EventInvokeConfig on $LATEST or the AutoPublishAlias alias, the
inline role policy for each destination, the SQS queue or SNS topic SAM creates
for a destination given only its Type, and SAM's conditions and error messages.

The function's Condition, DeletionPolicy and UpdateReplacePolicy now reach every
resource generated for it, as SAM passes them through. A condition naming another
with anything but a string is rejected as CloudFormation rejects it, which also
fails the template SAM produces for a conditional function with a conditional
destination, as on AWS.

* fix(cloudformation): resolve SSM parameters for the SAM transform and omit NoValue destinations

CloudFormation resolves an AWS::SSM::Parameter::Value<String> parameter before it
runs the SAM transform, so a destination Type taken from one is the stored value.
The transform now gets the given parameter values over each Default, with
SSM-typed parameters read from Parameter Store, wherever it runs.

A Destination of AWS::NoValue passes through SAM unchanged and leaves its side
without an ARN, which CloudFormation's validation rejects. The event invoke config
provisioner resolved it to an empty string and stored that; it now omits
AWS::NoValue, so the destination fails as the schema requires.

* refactor: share SHA-1 as Digests.sha1

The SAM transform's generated condition names, EC2 key pair fingerprints and
the SAML assertion name qualifier each made their own one-shot SHA-1 digest.
They now share Digests.sha1 beside sha256. Also moves samTransformParameters
above resolveSsmParameters' Javadoc, which it had been inserted beneath.
This commit is contained in:
Jay authored and GitHub committed 2026-10-12 18:34:39 -04:00
1 parent ce3d826fc7
commit aff6f0eec4
41 files changed
+2782 -36

No files matched your search

@@ -9,8 +9,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
class DigestsTest {
private static final String ABC_SHA1 = "a9993e364706816aba3e25717850c26c9cd0d89d";
private static final String ABC_SHA256 = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
@Test
void sha1MatchesTheFipsTestVector() {
assertEquals(ABC_SHA1, HexFormat.of().formatHex(Digests.sha1("abc".getBytes(StandardCharsets.UTF_8))));
}
@Test
void sha1HexOfTextDigestsItsUtf8Bytes() {
assertEquals(ABC_SHA1, Digests.sha1Hex("abc"));
assertEquals(HexFormat.of().formatHex(Digests.sha1("é".getBytes(StandardCharsets.UTF_8))), Digests.sha1Hex("é"));
}
@Test
void sha256MatchesTheFipsTestVector() {
assertEquals(ABC_SHA256, HexFormat.of().formatHex(Digests.sha256("abc".getBytes(StandardCharsets.UTF_8))));
@@ -19,6 +19,49 @@ class CloudFormationResourceConditionIntegrationTest {
RestAssuredJsonUtils.configureAwsContentTypes();
}
/**
* A condition naming another with anything but a string is a template error, which
* CloudFormation (measured in us-east-2) answers synchronously on CreateStack. The malformed
* operand comes first in an Fn::And, where evaluation alone would stop and read it as false.
*/
@Test
void aConditionReferenceThatIsNotAStringIsATemplateError() {
String template = """
{
"Conditions": {
"Deploy": { "Fn::Equals": ["a", "a"] },
"Other": { "Fn::Equals": ["a", "b"] },
"Both": { "Fn::And": [ { "Condition": { "Condition": "Deploy" } }, { "Condition": "Other" } ] }
},
"Resources": {
"Queue": { "Type": "AWS::SQS::Queue", "Condition": "Both" },
"Always": { "Type": "AWS::SQS::Queue" }
}
}
""";
String stackName = "cfn-cond-malformed-" + Long.toString(System.nanoTime(), 36);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("<Code>ValidationError</Code>"))
.body(containsString("Template error: every Condition object must have a single String value."));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(400);
}
@Test
void createStack_skipsResourceWhenResourceLevelConditionIsFalse() {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -0,0 +1,421 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* A SAM function's {@code EventInvokeConfig}, deployed and read back through the Lambda and IAM
* APIs. Before this the property was dropped, so a function declaring retries and a failure
* destination deployed with Lambda's defaults and no destination at all.
*/
@QuarkusTest
class CloudFormationSamEventInvokeConfigIntegrationTest {
/**
* A conditional function whose failure destination is itself conditional, which makes SAM's
* translator join the two conditions in a shape CloudFormation rejects.
*/
private static final String CONDITIONAL_FUNCTION_AND_DESTINATION = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Conditions": {
"Deploy": { "Fn::Equals": ["a", "a"] },
"UseOwn": { "Fn::Equals": ["a", "b"] }
},
"Resources": {
"Fn": {
"Type": "AWS::Serverless::Function",
"Condition": "Deploy",
"Properties": {
"Runtime": "python3.12",
"Handler": "index.handler",
"InlineCode": "def handler(e, c): return 'ok'",
"EventInvokeConfig": { "DestinationConfig": { "OnFailure": { "Type": "SQS",
"Destination": { "Fn::If": ["UseOwn", "arn:aws:sqs:us-east-1:000000000000:q", { "Ref": "AWS::NoValue" }] } } } }
}
}
}
}
""";
private final List<String> stacksToDelete = new ArrayList<>();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@AfterEach
void deleteStacks() {
for (String stackName : stacksToDelete) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/");
}
stacksToDelete.clear();
}
/**
* The shape kbdb's moderation function uses: two retries, six hours, and an SQS queue in the
* same template as the failure destination. The generated role may send to that queue.
*/
@Test
void retriesAgeAndAFailureQueueReachTheFunction() {
String name = "sam-eic-" + Long.toString(System.nanoTime(), 36);
createStack(name, """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"Dlq": { "Type": "AWS::SQS::Queue", "Properties": { "QueueName": "%1$s-dlq" } },
"Fn": {
"Type": "AWS::Serverless::Function",
"Properties": {
"FunctionName": "%1$s",
"Runtime": "python3.12",
"Handler": "index.handler",
"InlineCode": "def handler(e, c): return 'ok'",
"EventInvokeConfig": {
"MaximumRetryAttempts": 2,
"MaximumEventAgeInSeconds": 21600,
"DestinationConfig": { "OnFailure": { "Type": "SQS", "Destination": { "Fn::GetAtt": ["Dlq", "Arn"] } } }
}
}
}
}
}
""".formatted(name));
CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE");
String queueArn = "arn:aws:sqs:us-east-1:000000000000:" + name + "-dlq";
given().queryParam("Qualifier", "$LATEST")
.when().get("/2019-09-25/functions/" + name + "/event-invoke-config")
.then()
.statusCode(200)
.body("MaximumRetryAttempts", equalTo(2))
.body("MaximumEventAgeInSeconds", equalTo(21600))
.body("DestinationConfig.OnFailure.Destination", equalTo(queueArn));
getRolePolicy(physicalId(name, "FnRole"), "FnEventInvokeConfigOnFailureSQSPolicy")
.body(containsString("sqs:SendMessage"))
.body(containsString(queueArn))
.body(not(containsString("Fn::GetAtt")));
}
/** With AutoPublishAlias the configuration is on the alias, not on $LATEST. */
@Test
void anAutoPublishedFunctionGetsItsConfigurationOnTheAlias() {
String name = "sam-eic-alias-" + Long.toString(System.nanoTime(), 36);
createStack(name, """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"Fn": {
"Type": "AWS::Serverless::Function",
"Properties": {
"FunctionName": "%1$s",
"Runtime": "python3.12",
"Handler": "index.handler",
"InlineCode": "def handler(e, c): return 'ok'",
"AutoPublishAlias": "live",
"EventInvokeConfig": { "MaximumRetryAttempts": 0 }
}
}
}
}
""".formatted(name));
CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE");
given().queryParam("Qualifier", "live")
.when().get("/2019-09-25/functions/" + name + "/event-invoke-config")
.then()
.statusCode(200)
.body("MaximumRetryAttempts", equalTo(0));
given().queryParam("Qualifier", "$LATEST")
.when().get("/2019-09-25/functions/" + name + "/event-invoke-config")
.then()
.statusCode(404);
}
/** An SNS destination given only its Type gets the topic SAM creates for it. */
@Test
void aDestinationGivenOnlyItsTypeGetsTheTopicSamCreates() {
String name = "sam-eic-topic-" + Long.toString(System.nanoTime(), 36);
createStack(name, """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"Fn": {
"Type": "AWS::Serverless::Function",
"Properties": {
"FunctionName": "%1$s",
"Runtime": "python3.12",
"Handler": "index.handler",
"InlineCode": "def handler(e, c): return 'ok'",
"EventInvokeConfig": { "DestinationConfig": { "OnSuccess": { "Type": "SNS" } } }
}
}
}
}
""".formatted(name));
CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE");
String topicArn = physicalId(name, "FnEventInvokeConfigOnSuccessTopic");
given().queryParam("Qualifier", "$LATEST")
.when().get("/2019-09-25/functions/" + name + "/event-invoke-config")
.then()
.statusCode(200)
.body("DestinationConfig.OnSuccess.Destination", equalTo(topicArn));
getRolePolicy(physicalId(name, "FnRole"), "FnEventInvokeConfigOnSuccessSNSPolicy")
.body(containsString("sns:publish"))
.body(containsString(topicArn));
}
/** SAM rejects a destination Type it does not know, with its own message. */
@Test
void anUnknownDestinationTypeFailsTheStackWithSamsMessage() {
String name = "sam-eic-badtype-" + Long.toString(System.nanoTime(), 36);
createStack(name, """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"Fn": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Runtime": "python3.12",
"Handler": "index.handler",
"InlineCode": "def handler(e, c): return 'ok'",
"EventInvokeConfig": { "DestinationConfig": { "OnFailure": {
"Type": "sqs", "Destination": "arn:aws:sqs:us-east-1:000000000000:q" } } }
}
}
}
}
""");
CfnStackWaits.StackState state = CfnStackWaits.awaitStatus(name, "CREATE_FAILED");
assertEquals("Resource with id [Fn] is invalid. 'Type: sqs' must be one of "
+ "['SQS', 'SNS', 'EventBridge', 'Lambda', 'S3Bucket']", state.reason());
}
/**
* A conditional function whose destination is itself conditional: SAM's translator joins the
* two conditions with an Fn::And whose operands are {"Condition": {"Condition": name}}, and
* CloudFormation rejects the template it submits. Measured on CloudFormation (us-east-2), the
* stack fails during creation, after the transform, with this reason.
*/
@Test
void aConditionalFunctionWithAConditionalDestinationFailsAsOnAws() {
String name = "sam-eic-and-" + Long.toString(System.nanoTime(), 36);
createStack(name, CONDITIONAL_FUNCTION_AND_DESTINATION);
CfnStackWaits.StackState state = CfnStackWaits.awaitStatus(name, "CREATE_FAILED");
assertEquals("Template error: every Condition object must have a single String value.", state.reason());
}
/**
* The same template through a change set, as {@code sam deploy} submits it. Measured on
* CloudFormation (us-east-2): the change set is FAILED, not executable, with the template error
* as its reason, and DescribeChangeSet answers normally rather than with an error.
*/
@Test
void theSameTemplateFailsItsChangeSetWithTheTemplateError() {
String name = "sam-eic-cs-" + Long.toString(System.nanoTime(), 36);
stacksToDelete.add(name);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", name)
.formParam("ChangeSetName", "deploy")
.formParam("ChangeSetType", "CREATE")
.formParam("TemplateBody", CONDITIONAL_FUNCTION_AND_DESTINATION)
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200);
XmlPath changeSet = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeChangeSet")
.formParam("StackName", name)
.formParam("ChangeSetName", "deploy")
.when().post("/").then().statusCode(200).extract().xmlPath();
assertEquals("FAILED", changeSet.getString("**.find { it.name() == 'Status' }"));
assertEquals("UNAVAILABLE", changeSet.getString("**.find { it.name() == 'ExecutionStatus' }"));
assertEquals("Template error: every Condition object must have a single String value.",
changeSet.getString("**.find { it.name() == 'StatusReason' }"));
}
/** A Type given as a parameter reference takes the value the stack is given over the Default. */
@Test
void aParameterTypeTakesTheValueTheStackIsGiven() {
String name = "sam-eic-param-" + Long.toString(System.nanoTime(), 36);
stacksToDelete.add(name);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", name)
.formParam("TemplateBody", """
{
"Transform": "AWS::Serverless-2016-10-31",
"Parameters": { "DestType": { "Type": "String", "Default": "SQS" } },
"Resources": {
"Fn": {
"Type": "AWS::Serverless::Function",
"Properties": {
"FunctionName": "%1$s",
"Runtime": "python3.12",
"Handler": "index.handler",
"InlineCode": "def handler(e, c): return 'ok'",
"EventInvokeConfig": { "DestinationConfig": { "OnFailure": { "Type": { "Ref": "DestType" } } } }
}
}
}
}
""".formatted(name))
.formParam("Parameters.member.1.ParameterKey", "DestType")
.formParam("Parameters.member.1.ParameterValue", "SNS")
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200);
CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE");
String topicArn = physicalId(name, "FnEventInvokeConfigOnFailureTopic");
given().queryParam("Qualifier", "$LATEST")
.when().get("/2019-09-25/functions/" + name + "/event-invoke-config")
.then()
.statusCode(200)
.body("DestinationConfig.OnFailure.Destination", equalTo(topicArn));
}
/**
* CloudFormation resolves an AWS::SSM::Parameter::Value parameter before it runs the
* transform, so SAM reads the stored value. Measured on CloudFormation (us-east-2): a Type
* taken from such a parameter holding SNS creates the topic and makes it the destination.
*/
@Test
void aTypeFromAnSsmParameterUsesTheStoredValue() {
String name = "sam-eic-ssm-" + Long.toString(System.nanoTime(), 36);
String parameterName = "/" + name + "/dest-type";
given()
.contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.body("{\"Name\": \"" + parameterName + "\", \"Type\": \"String\", \"Value\": \"SNS\"}")
.when()
.post("/")
.then()
.statusCode(200);
createStack(name, """
{
"Transform": "AWS::Serverless-2016-10-31",
"Parameters": { "DestType": { "Type": "AWS::SSM::Parameter::Value<String>", "Default": "%2$s" } },
"Resources": {
"Fn": {
"Type": "AWS::Serverless::Function",
"Properties": {
"FunctionName": "%1$s",
"Runtime": "python3.12",
"Handler": "index.handler",
"InlineCode": "def handler(e, c): return 'ok'",
"EventInvokeConfig": { "DestinationConfig": { "OnFailure": { "Type": { "Ref": "DestType" } } } }
}
}
}
}
""".formatted(name, parameterName));
CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE");
String topicArn = physicalId(name, "FnEventInvokeConfigOnFailureTopic");
given().queryParam("Qualifier", "$LATEST")
.when().get("/2019-09-25/functions/" + name + "/event-invoke-config")
.then()
.statusCode(200)
.body("DestinationConfig.OnFailure.Destination", equalTo(topicArn));
}
/**
* A Destination of AWS::NoValue passes through SAM unchanged and leaves the destination without
* an ARN. Measured on CloudFormation (us-east-2): the stack fails validation instead of
* creating a configuration with an empty destination.
*/
@Test
void aNoValueDestinationFailsTheStackInsteadOfStoringAnEmptyOne() {
String name = "sam-eic-novalue-" + Long.toString(System.nanoTime(), 36);
createStack(name, """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"Fn": {
"Type": "AWS::Serverless::Function",
"Properties": {
"FunctionName": "%s",
"Runtime": "python3.12",
"Handler": "index.handler",
"InlineCode": "def handler(e, c): return 'ok'",
"EventInvokeConfig": { "DestinationConfig": { "OnFailure": { "Type": "SQS", "Destination": { "Ref": "AWS::NoValue" } } } }
}
}
}
}
""".formatted(name));
CfnStackWaits.StackState state = CfnStackWaits.awaitStatus(name, "ROLLBACK_COMPLETE");
given().queryParam("Qualifier", "$LATEST")
.when().get("/2019-09-25/functions/" + name + "/event-invoke-config")
.then()
.statusCode(404);
assertEquals("ROLLBACK_COMPLETE", state.status());
}
private void createStack(String stackName, String template) {
stacksToDelete.add(stackName);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200);
}
private static String physicalId(String stackName, String logicalId) {
XmlPath xml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResource")
.formParam("StackName", stackName)
.formParam("LogicalResourceId", logicalId)
.when().post("/").then().statusCode(200).extract().xmlPath();
return xml.getString("**.find { it.name() == 'PhysicalResourceId' }");
}
private static ValidatableResponse getRolePolicy(String roleName, String policyName) {
return given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", roleName)
.formParam("PolicyName", policyName)
.when().post("/").then().statusCode(200);
}
}
@@ -0,0 +1,236 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A SAM function's {@code EventInvokeConfig}, expanded as AWS's own SAM translator expands it.
*
* <p>Each fixture under {@code src/test/resources/cloudformation/sam-event-invoke-config} holds a
* template and what aws-sam-translator 1.115.0 (the library behind {@code sam deploy} and the
* {@code AWS::Serverless-2016-10-31} transform) generated from it: the
* {@code FnEventInvokeConfig*} resources, the generated role's attributes and inline policies, and
* any conditions it added, or the error it rejected the template with. They were produced with
* {@code samtranslator.translator.transform.transform(template, {}, loader)}, a loader whose
* {@code load()} returns {@code {}}.
*/
class SamEventInvokeConfigTransformTest {
private static final Path FIXTURES = Path.of("src/test/resources/cloudformation/sam-event-invoke-config");
private final ObjectMapper mapper = new ObjectMapper();
private final SamTransformProcessor processor = new SamTransformProcessor(mapper);
static Stream<String> fixtures() throws IOException {
try (Stream<Path> files = Files.list(FIXTURES)) {
return files.map(file -> file.getFileName().toString())
.filter(name -> name.endsWith(".json"))
.sorted()
.toList()
.stream();
}
}
@ParameterizedTest(name = "{0}")
@MethodSource("fixtures")
void matchesTheSamTranslator(String fixtureName) throws IOException {
JsonNode fixture = mapper.readTree(FIXTURES.resolve(fixtureName).toFile());
JsonNode input = fixture.path("input");
if (fixture.has("error")) {
AwsException e = assertThrows(AwsException.class, () -> processor.expandSamTemplate(input));
assertEquals("ValidationError", e.getErrorCode());
assertEquals(fixture.path("error").asText(), e.getMessage());
return;
}
JsonNode expanded = processor.expandSamTemplate(input);
JsonNode resources = expanded.path("Resources");
JsonNode expected = fixture.path("expected");
List<String> generated = new ArrayList<>();
resources.fieldNames().forEachRemaining(id -> {
if (id.startsWith("FnEventInvokeConfig")) {
generated.add(id);
}
});
List<String> expectedIds = new ArrayList<>();
expected.fieldNames().forEachRemaining(id -> {
if (id.startsWith("FnEventInvokeConfig")) {
expectedIds.add(id);
}
});
assertEquals(expectedIds.stream().sorted().toList(), generated.stream().sorted().toList(),
"the resources SAM generates for EventInvokeConfig");
for (String id : expectedIds) {
assertEquals(withFlociAliasId(expected.path(id), resources), resources.path(id), id);
}
JsonNode expectedRole = expected.path("FnRole");
JsonNode role = resources.path("FnRole");
if (expectedRole.isMissingNode()) {
assertTrue(role.isMissingNode(), "a function with its own Role gets no generated role");
} else {
assertEquals(expectedRole.path("Condition"), role.path("Condition"), "the role's Condition");
JsonNode expectedPolicies = expectedRole.path("Policies");
JsonNode policies = role.path("Properties").path("Policies");
if (expectedPolicies.isNull() || expectedPolicies.isMissingNode()) {
assertTrue(policies.isMissingNode(), "no inline policies: " + policies);
} else {
assertEquals(expectedPolicies, policies, "the role's inline policies");
}
}
// SAM passes the function's Condition, DeletionPolicy and UpdateReplacePolicy to the alias
// and version AutoPublishAlias generates as well. Only what the function declares is
// checked: SAM also retains every published version on its own (DeletionPolicy: Retain),
// which floci's AutoPublishAlias expansion has never done and this change does not touch.
JsonNode function = input.path("Resources").path("Fn");
for (Map.Entry<String, JsonNode> byType : fixture.path("expectedAttributesByType").properties()) {
JsonNode generatedResource = null;
for (Map.Entry<String, JsonNode> resource : resources.properties()) {
if (byType.getKey().equals(resource.getValue().path("Type").asText())) {
generatedResource = resource.getValue();
}
}
for (Map.Entry<String, JsonNode> attribute : byType.getValue().properties()) {
if (function.has(attribute.getKey())) {
assertEquals(attribute.getValue(), generatedResource.path(attribute.getKey()),
byType.getKey() + " " + attribute.getKey());
}
}
}
JsonNode inputConditions = input.path("Conditions");
JsonNode expectedConditions = fixture.path("expectedConditions");
List<String> added = new ArrayList<>();
expanded.path("Conditions").fieldNames().forEachRemaining(name -> {
if (!inputConditions.has(name)) {
added.add(name);
}
});
List<String> expectedAdded = new ArrayList<>();
expectedConditions.fieldNames().forEachRemaining(expectedAdded::add);
assertEquals(expectedAdded.stream().sorted().toList(), added.stream().sorted().toList(),
"the conditions SAM adds");
for (Map.Entry<String, JsonNode> condition : expectedConditions.properties()) {
assertEquals(condition.getValue(), expanded.path("Conditions").path(condition.getKey()),
condition.getKey());
}
}
/**
* The expected resource with a {@code DependsOn} on SAM's alias id replaced by floci's. SAM
* names an {@code AutoPublishAlias} alias {@code FnAlias<name>} with the name as written; floci
* capitalises it ({@code FnAliasLive}), which predates this expansion and would rename the alias
* in existing stacks if changed. The configuration must depend on the alias floci creates.
*/
private JsonNode withFlociAliasId(JsonNode expected, JsonNode resources) {
if (!expected.path("DependsOn").isArray()) {
return expected;
}
String flociAlias = null;
for (Map.Entry<String, JsonNode> resource : resources.properties()) {
if ("AWS::Lambda::Alias".equals(resource.getValue().path("Type").asText())) {
flociAlias = resource.getKey();
}
}
ObjectNode copy = expected.deepCopy();
copy.set("DependsOn", mapper.createArrayNode().add(flociAlias));
return copy;
}
/** Without the property nothing changes: no configuration, and the generated role carries no inline policies. */
@Test
void aFunctionWithoutEventInvokeConfigGetsNoneAndAnUnchangedRole() throws IOException {
JsonNode expanded = processor.expandSamTemplate(mapper.readTree("""
{"Transform": "AWS::Serverless-2016-10-31",
"Resources": {"Fn": {"Type": "AWS::Serverless::Function",
"Properties": {"Runtime": "python3.12", "Handler": "index.handler", "CodeUri": "s3://b/k"}}}}
"""));
assertTrue(expanded.path("Resources").path("FnEventInvokeConfig").isMissingNode());
assertTrue(expanded.path("Resources").path("FnRole").path("Properties").path("Policies").isMissingNode());
assertTrue(expanded.path("Resources").path("FnRole").path("Condition").isMissingNode());
assertFalse(expanded.has("Conditions"), "no Conditions section is added when none is needed");
}
private static final String TYPE_FROM_PARAMETER = """
{"Transform": "AWS::Serverless-2016-10-31",
"Parameters": {"DestType": {"Type": "String" %s}},
"Resources": {"Fn": {"Type": "AWS::Serverless::Function",
"Properties": {"Runtime": "python3.12", "Handler": "index.handler", "CodeUri": "s3://b/k",
"EventInvokeConfig": {"DestinationConfig": {"OnFailure": {"Type": {"Ref": "DestType"}}}}}}}}
""";
/** SAM resolves a parameter reference to the value the stack is given before its Default. */
@Test
void aTypeFromAParameterTakesTheGivenValueOverTheDefault() throws IOException {
JsonNode expanded = processor.expandSamTemplate(
mapper.readTree(TYPE_FROM_PARAMETER.formatted(", \"Default\": \"SQS\"")), Map.of("DestType", "SNS"));
assertEquals("AWS::SNS::Topic",
expanded.path("Resources").path("FnEventInvokeConfigOnFailureTopic").path("Type").asText());
assertTrue(expanded.path("Resources").path("FnEventInvokeConfigOnFailureQueue").isMissingNode());
}
@Test
void aTypeFromAParameterWithoutADefaultTakesTheGivenValue() throws IOException {
JsonNode expanded = processor.expandSamTemplate(
mapper.readTree(TYPE_FROM_PARAMETER.formatted("")), Map.of("DestType", "SQS"));
assertEquals("AWS::SQS::Queue",
expanded.path("Resources").path("FnEventInvokeConfigOnFailureQueue").path("Type").asText());
}
/** An Fn::If whose condition is not a name is passed through as given, not read as a conditional destination. */
@Test
void anFnIfWithoutAConditionNameIsPassedThroughAsGiven() throws IOException {
JsonNode expanded = processor.expandSamTemplate(mapper.readTree("""
{"Transform": "AWS::Serverless-2016-10-31",
"Resources": {"Fn": {"Type": "AWS::Serverless::Function",
"Properties": {"Runtime": "python3.12", "Handler": "index.handler", "CodeUri": "s3://b/k",
"EventInvokeConfig": {"DestinationConfig": {"OnFailure": {"Type": "SQS",
"Destination": {"Fn::If": [{"Ref": "X"}, {"Ref": "AWS::NoValue"}, "arn:aws:sqs:us-east-1:123456789012:q"]}}}}}}}}
"""));
JsonNode resources = expanded.path("Resources");
assertTrue(resources.path("FnEventInvokeConfigOnFailureQueue").isMissingNode(), "no queue is created");
assertEquals(mapper.readTree("""
{"Fn::If": [{"Ref": "X"}, {"Ref": "AWS::NoValue"}, "arn:aws:sqs:us-east-1:123456789012:q"]}
"""), resources.path("FnEventInvokeConfig").path("Properties").path("DestinationConfig")
.path("OnFailure").path("Destination"));
assertFalse(expanded.has("Conditions"), "no condition is generated");
}
/** An empty EventInvokeConfig is falsy to SAM, which then generates nothing for it. */
@Test
void anEmptyEventInvokeConfigGeneratesNothing() throws IOException {
JsonNode expanded = processor.expandSamTemplate(mapper.readTree("""
{"Transform": "AWS::Serverless-2016-10-31",
"Resources": {"Fn": {"Type": "AWS::Serverless::Function",
"Properties": {"Runtime": "python3.12", "Handler": "index.handler", "CodeUri": "s3://b/k",
"EventInvokeConfig": {}}}}}
"""));
assertTrue(expanded.path("Resources").path("FnEventInvokeConfig").isMissingNode());
}
}
@@ -2,7 +2,8 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TextNode;
import com.fasterxml.jackson.databind.node.MissingNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
@@ -60,6 +61,7 @@ class LambdaEventInvokeConfigCfnProvisionerTest {
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0));
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(i -> i.getArgument(0));
// The service never answers null: a missing configuration throws. Tests that care about
// the settings before an update stub their own.
when(lambda.getEventInvokeConfig(anyString(), anyString(), anyString()))
@@ -421,9 +423,9 @@ class LambdaEventInvokeConfigCfnProvisionerTest {
/** A conditional DestinationConfig that resolves to AWS::NoValue is omitted, not sent as an empty set. */
@Test
void aDestinationConfigResolvingToNoValueIsNotSent() {
when(engine.resolveNode(any())).thenAnswer(i -> {
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(i -> {
JsonNode node = i.getArgument(0);
return node.has("Ref") ? TextNode.valueOf("") : node;
return node.has("Ref") ? MissingNode.getInstance() : node;
});
provision("""
@@ -438,10 +440,10 @@ class LambdaEventInvokeConfigCfnProvisionerTest {
@Test
void aDestinationSideResolvingToNoValueIsNotSent() {
when(engine.resolveNode(any())).thenAnswer(i -> {
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(i -> {
JsonNode node = i.getArgument(0);
if (node.isObject() && node.has("OnSuccess")) {
((com.fasterxml.jackson.databind.node.ObjectNode) node).set("OnSuccess", TextNode.valueOf(""));
((ObjectNode) node).remove("OnSuccess");
}
return node;
});
@@ -458,6 +460,31 @@ class LambdaEventInvokeConfigCfnProvisionerTest {
request.getValue().get("DestinationConfig"));
}
/**
* A Destination that resolves to AWS::NoValue leaves its side without one, which the registry
* schema does not allow. CloudFormation fails such a template's validation rather than
* creating a configuration with an empty destination.
*/
@Test
void aDestinationResolvingToNoValueIsRejectedRatherThanSentEmpty() {
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(i -> {
JsonNode node = i.getArgument(0);
JsonNode onFailure = node.path("OnFailure");
if (onFailure.isObject() && onFailure.path("Destination").has("Ref")) {
((ObjectNode) onFailure).remove("Destination");
}
return node;
});
AwsException e = assertThrows(AwsException.class, () -> provision("""
{"FunctionName": "orders", "Qualifier": "$LATEST",
"DestinationConfig": {"OnFailure": {"Destination": {"Ref": "AWS::NoValue"}}}}
""", null));
assertTrue(e.getMessage().contains("DestinationConfig.OnFailure requires Destination"), e.getMessage());
verify(lambda, never()).putEventInvokeConfig(anyString(), anyString(), anyString(), any());
}
private static FunctionEventInvokeConfig config(Integer retries, Integer eventAge,
String onSuccess, String onFailure) {
FunctionEventInvokeConfig config = new FunctionEventInvokeConfig();