Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudFormation): support AWS::Serverless-2016-10-31 SAM Transform in CloudFormation (#1012)
Dixit R Jainbd6e7795f802
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.javaindex 28dbe11a22..32083871fb 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java@@ -46,6 +46,7 @@ public class CloudFormationService {private final ObjectMapper objectMapper;private final EmulatorConfig config;private final RegionResolver regionResolver;+ private final SamTransformProcessor samTransformProcessor;private final Clock clock;@Inject@@ -57,6 +58,7 @@ public class CloudFormationService {this.objectMapper = objectMapper;this.config = config;this.regionResolver = regionResolver;+ this.samTransformProcessor = new SamTransformProcessor(objectMapper);this.clock = clock;}@@ -269,6 +271,15 @@ public class CloudFormationService {boolean isCreate, String region, String accountId) {try {JsonNode template = parseTemplate(templateBody);++ // Apply SAM transform if the template declares AWS::Serverless-2016-10-31+ if (samTransformProcessor.hasSamTransform(template)) {+ LOG.infov("Applying SAM transform for stack {0}", stack.getStackName());+ template = samTransformProcessor.expandSamTemplate(template);+ // Store the expanded template so GetTemplate returns the transformed version+ templateBody = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(template);+ }+stack.setTemplateBody(templateBody);// Merge default parameter values from the template with caller-supplied paramsdiff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.javanew file mode 100644index 0000000000..0661c8df41--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java@@ -0,0 +1,405 @@+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.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import org.jboss.logging.Logger;++import java.util.ArrayList;+import java.util.Iterator;+import java.util.List;+import java.util.Map;++/**+ * Expands {@code AWS::Serverless-2016-10-31} SAM resource types into standard CloudFormation+ * resources. Inline policy documents in {@code Policies} are silently ignored — only ARN+ * references are attached as managed policies on the generated execution role.+ */+class SamTransformProcessor {++ private static final Logger LOG = Logger.getLogger(SamTransformProcessor.class);+ private static final String SAM_TRANSFORM = "AWS::Serverless-2016-10-31";++ private final ObjectMapper objectMapper;++ SamTransformProcessor(ObjectMapper objectMapper) {+ this.objectMapper = objectMapper;+ }++ boolean hasSamTransform(JsonNode template) {+ JsonNode transform = template.path("Transform");+ if (transform.isTextual()) {+ return SAM_TRANSFORM.equals(transform.asText());+ }+ if (transform.isArray()) {+ for (JsonNode t : transform) {+ if (SAM_TRANSFORM.equals(t.asText())) {+ return true;+ }+ }+ }+ return false;+ }++ JsonNode expandSamTemplate(JsonNode template) {+ if (!hasSamTransform(template)) {+ return template;+ }++ ObjectNode expanded = template.deepCopy();+ expanded.remove("Transform");++ JsonNode resources = expanded.path("Resources");+ if (!resources.isObject()) {+ return expanded;+ }++ ObjectNode expandedResources = (ObjectNode) resources;+ List<String> samLogicalIds = new ArrayList<>();+ resources.fieldNames().forEachRemaining(logicalId -> {+ String type = resources.path(logicalId).path("Type").asText("");+ if (type.startsWith("AWS::Serverless::")) {+ samLogicalIds.add(logicalId);+ }+ });++ for (String logicalId : samLogicalIds) {+ JsonNode resDef = resources.get(logicalId);+ String type = resDef.path("Type").asText();+ JsonNode properties = resDef.path("Properties");++ switch (type) {+ case "AWS::Serverless::Function" ->+ expandServerlessFunction(logicalId, properties, expandedResources);+ case "AWS::Serverless::SimpleTable" ->+ expandServerlessSimpleTable(logicalId, properties, expandedResources);+ case "AWS::Serverless::Api" ->+ expandServerlessApi(logicalId, properties, expandedResources);+ default -> LOG.debugv("Unsupported SAM resource type: {0} ({1})", type, logicalId);+ }+ }++ return expanded;+ }++ private void expandServerlessFunction(String logicalId, JsonNode properties, ObjectNode resources) {+ resources.remove(logicalId);++ boolean hasExplicitRole = !properties.path("Role").isMissingNode()+ && !properties.path("Role").isNull();+ String roleLogicalId = logicalId + "Role";++ if (!hasExplicitRole) {+ ObjectNode roleResource = createExecutionRole(properties);+ resources.set(roleLogicalId, roleResource);+ }++ ObjectNode lambdaResource = createLambdaFunction(logicalId, roleLogicalId, properties, hasExplicitRole);+ resources.set(logicalId, lambdaResource);++ JsonNode events = properties.path("Events");+ if (events.isObject()) {+ Iterator<Map.Entry<String, JsonNode>> eventFields = events.fields();+ while (eventFields.hasNext()) {+ Map.Entry<String, JsonNode> entry = eventFields.next();+ expandFunctionEvent(logicalId, entry.getKey(), entry.getValue(), resources);+ }+ }+ }++ private ObjectNode createExecutionRole(JsonNode properties) {+ ObjectNode roleDef = objectMapper.createObjectNode();+ roleDef.put("Type", "AWS::IAM::Role");++ ObjectNode roleProps = objectMapper.createObjectNode();++ ObjectNode assumePolicy = objectMapper.createObjectNode();+ assumePolicy.put("Version", "2012-10-17");+ ArrayNode statements = objectMapper.createArrayNode();+ ObjectNode stmt = objectMapper.createObjectNode();+ stmt.put("Effect", "Allow");+ ObjectNode principal = objectMapper.createObjectNode();+ principal.put("Service", "lambda.amazonaws.com");+ stmt.set("Principal", principal);+ stmt.put("Action", "sts:AssumeRole");+ statements.add(stmt);+ assumePolicy.set("Statement", statements);+ roleProps.set("AssumeRolePolicyDocument", assumePolicy);++ ArrayNode managedPolicies = objectMapper.createArrayNode();+ managedPolicies.add("arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole");++ JsonNode userPolicies = properties.path("Policies");+ if (userPolicies.isArray()) {+ for (JsonNode policy : userPolicies) {+ if (policy.isTextual()) {+ managedPolicies.add(policy.asText());+ }+ }+ } else if (userPolicies.isTextual()) {+ managedPolicies.add(userPolicies.asText());+ }+ roleProps.set("ManagedPolicyArns", managedPolicies);++ roleDef.set("Properties", roleProps);+ return roleDef;+ }++ private ObjectNode createLambdaFunction(String logicalId, String roleLogicalId,+ JsonNode properties, boolean hasExplicitRole) {+ ObjectNode lambdaDef = objectMapper.createObjectNode();+ lambdaDef.put("Type", "AWS::Lambda::Function");++ ObjectNode lambdaProps = objectMapper.createObjectNode();++ copyIfPresent(properties, "FunctionName", lambdaProps);+ copyIfPresent(properties, "Handler", lambdaProps);+ copyIfPresent(properties, "Runtime", lambdaProps);++ lambdaProps.set("Code", buildLambdaCode(properties));++ if (hasExplicitRole) {+ lambdaProps.set("Role", properties.get("Role").deepCopy());+ } else {+ ObjectNode roleRef = objectMapper.createObjectNode();+ ArrayNode getAtt = objectMapper.createArrayNode();+ getAtt.add(roleLogicalId);+ getAtt.add("Arn");+ roleRef.set("Fn::GetAtt", getAtt);+ lambdaProps.set("Role", roleRef);+ }++ copyIfPresent(properties, "Timeout", lambdaProps);+ copyIfPresent(properties, "MemorySize", lambdaProps);+ copyIfPresent(properties, "Environment", lambdaProps);+ copyIfPresent(properties, "Layers", lambdaProps);+ copyIfPresent(properties, "Tags", lambdaProps);+ copyIfPresent(properties, "Architectures", lambdaProps);+ copyIfPresent(properties, "ReservedConcurrentExecutions", lambdaProps);+ copyIfPresent(properties, "EphemeralStorage", lambdaProps);++ JsonNode tracing = properties.path("Tracing");+ if (!tracing.isMissingNode()) {+ ObjectNode tracingConfig = objectMapper.createObjectNode();+ tracingConfig.set("Mode", tracing.deepCopy());+ lambdaProps.set("TracingConfig", tracingConfig);+ }++ lambdaDef.set("Properties", lambdaProps);+ return lambdaDef;+ }++ private ObjectNode buildLambdaCode(JsonNode properties) {+ ObjectNode code = objectMapper.createObjectNode();++ JsonNode inlineCode = properties.path("InlineCode");+ if (!inlineCode.isMissingNode()) {+ code.set("ZipFile", inlineCode.deepCopy());+ return code;+ }++ JsonNode codeUri = properties.path("CodeUri");+ if (codeUri.isTextual()) {+ String uri = codeUri.asText();+ if (uri.startsWith("s3://")) {+ String withoutScheme = uri.substring(5);+ int slash = withoutScheme.indexOf('/');+ if (slash > 0) {+ code.put("S3Bucket", withoutScheme.substring(0, slash));+ code.put("S3Key", withoutScheme.substring(slash + 1));+ }+ } else {+ code.put("ZipFile", "// SAM local code: " + uri);+ }+ return code;+ }++ if (codeUri.isObject()) {+ JsonNode bucket = codeUri.path("Bucket");+ if (!bucket.isMissingNode()) code.set("S3Bucket", bucket.deepCopy());+ JsonNode key = codeUri.path("Key");+ if (!key.isMissingNode()) code.set("S3Key", key.deepCopy());+ JsonNode version = codeUri.path("Version");+ if (!version.isMissingNode()) code.set("S3ObjectVersion", version.deepCopy());+ return code;+ }++ JsonNode imageUri = properties.path("ImageUri");+ if (!imageUri.isMissingNode()) {+ code.set("ImageUri", imageUri.deepCopy());+ return code;+ }++ code.put("ZipFile", "// No code specified");+ return code;+ }++ private void expandFunctionEvent(String functionLogicalId, String eventName,+ JsonNode eventDef, ObjectNode resources) {+ String eventType = eventDef.path("Type").asText("");+ JsonNode eventProps = eventDef.path("Properties");++ switch (eventType) {+ case "SQS", "Kinesis", "DynamoDB" ->+ expandEventSourceMapping(functionLogicalId, eventName, eventProps, resources);+ case "Api" ->+ LOG.debugv("SAM Api event for {0}.{1} — handled by Api resource",+ functionLogicalId, eventName);+ default ->+ LOG.debugv("SAM event type {0} for {1}.{2} not expanded",+ eventType, functionLogicalId, eventName);+ }+ }++ private void expandEventSourceMapping(String functionLogicalId, String eventName,+ JsonNode eventProps, ObjectNode resources) {+ String esmLogicalId = functionLogicalId + eventName;++ ObjectNode esmDef = objectMapper.createObjectNode();+ esmDef.put("Type", "AWS::Lambda::EventSourceMapping");++ ObjectNode esmProps = objectMapper.createObjectNode();++ ObjectNode funcRef = objectMapper.createObjectNode();+ funcRef.put("Ref", functionLogicalId);+ esmProps.set("FunctionName", funcRef);++ JsonNode sourceArn = eventProps.path("Queue");+ if (sourceArn.isMissingNode()) {+ sourceArn = eventProps.path("Stream");+ }+ if (!sourceArn.isMissingNode()) {+ esmProps.set("EventSourceArn", sourceArn.deepCopy());+ }++ copyIfPresent(eventProps, "BatchSize", esmProps);+ copyIfPresent(eventProps, "Enabled", esmProps);++ esmDef.set("Properties", esmProps);+ ArrayNode dependsOn = objectMapper.createArrayNode();+ dependsOn.add(functionLogicalId);+ esmDef.set("DependsOn", dependsOn);++ resources.set(esmLogicalId, esmDef);+ }++ private void expandServerlessSimpleTable(String logicalId, JsonNode properties, ObjectNode resources) {+ resources.remove(logicalId);++ ObjectNode tableDef = objectMapper.createObjectNode();+ tableDef.put("Type", "AWS::DynamoDB::Table");++ ObjectNode tableProps = objectMapper.createObjectNode();++ copyIfPresent(properties, "TableName", tableProps);++ JsonNode primaryKey = properties.path("PrimaryKey");+ ArrayNode keySchema = objectMapper.createArrayNode();+ ArrayNode attrDefs = objectMapper.createArrayNode();++ if (primaryKey.isObject()) {+ String pkName = primaryKey.path("Name").asText("id");+ String pkType = mapSamAttributeType(primaryKey.path("Type").asText("String"));++ ObjectNode hashKey = objectMapper.createObjectNode();+ hashKey.put("AttributeName", pkName);+ hashKey.put("KeyType", "HASH");+ keySchema.add(hashKey);++ ObjectNode hashAttr = objectMapper.createObjectNode();+ hashAttr.put("AttributeName", pkName);+ hashAttr.put("AttributeType", pkType);+ attrDefs.add(hashAttr);+ } else {+ ObjectNode hashKey = objectMapper.createObjectNode();+ hashKey.put("AttributeName", "id");+ hashKey.put("KeyType", "HASH");+ keySchema.add(hashKey);++ ObjectNode hashAttr = objectMapper.createObjectNode();+ hashAttr.put("AttributeName", "id");+ hashAttr.put("AttributeType", "S");+ attrDefs.add(hashAttr);+ }++ tableProps.set("KeySchema", keySchema);+ tableProps.set("AttributeDefinitions", attrDefs);+ tableProps.put("BillingMode", "PAY_PER_REQUEST");++ copyIfPresent(properties, "Tags", tableProps);++ tableDef.set("Properties", tableProps);+ resources.set(logicalId, tableDef);+ }++ private void expandServerlessApi(String logicalId, JsonNode properties, ObjectNode resources) {+ resources.remove(logicalId);++ ObjectNode apiDef = objectMapper.createObjectNode();+ apiDef.put("Type", "AWS::ApiGateway::RestApi");+ ObjectNode apiProps = objectMapper.createObjectNode();++ JsonNode name = properties.path("Name");+ if (!name.isMissingNode()) {+ apiProps.set("Name", name.deepCopy());+ } else {+ apiProps.put("Name", logicalId);+ }+ copyIfPresent(properties, "Description", apiProps);++ apiDef.set("Properties", apiProps);+ resources.set(logicalId, apiDef);++ String deploymentLogicalId = logicalId + "Deployment";+ ObjectNode deployDef = objectMapper.createObjectNode();+ deployDef.put("Type", "AWS::ApiGateway::Deployment");+ ObjectNode deployProps = objectMapper.createObjectNode();+ ObjectNode restApiRef = objectMapper.createObjectNode();+ restApiRef.put("Ref", logicalId);+ deployProps.set("RestApiId", restApiRef);+ deployDef.set("Properties", deployProps);+ ArrayNode deployDeps = objectMapper.createArrayNode();+ deployDeps.add(logicalId);+ deployDef.set("DependsOn", deployDeps);+ resources.set(deploymentLogicalId, deployDef);++ String stageLogicalId = logicalId + "Stage";+ ObjectNode stageDef = objectMapper.createObjectNode();+ stageDef.put("Type", "AWS::ApiGateway::Stage");+ ObjectNode stageProps = objectMapper.createObjectNode();+ stageProps.set("RestApiId", restApiRef.deepCopy());+ ObjectNode deployRef = objectMapper.createObjectNode();+ deployRef.put("Ref", deploymentLogicalId);+ stageProps.set("DeploymentId", deployRef);++ JsonNode stageName = properties.path("StageName");+ if (!stageName.isMissingNode()) {+ stageProps.set("StageName", stageName.deepCopy());+ } else {+ stageProps.put("StageName", "Prod");+ }++ stageDef.set("Properties", stageProps);+ ArrayNode stageDeps = objectMapper.createArrayNode();+ stageDeps.add(deploymentLogicalId);+ stageDef.set("DependsOn", stageDeps);+ resources.set(stageLogicalId, stageDef);+ }++ private void copyIfPresent(JsonNode source, String field, ObjectNode target) {+ JsonNode value = source.path(field);+ if (!value.isMissingNode() && !value.isNull()) {+ target.set(field, value.deepCopy());+ }+ }++ private String mapSamAttributeType(String samType) {+ return switch (samType) {+ case "String" -> "S";+ case "Number" -> "N";+ case "Binary" -> "B";+ default -> "S";+ };+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.javanew file mode 100644index 0000000000..08aef74772--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java@@ -0,0 +1,596 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+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.MatcherAssert.assertThat;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.not;++@QuarkusTest+class SamTransformIntegrationTest {++ 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();+ }++ @Test+ void samFunction_withInlineCode_createsLambdaAndRole() {+ String stackName = "sam-hello-stack";+ stacksToDelete.add(stackName);++ String template = """+ AWSTemplateFormatVersion: '2010-09-09'+ Transform: AWS::Serverless-2016-10-31+ Resources:+ HelloFunction:+ Type: AWS::Serverless::Function+ Properties:+ FunctionName: sam-hello-func+ Handler: index.handler+ Runtime: nodejs22.x+ InlineCode: |+ exports.handler = async () => ({ statusCode: 200, body: 'ok' });+ """;++ 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)+ .body(containsString("<StackId>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));++ given()+ .when()+ .get("/2015-03-31/functions/sam-hello-func")+ .then()+ .statusCode(200)+ .body("Configuration.FunctionName", equalTo("sam-hello-func"))+ .body("Configuration.Handler", equalTo("index.handler"))+ .body("Configuration.Runtime", equalTo("nodejs22.x"));++ String resourcesXml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStackResources")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();++ assertThat(resourcesXml, containsString("<ResourceType>AWS::Lambda::Function</ResourceType>"));+ assertThat(resourcesXml, containsString("<ResourceType>AWS::IAM::Role</ResourceType>"));+ assertThat(resourcesXml, not(containsString("AWS::Serverless::Function")));+ }++ @Test+ void samFunction_withExplicitRole_skipsRoleGeneration() {+ String stackName = "sam-explicit-role-stack";+ stacksToDelete.add(stackName);++ String template = """+ AWSTemplateFormatVersion: '2010-09-09'+ Transform: AWS::Serverless-2016-10-31+ Resources:+ MyFunc:+ Type: AWS::Serverless::Function+ Properties:+ FunctionName: sam-explicit-role-func+ Handler: index.handler+ Runtime: nodejs20.x+ InlineCode: "exports.handler = async () => ({});"+ Role: arn:aws:iam::000000000000:role/my-existing-role+ """;++ 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)+ .body(containsString("<StackId>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));++ given()+ .when()+ .get("/2015-03-31/functions/sam-explicit-role-func")+ .then()+ .statusCode(200)+ .body("Configuration.FunctionName", equalTo("sam-explicit-role-func"))+ .body("Configuration.Role", equalTo("arn:aws:iam::000000000000:role/my-existing-role"));++ // Verify no IAM role was created (only Lambda, no Role resource)+ String resourcesXml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStackResources")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();++ assertThat(resourcesXml, containsString("<ResourceType>AWS::Lambda::Function</ResourceType>"));+ assertThat(resourcesXml, not(containsString("<ResourceType>AWS::IAM::Role</ResourceType>")));+ }++ @Test+ void samFunction_withEnvironmentAndTimeout() {+ String stackName = "sam-configured-stack";+ stacksToDelete.add(stackName);++ String template = """+ AWSTemplateFormatVersion: '2010-09-09'+ Transform: AWS::Serverless-2016-10-31+ Resources:+ ConfiguredFunc:+ Type: AWS::Serverless::Function+ Properties:+ FunctionName: sam-configured-func+ Handler: app.handler+ Runtime: python3.12+ InlineCode: "def handler(event, context): return {'statusCode': 200}"+ Timeout: 30+ MemorySize: 256+ Environment:+ Variables:+ TABLE_NAME: my-table+ STAGE: local+ """;++ 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)+ .body(containsString("<StackId>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));++ given()+ .when()+ .get("/2015-03-31/functions/sam-configured-func")+ .then()+ .statusCode(200)+ .body("Configuration.FunctionName", equalTo("sam-configured-func"))+ .body("Configuration.Handler", equalTo("app.handler"))+ .body("Configuration.Runtime", equalTo("python3.12"))+ .body("Configuration.Timeout", equalTo(30))+ .body("Configuration.MemorySize", equalTo(256))+ .body("Configuration.Environment.Variables.TABLE_NAME", equalTo("my-table"))+ .body("Configuration.Environment.Variables.STAGE", equalTo("local"));+ }++ @Test+ void samSimpleTable_createsDynamoDbTable() {+ String stackName = "sam-table-stack";+ stacksToDelete.add(stackName);++ String template = """+ AWSTemplateFormatVersion: '2010-09-09'+ Transform: AWS::Serverless-2016-10-31+ Resources:+ MyTable:+ Type: AWS::Serverless::SimpleTable+ Properties:+ TableName: sam-simple-table+ PrimaryKey:+ Name: userId+ Type: String+ """;++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackId>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));++ given()+ .header("X-Amz-Target", "DynamoDB_20120810.DescribeTable")+ .contentType("application/x-amz-json-1.0")+ .body("""+ {"TableName": "sam-simple-table"}+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Table.TableName", equalTo("sam-simple-table"))+ .body("Table.KeySchema[0].AttributeName", equalTo("userId"))+ .body("Table.KeySchema[0].KeyType", equalTo("HASH"));++ String resourcesXml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStackResources")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();++ assertThat(resourcesXml, containsString("<ResourceType>AWS::DynamoDB::Table</ResourceType>"));+ assertThat(resourcesXml, not(containsString("AWS::Serverless::SimpleTable")));+ }++ @Test+ void samApi_createsApiGatewayResources() {+ String stackName = "sam-api-stack";+ stacksToDelete.add(stackName);++ String template = """+ AWSTemplateFormatVersion: '2010-09-09'+ Transform: AWS::Serverless-2016-10-31+ Resources:+ MyApi:+ Type: AWS::Serverless::Api+ Properties:+ Name: sam-test-api+ StageName: dev+ """;++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackId>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));++ String resourcesXml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStackResources")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();++ assertThat(resourcesXml, containsString("<ResourceType>AWS::ApiGateway::RestApi</ResourceType>"));+ assertThat(resourcesXml, not(containsString("AWS::Serverless::Api")));+ }++ @Test+ void samFunction_withCodeUri_s3Reference() {+ String stackName = "sam-s3code-stack";+ stacksToDelete.add(stackName);++ given()+ .when()+ .put("/sam-code-bucket")+ .then()+ .statusCode(200);++ byte[] zipBytes = buildHandlerZip();+ given()+ .contentType("application/zip")+ .body(zipBytes)+ .when()+ .put("/sam-code-bucket/app.zip")+ .then()+ .statusCode(200);++ String template = """+ AWSTemplateFormatVersion: '2010-09-09'+ Transform: AWS::Serverless-2016-10-31+ Resources:+ S3Func:+ Type: AWS::Serverless::Function+ Properties:+ FunctionName: sam-s3code-func+ Handler: index.handler+ Runtime: nodejs20.x+ CodeUri: s3://sam-code-bucket/app.zip+ """;++ 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)+ .body(containsString("<StackId>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));++ given()+ .when()+ .get("/2015-03-31/functions/sam-s3code-func")+ .then()+ .statusCode(200)+ .body("Configuration.FunctionName", equalTo("sam-s3code-func"));+ }++ @Test+ void samMixedTemplate_withStandardAndSamResources() {+ String stackName = "sam-mixed-stack";+ stacksToDelete.add(stackName);++ String template = """+ AWSTemplateFormatVersion: '2010-09-09'+ Transform: AWS::Serverless-2016-10-31+ Resources:+ MyQueue:+ Type: AWS::SQS::Queue+ Properties:+ QueueName: sam-mixed-queue+ ProcessorFunc:+ Type: AWS::Serverless::Function+ Properties:+ FunctionName: sam-mixed-func+ Handler: index.handler+ Runtime: nodejs20.x+ InlineCode: "exports.handler = async (e) => ({});"+ """;++ 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)+ .body(containsString("<StackId>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "GetQueueUrl")+ .formParam("QueueName", "sam-mixed-queue")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("sam-mixed-queue"));++ given()+ .when()+ .get("/2015-03-31/functions/sam-mixed-func")+ .then()+ .statusCode(200)+ .body("Configuration.FunctionName", equalTo("sam-mixed-func"));+ }++ @Test+ void templateWithoutTransform_isNotAffected() {+ String stackName = "no-transform-stack";+ stacksToDelete.add(stackName);++ String template = """+ {+ "Resources": {+ "MyQueue": {+ "Type": "AWS::SQS::Queue",+ "Properties": {+ "QueueName": "no-transform-queue"+ }+ }+ }+ }+ """;++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackId>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "GetQueueUrl")+ .formParam("QueueName", "no-transform-queue")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("no-transform-queue"));+ }++ @Test+ void samFunction_viaChangeSet_createsLambda() {+ String stackName = "sam-changeset-stack";+ stacksToDelete.add(stackName);++ String template = """+ AWSTemplateFormatVersion: '2010-09-09'+ Transform: AWS::Serverless-2016-10-31+ Resources:+ CsFunc:+ Type: AWS::Serverless::Function+ Properties:+ FunctionName: sam-changeset-func+ Handler: index.handler+ Runtime: nodejs20.x+ InlineCode: "exports.handler = async () => ({});"+ """;++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateChangeSet")+ .formParam("StackName", stackName)+ .formParam("ChangeSetName", "sam-cs-1")+ .formParam("ChangeSetType", "CREATE")+ .formParam("TemplateBody", template)+ .formParam("Capabilities.member.1", "CAPABILITY_IAM")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<Id>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "ExecuteChangeSet")+ .formParam("StackName", stackName)+ .formParam("ChangeSetName", "sam-cs-1")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));++ given()+ .when()+ .get("/2015-03-31/functions/sam-changeset-func")+ .then()+ .statusCode(200)+ .body("Configuration.FunctionName", equalTo("sam-changeset-func"));+ }++ private static byte[] buildHandlerZip() {+ try {+ var baos = new java.io.ByteArrayOutputStream();+ try (var zos = new java.util.zip.ZipOutputStream(baos)) {+ zos.putNextEntry(new java.util.zip.ZipEntry("index.js"));+ zos.write("exports.handler=async(e)=>({statusCode:200})".getBytes(java.nio.charset.StandardCharsets.UTF_8));+ zos.closeEntry();+ }+ return baos.toByteArray();+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.javanew file mode 100644index 0000000000..f82816ef43--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java@@ -0,0 +1,398 @@+package io.github.hectorvent.floci.services.cloudformation;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.*;++/**+ * Unit tests for the SAM Transform processor logic.+ */+class SamTransformProcessorTest {++ private ObjectMapper objectMapper;+ private SamTransformProcessor processor;++ @BeforeEach+ void setUp() {+ objectMapper = new ObjectMapper();+ processor = new SamTransformProcessor(objectMapper);+ }++ @Test+ void hasSamTransform_withStringTransform() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {"Transform": "AWS::Serverless-2016-10-31", "Resources": {}}+ """);+ assertTrue(processor.hasSamTransform(template));+ }++ @Test+ void hasSamTransform_withArrayTransform() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {"Transform": ["AWS::Serverless-2016-10-31", "AWS::Other"], "Resources": {}}+ """);+ assertTrue(processor.hasSamTransform(template));+ }++ @Test+ void hasSamTransform_withoutTransform() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {"Resources": {"MyBucket": {"Type": "AWS::S3::Bucket"}}}+ """);+ assertFalse(processor.hasSamTransform(template));+ }++ @Test+ void hasSamTransform_withDifferentTransform() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {"Transform": "AWS::Include", "Resources": {}}+ """);+ assertFalse(processor.hasSamTransform(template));+ }++ @Test+ void expandSamTemplate_functionWithInlineCode() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {+ "MyFunc": {+ "Type": "AWS::Serverless::Function",+ "Properties": {+ "Handler": "index.handler",+ "Runtime": "nodejs20.x",+ "InlineCode": "exports.handler = async () => ({});"+ }+ }+ }+ }+ """);++ JsonNode expanded = processor.expandSamTemplate(template);++ // Transform should be removed+ assertTrue(expanded.path("Transform").isMissingNode());++ // Should have Lambda function and IAM role+ JsonNode resources = expanded.path("Resources");+ assertTrue(resources.has("MyFunc"));+ assertTrue(resources.has("MyFuncRole"));++ assertEquals("AWS::Lambda::Function", resources.path("MyFunc").path("Type").asText());+ assertEquals("AWS::IAM::Role", resources.path("MyFuncRole").path("Type").asText());++ // Lambda should have ZipFile code from InlineCode+ JsonNode lambdaProps = resources.path("MyFunc").path("Properties");+ assertEquals("index.handler", lambdaProps.path("Handler").asText());+ assertEquals("nodejs20.x", lambdaProps.path("Runtime").asText());+ assertEquals("exports.handler = async () => ({});",+ lambdaProps.path("Code").path("ZipFile").asText());++ // Role should reference the generated role via Fn::GetAtt+ JsonNode roleRef = lambdaProps.path("Role");+ assertTrue(roleRef.has("Fn::GetAtt"));+ assertEquals("MyFuncRole", roleRef.path("Fn::GetAtt").get(0).asText());+ assertEquals("Arn", roleRef.path("Fn::GetAtt").get(1).asText());+ }++ @Test+ void expandSamTemplate_functionWithExplicitRole() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {+ "MyFunc": {+ "Type": "AWS::Serverless::Function",+ "Properties": {+ "Handler": "index.handler",+ "Runtime": "nodejs20.x",+ "InlineCode": "code",+ "Role": "arn:aws:iam::123456789012:role/my-role"+ }+ }+ }+ }+ """);++ JsonNode expanded = processor.expandSamTemplate(template);+ JsonNode resources = expanded.path("Resources");+ JsonNode lambdaProps = resources.path("MyFunc").path("Properties");++ // Should use the explicit role ARN+ assertEquals("arn:aws:iam::123456789012:role/my-role", lambdaProps.path("Role").asText());+ // Should NOT create a generated role resource+ assertFalse(resources.has("MyFuncRole"));+ }++ @Test+ void expandSamTemplate_functionWithS3CodeUri() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {+ "MyFunc": {+ "Type": "AWS::Serverless::Function",+ "Properties": {+ "Handler": "index.handler",+ "Runtime": "nodejs20.x",+ "CodeUri": "s3://my-bucket/code.zip"+ }+ }+ }+ }+ """);++ JsonNode expanded = processor.expandSamTemplate(template);+ JsonNode code = expanded.path("Resources").path("MyFunc").path("Properties").path("Code");++ assertEquals("my-bucket", code.path("S3Bucket").asText());+ assertEquals("code.zip", code.path("S3Key").asText());+ }++ @Test+ void expandSamTemplate_functionWithCodeUriObject() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {+ "MyFunc": {+ "Type": "AWS::Serverless::Function",+ "Properties": {+ "Handler": "index.handler",+ "Runtime": "nodejs20.x",+ "CodeUri": {+ "Bucket": "my-bucket",+ "Key": "path/to/code.zip",+ "Version": "abc123"+ }+ }+ }+ }+ }+ """);++ JsonNode expanded = processor.expandSamTemplate(template);+ JsonNode code = expanded.path("Resources").path("MyFunc").path("Properties").path("Code");++ assertEquals("my-bucket", code.path("S3Bucket").asText());+ assertEquals("path/to/code.zip", code.path("S3Key").asText());+ assertEquals("abc123", code.path("S3ObjectVersion").asText());+ }++ @Test+ void expandSamTemplate_simpleTable() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {+ "MyTable": {+ "Type": "AWS::Serverless::SimpleTable",+ "Properties": {+ "TableName": "my-table",+ "PrimaryKey": {+ "Name": "pk",+ "Type": "String"+ }+ }+ }+ }+ }+ """);++ JsonNode expanded = processor.expandSamTemplate(template);+ JsonNode resources = expanded.path("Resources");++ assertEquals("AWS::DynamoDB::Table", resources.path("MyTable").path("Type").asText());++ JsonNode tableProps = resources.path("MyTable").path("Properties");+ assertEquals("my-table", tableProps.path("TableName").asText());+ assertEquals("pk", tableProps.path("KeySchema").get(0).path("AttributeName").asText());+ assertEquals("HASH", tableProps.path("KeySchema").get(0).path("KeyType").asText());+ assertEquals("pk", tableProps.path("AttributeDefinitions").get(0).path("AttributeName").asText());+ assertEquals("S", tableProps.path("AttributeDefinitions").get(0).path("AttributeType").asText());+ assertEquals("PAY_PER_REQUEST", tableProps.path("BillingMode").asText());+ }++ @Test+ void expandSamTemplate_simpleTableWithDefaultKey() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {+ "MyTable": {+ "Type": "AWS::Serverless::SimpleTable",+ "Properties": {+ "TableName": "default-key-table"+ }+ }+ }+ }+ """);++ JsonNode expanded = processor.expandSamTemplate(template);+ JsonNode tableProps = expanded.path("Resources").path("MyTable").path("Properties");++ // Default key should be "id" of type "S"+ assertEquals("id", tableProps.path("KeySchema").get(0).path("AttributeName").asText());+ assertEquals("S", tableProps.path("AttributeDefinitions").get(0).path("AttributeType").asText());+ }++ @Test+ void expandSamTemplate_api() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {+ "MyApi": {+ "Type": "AWS::Serverless::Api",+ "Properties": {+ "Name": "test-api",+ "StageName": "prod"+ }+ }+ }+ }+ """);++ JsonNode expanded = processor.expandSamTemplate(template);+ JsonNode resources = expanded.path("Resources");++ // Should create RestApi, Deployment, and Stage+ assertEquals("AWS::ApiGateway::RestApi", resources.path("MyApi").path("Type").asText());+ assertEquals("AWS::ApiGateway::Deployment", resources.path("MyApiDeployment").path("Type").asText());+ assertEquals("AWS::ApiGateway::Stage", resources.path("MyApiStage").path("Type").asText());++ // Stage should have the specified name+ assertEquals("prod",+ resources.path("MyApiStage").path("Properties").path("StageName").asText());+ }++ @Test+ void expandSamTemplate_mixedResources() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {+ "MyBucket": {+ "Type": "AWS::S3::Bucket",+ "Properties": {"BucketName": "my-bucket"}+ },+ "MyFunc": {+ "Type": "AWS::Serverless::Function",+ "Properties": {+ "Handler": "index.handler",+ "Runtime": "nodejs20.x",+ "InlineCode": "code"+ }+ }+ }+ }+ """);++ JsonNode expanded = processor.expandSamTemplate(template);+ JsonNode resources = expanded.path("Resources");++ // Standard resource should be preserved+ assertEquals("AWS::S3::Bucket", resources.path("MyBucket").path("Type").asText());+ assertEquals("my-bucket", resources.path("MyBucket").path("Properties").path("BucketName").asText());++ // SAM resource should be expanded+ assertEquals("AWS::Lambda::Function", resources.path("MyFunc").path("Type").asText());+ assertTrue(resources.has("MyFuncRole"));+ }++ @Test+ void expandSamTemplate_noTransform_returnsUnchanged() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {+ "Resources": {+ "MyBucket": {+ "Type": "AWS::S3::Bucket",+ "Properties": {"BucketName": "my-bucket"}+ }+ }+ }+ """);++ JsonNode result = processor.expandSamTemplate(template);+ assertEquals(template, result);+ }++ @Test+ void expandSamTemplate_functionWithEnvironmentAndTimeout() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {+ "MyFunc": {+ "Type": "AWS::Serverless::Function",+ "Properties": {+ "Handler": "app.handler",+ "Runtime": "python3.12",+ "InlineCode": "def handler(e,c): pass",+ "Timeout": 30,+ "MemorySize": 512,+ "Environment": {+ "Variables": {+ "TABLE": "my-table"+ }+ }+ }+ }+ }+ }+ """);++ JsonNode expanded = processor.expandSamTemplate(template);+ JsonNode lambdaProps = expanded.path("Resources").path("MyFunc").path("Properties");++ assertEquals(30, lambdaProps.path("Timeout").asInt());+ assertEquals(512, lambdaProps.path("MemorySize").asInt());+ assertEquals("my-table", lambdaProps.path("Environment").path("Variables").path("TABLE").asText());+ }++ @Test+ void expandSamTemplate_functionWithSqsEvent() throws Exception {+ JsonNode template = objectMapper.readTree("""+ {+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {+ "MyFunc": {+ "Type": "AWS::Serverless::Function",+ "Properties": {+ "Handler": "index.handler",+ "Runtime": "nodejs20.x",+ "InlineCode": "code",+ "Events": {+ "SqsTrigger": {+ "Type": "SQS",+ "Properties": {+ "Queue": "arn:aws:sqs:us-east-1:123456789012:my-queue",+ "BatchSize": 10+ }+ }+ }+ }+ }+ }+ }+ """);++ JsonNode expanded = processor.expandSamTemplate(template);+ JsonNode resources = expanded.path("Resources");++ // Should create an EventSourceMapping+ assertTrue(resources.has("MyFuncSqsTrigger"));+ assertEquals("AWS::Lambda::EventSourceMapping",+ resources.path("MyFuncSqsTrigger").path("Type").asText());++ JsonNode esmProps = resources.path("MyFuncSqsTrigger").path("Properties");+ assertEquals("MyFunc", esmProps.path("FunctionName").path("Ref").asText());+ assertEquals("arn:aws:sqs:us-east-1:123456789012:my-queue",+ esmProps.path("EventSourceArn").asText());+ assertEquals(10, esmProps.path("BatchSize").asInt());+ }+}