diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java index 9a22f1dbd4..776457efab 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java @@ -246,6 +246,7 @@ public class CloudFormationQueryHandler { .elem("StackName", cs.getStackName()) .elem("Status", cs.getStatus()) .elem("ExecutionStatus", cs.getExecutionStatus()) + .elem("StatusReason", cs.getStatusReason()) .start("Changes"); for (CloudFormationService.ResourceChange change : changes) { xml.start("member") @@ -277,7 +278,7 @@ public class CloudFormationQueryHandler { String stackName = params.getFirst("StackName"); String changeSetName = params.getFirst("ChangeSetName"); try { - cfnService.executeChangeSet(stackName, changeSetName, region); + cfnService.executeChangeSetForRequest(stackName, changeSetName, region); } catch (AwsException e) { return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus()); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 75ac9f3ef6..6e96b236de 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -4141,7 +4141,7 @@ public class CloudFormationResourceProvisioner { JsonNode tracingConfiguration = resolveStateMachineTracingConfiguration(props, engine); JsonNode encryptionConfiguration = resolveStateMachineEncryptionConfiguration(props, engine); - StateMachine existing = findStateMachine(r.getPhysicalId()); + StateMachine existing = findExistingOrStubbedStateMachine(r.getPhysicalId()); String desiredNameMode = hasExplicitName ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED; String previousNameMode = r.getAttributes().get(SFN_NAME_MODE_ATTR); if (existing != null && previousNameMode == null) { @@ -4234,6 +4234,19 @@ public class CloudFormationResourceProvisioner { r.getAttributes().put(SFN_NAME_MODE_ATTR, desiredNameMode); } + /** Matches the non-ARN stub physical id the default provisioning arm writes, {@code -<8 hex>} (see :523). */ + private static final Pattern STUB_PHYSICAL_ID = Pattern.compile("^[A-Za-z0-9]+-[0-9a-f]{8}$"); + + private static boolean isStubPhysicalId(String physicalId) { + return STUB_PHYSICAL_ID.matcher(physicalId).matches(); + } + + /** + * Looks up a state machine by ARN, treating {@code StateMachineDoesNotExist} as "not found". + * An {@code InvalidArn} error is not swallowed here: every caller of this method reads an ARN + * this floci instance itself recorded (a cleanup or rollback snapshot), so a malformed value + * reaching {@code describeStateMachine} is a real anomaly, not a legitimate "not found" case. + */ private StateMachine findStateMachine(String stateMachineArn) { if (stateMachineArn == null || stateMachineArn.isBlank()) { return null; @@ -4248,6 +4261,31 @@ public class CloudFormationResourceProvisioner { } } + /** + * Same as {@link #findStateMachine}, but additionally treats {@code InvalidArn} as "not found" + * when {@code physicalId} matches the stub shape a pre-SAM-expansion floci build wrote + * ({@code -<8 hex>}, produced at :523). A stack whose + * {@code AWS::Serverless::StateMachine} resource was provisioned before floci expanded SAM + * types carries that stub value into its next update; without this, {@code describeStateMachine} + * throws {@code InvalidArn} for it and the update fails instead of creating the real resource. + * Used only at the provisioning entry point, where that upgrade path is legitimate: unlike + * {@link #findStateMachine}'s other callers, a stub here is expected, not an anomaly. + */ + private StateMachine findExistingOrStubbedStateMachine(String physicalId) { + if (physicalId == null || physicalId.isBlank()) { + return null; + } + try { + return stepFunctionsService.describeStateMachine(physicalId); + } catch (AwsException e) { + if ("StateMachineDoesNotExist".equals(e.getErrorCode()) + || ("InvalidArn".equals(e.getErrorCode()) && isStubPhysicalId(physicalId))) { + return null; + } + throw e; + } + } + private String inferStepFunctionsNameMode( StateMachine existing, String stackName, String logicalId) { String base = stackName + "-" + logicalId; @@ -4778,9 +4816,10 @@ public class CloudFormationResourceProvisioner { if (name == null || name.isBlank()) { name = generatePhysicalName(stackName, r.getLogicalId(), 255, false); } + String description = resolveOptional(props, "Description", engine); Map req = new HashMap<>(); req.put("name", name); - req.put("description", resolveOptional(props, "Description", engine)); + req.put("description", description); if (props.has("EndpointConfiguration")) { JsonNode epNode = props.get("EndpointConfiguration"); @@ -4793,6 +4832,35 @@ public class CloudFormationResourceProvisioner { var api = apiGatewayService.createRestApi(region, req); r.setPhysicalId(api.getId()); r.getAttributes().put("RootResourceId", apiGatewayService.getResources(region, api.getId()).get(0).getId()); + + // A declared Body or BodyS3Location is the whole OpenAPI document: measured against real + // AWS, us-east-1, create-change-set, it becomes the RestApi's Body with no synthesized + // AWS::ApiGateway::Resource or AWS::ApiGateway::Method, so the working OpenAPI + // materializer (putRestApi + applyOpenApiSpec) is the only place that turns it into + // resources and methods. The same probe's processed template keeps a declared Name and + // Description in their own properties even when Body.info carries a different title or + // description, but putRestApi overwrites both from the document's info, so the resolved + // Name and Description (null when Description is undeclared, clearing what putRestApi + // just set) are re-applied immediately after. + JsonNode openApiDocument = resolveOpenApiDocument(props, engine); + if (openApiDocument != null) { + apiGatewayService.putRestApi(region, api.getId(), "overwrite", openApiDocument.toString()); + apiGatewayService.updateRestApi(region, api.getId(), + List.of(replacePatchOp("/name", name), replacePatchOp("/description", description))); + } + } + + /** + * A {@code replace} patch operation for {@link ApiGatewayService#updateRestApi}, allowing a + * {@code null} value ({@code Map.of} rejects one) so an undeclared property can still be + * cleared rather than left at whatever {@code putRestApi} last wrote to it. + */ + private Map replacePatchOp(String path, String value) { + Map op = new HashMap<>(); + op.put("op", "replace"); + op.put("path", path); + op.put("value", value); + return op; } private void provisionApiGatewayResource(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, @@ -4934,7 +5002,7 @@ public class CloudFormationResourceProvisioner { */ private void reconcileApiGatewayV2BodyRoutes(StackResource r, String region, String apiId, JsonNode props, CloudFormationTemplateEngine engine) { - JsonNode body = resolveApiGatewayV2OpenApiBody(props, engine); + JsonNode body = resolveOpenApiDocument(props, engine); ApiGatewayV2BodyResourceState previous = null; try { previous = snapshotApiGatewayV2BodyResources(r, region, apiId); @@ -4970,7 +5038,7 @@ public class CloudFormationResourceProvisioner { replacement.authorizerIds()); } - private JsonNode resolveApiGatewayV2OpenApiBody(JsonNode props, CloudFormationTemplateEngine engine) { + private JsonNode resolveOpenApiDocument(JsonNode props, CloudFormationTemplateEngine engine) { if (props == null) { return null; } @@ -4982,7 +5050,7 @@ public class CloudFormationResourceProvisioner { } JsonNode location = engine.resolveNode(props.get("BodyS3Location")); - ApiGatewayV2BodyS3Location bodyS3Location = parseApiGatewayV2BodyS3Location(location); + OpenApiBodyS3Location bodyS3Location = parseOpenApiBodyS3Location(location); try { byte[] document = s3Service.getObject(bodyS3Location.bucket(), bodyS3Location.key(), @@ -5001,14 +5069,14 @@ public class CloudFormationResourceProvisioner { } } - private ApiGatewayV2BodyS3Location parseApiGatewayV2BodyS3Location(JsonNode location) { + private OpenApiBodyS3Location parseOpenApiBodyS3Location(JsonNode location) { if (location != null && location.isTextual()) { String uri = location.asText(); if (uri.startsWith("s3://")) { String withoutScheme = uri.substring("s3://".length()); int slash = withoutScheme.indexOf('/'); if (slash > 0 && slash < withoutScheme.length() - 1) { - return new ApiGatewayV2BodyS3Location(withoutScheme.substring(0, slash), + return new OpenApiBodyS3Location(withoutScheme.substring(0, slash), withoutScheme.substring(slash + 1), null); } } @@ -5016,7 +5084,7 @@ public class CloudFormationResourceProvisioner { String bucket = textOrNull(location, "Bucket"); String key = textOrNull(location, "Key"); if (bucket != null && !bucket.isBlank() && key != null && !key.isBlank()) { - return new ApiGatewayV2BodyS3Location(bucket, key, textOrNull(location, "Version")); + return new OpenApiBodyS3Location(bucket, key, textOrNull(location, "Version")); } } throw new AwsException("ValidationException", @@ -5493,7 +5561,7 @@ public class CloudFormationResourceProvisioner { private record OpenApiAuthorizerBinding(String authorizationType, String authorizerId) {} - private record ApiGatewayV2BodyS3Location(String bucket, String key, String version) {} + private record OpenApiBodyS3Location(String bucket, String key, String version) {} private static final class ApiGatewayV2BodyMaterializationException extends RuntimeException { private final ApiGatewayV2BodyResources resources; 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.java index abf20fcb20..e2ee26e954 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 @@ -223,8 +223,20 @@ public class CloudFormationService implements ResourceProvider { boolean attachToReviewInProgressStack) { String resolvedTemplate = resolveTemplate(templateBody, templateUrl); + // Real CloudFormation runs a declared macro (here, only AWS::Serverless-2016-10-31) + // before it ever evaluates the template's own resources or conditions. On real AWS, + // create-change-set against a template with an invalid SAM resource (for example a local, + // unpackaged DefinitionUri) does not fail the API call: it creates the change set and + // marks it FAILED, with the transform's own error in StatusReason. Match that here instead + // of throwing, so this failure is reported by the change set, not by a 400 on creation. + String samTransformFailureReason = samTransformFailureReason(stackName, resolvedTemplate); + // Reject an unresolvable condition dependency graph up front, before any stack state is // created, so CreateStack/UpdateStack fail synchronously the way real CloudFormation does. + // Unconditional: validateConditionDependencies already returns immediately for any + // template declaring the SAM transform, whether or not that transform succeeded, so + // gating this call on samTransformFailureReason == null duplicates that check for no + // effect. validateConditionDependencies(resolvedTemplate, parameters, region, accountId); // A CREATE change set against a name that already has a stack of any status - including @@ -290,8 +302,14 @@ public class CloudFormationService implements ResourceProvider { cs.setTemplateBody(resolvedTemplate); cs.setParameters(parameters); cs.setCapabilities(capabilities); - cs.setStatus("CREATE_COMPLETE"); - cs.setExecutionStatus("AVAILABLE"); + if (samTransformFailureReason != null) { + cs.setStatus("FAILED"); + cs.setExecutionStatus("UNAVAILABLE"); + cs.setStatusReason(samTransformFailureReason); + } else { + cs.setStatus("CREATE_COMPLETE"); + cs.setExecutionStatus("AVAILABLE"); + } target.getChangeSets().put(changeSetName, cs); created[0] = cs; return target; @@ -301,6 +319,46 @@ public class CloudFormationService implements ResourceProvider { return created[0]; } + /** + * Returns the change set's {@code StatusReason} when {@code templateBody} declares the SAM + * transform and that transform fails, {@code null} when the transform is absent or succeeds. + * The wrapping sentence mirrors real CloudFormation's own framing, measured against real AWS, + * us-east-1: {@code "Transform AWS::Serverless-2016-10-31 failed with: Invalid Serverless + * Application Specification document. Number of errors found: 1. "} followed by the + * transform's own per-resource message. The count is always 1: {@code expandSamTemplate} + * throws on the first bad resource rather than accumulating them. + */ + private String samTransformFailureReason(String stackName, String templateBody) { + JsonNode template; + try { + template = parseTemplate(templateBody); + } catch (Exception e) { + // Template parse failures are reported by validateConditionDependencies and by + // execution itself, with their own messages; not this transform-specific one. + return null; + } + if (!samTransformProcessor.hasSamTransform(template)) { + return null; + } + try { + samTransformProcessor.expandSamTemplate(template); + return null; + } catch (AwsException e) { + return "Transform AWS::Serverless-2016-10-31 failed with: Invalid Serverless " + + "Application Specification document. Number of errors found: 1. " + + e.getMessage(); + } catch (Exception e) { + // Anything other than the transform's own validation error (a ClassCastException or + // NPE from inside expandSamTemplate) is a real bug, not a template-authoring mistake. + // Swallowing it here would report the change set CREATE_COMPLETE while the same + // exception resurfaces unlogged when the change set is later executed. Log it with the + // stack name and let it fail loud instead. + LOG.errorv("Stack {0} SAM transform preflight failed unexpectedly: {1}", + stackName, e.getMessage()); + throw e; + } + } + // ── DescribeChangeSet ───────────────────────────────────────────────────── public ChangeSet describeChangeSet(String stackName, String changeSetName, String region) { @@ -319,6 +377,12 @@ public class CloudFormationService implements ResourceProvider { * executed a template) report every resource with a truthy {@code Condition} as an Add. */ public List computeChangeSetChanges(ChangeSet cs, String region) { + if ("FAILED".equals(cs.getStatus())) { + // A SAM transform failure already recorded by createChangeSet (see + // samTransformFailureReason): the change set carries 0 changes, matching real + // CloudFormation's own CreateChangeSet response for the same failure. + return List.of(); + } Stack stack = getStackOrThrow(cs.getStackName(), region); try { JsonNode newTemplate = parseTemplate(cs.getTemplateBody()); @@ -465,6 +529,34 @@ public class CloudFormationService implements ResourceProvider { return executeChangeSet(stackName, changeSetName, region, regionResolver.getAccountId()); } + /** + * Entry point for the {@code ExecuteChangeSet} operation itself, as opposed to the execute that + * {@code CreateStack}/{@code UpdateStack} run internally right after creating their own change + * set. + * + *

Real CloudFormation refuses to execute a change set that is not {@code AVAILABLE}, for + * example one a failed SAM transform already marked {@code FAILED}/{@code UNAVAILABLE}: it + * throws {@code InvalidChangeSetStatus}, naming the change set's ARN and its current status, + * and leaves the stack exactly where it was. Routing that check through a separate entry point + * keeps {@code CreateStack}/{@code UpdateStack} able to reach {@code CREATE_FAILED} (or its + * update equivalent) when their own change set failed - executing it unconditionally is how + * that failure surfaces on those paths, and floci must still expose it there. + */ + public Future executeChangeSetForRequest(String stackName, String changeSetName, String region) { + Stack stack = getStackOrThrow(stackName, region); + ChangeSet cs = stack.getChangeSets().get(resolveChangeSetName(changeSetName)); + if (cs == null) { + throw new AwsException("ChangeSetNotFoundException", + "ChangeSet [" + changeSetName + "] does not exist", 400); + } + if (!"AVAILABLE".equals(cs.getExecutionStatus())) { + throw new AwsException("InvalidChangeSetStatus", + "ChangeSet [" + cs.getChangeSetId() + "] cannot be executed in its current " + + "status of [" + cs.getStatus() + "]", 400); + } + return executeChangeSet(stackName, changeSetName, region, regionResolver.getAccountId()); + } + /** * Executes a change set, provisioning its resources into {@code accountId}'s namespace. * @@ -472,6 +564,11 @@ public class CloudFormationService implements ResourceProvider { * the downstream service calls would otherwise fall back to the default account. The resources * are materialized under a synthetic request scope bound to {@code accountId} so a single-stack * deployment lands in the caller's account, and a StackSet instance lands in its target account. + * + *

Unlike {@link #executeChangeSetForRequest}, this does not refuse a non-{@code AVAILABLE} + * change set: {@code CreateStack}/{@code UpdateStack} call this directly right after creating + * their own change set, and must still reach {@code CREATE_FAILED} (or its update equivalent) + * when that change set failed, for example from a failed SAM transform. */ public Future executeChangeSet(String stackName, String changeSetName, String region, String accountId) { Stack stack = getStackOrThrow(stackName, region); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java index 80c1cdd922..48fd1b6219 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java @@ -11,6 +11,8 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Expands {@code AWS::Serverless-2016-10-31} SAM resource types into standard CloudFormation @@ -22,6 +24,16 @@ class SamTransformProcessor { private static final Logger LOG = Logger.getLogger(SamTransformProcessor.class); private static final String SAM_TRANSFORM = "AWS::Serverless-2016-10-31"; + /** + * Matches a valid {@code s3://bucket/key} URI, optionally suffixed with a + * {@code ?versionId=} query parameter, the way real SAM packages a {@code DefinitionUri}. + * The key is non-greedy so only a trailing {@code ?versionId=} is split off; S3 permits a + * literal {@code ?} in a key (for example {@code s3://bucket/key?foo=1}), and such a key must + * still match here rather than being rejected as an invalid URI. + */ + private static final Pattern S3_DEFINITION_URI = Pattern.compile( + "^s3://(?[^/?]+)/(?.+?)(?:\\?versionId=(?.+))?$"); + private final ObjectMapper objectMapper; SamTransformProcessor(ObjectMapper objectMapper) { @@ -84,16 +96,37 @@ class SamTransformProcessor { String type = resDef.path("Type").asText(); JsonNode properties = resDef.path("Properties"); + // SAM CLI writes SamResourceId (in Metadata) for every AWS::Serverless::* resource it + // transforms, not only state machines, and CloudFormation carries a resource's + // Metadata/DependsOn/Condition/DeletionPolicy/UpdateReplacePolicy through a transform + // unchanged. Each arm's generated resource lands back at the same logicalId key, so + // copyResourceLevelAttributes runs once per arm, right after that arm builds its node. switch (type) { - case "AWS::Serverless::Function" -> - expandServerlessFunction(logicalId, mergeGlobals(globals, "Function", properties), expandedResources); - case "AWS::Serverless::SimpleTable" -> - expandServerlessSimpleTable(logicalId, mergeGlobals(globals, "SimpleTable", properties), expandedResources); - case "AWS::Serverless::Api" -> - expandServerlessApi(logicalId, mergeGlobals(globals, "Api", properties), expandedResources); - case "AWS::Serverless::HttpApi" -> - expandServerlessHttpApi(logicalId, mergeGlobals(globals, "HttpApi", properties), - httpApiRoutes, expandedResources); + case "AWS::Serverless::Function" -> { + expandServerlessFunction(logicalId, mergeGlobals(globals, "Function", properties), expandedResources); + copyResourceLevelAttributes(resDef, (ObjectNode) expandedResources.path(logicalId)); + } + case "AWS::Serverless::SimpleTable" -> { + expandServerlessSimpleTable(logicalId, mergeGlobals(globals, "SimpleTable", properties), expandedResources); + copyResourceLevelAttributes(resDef, (ObjectNode) expandedResources.path(logicalId)); + } + case "AWS::Serverless::Api" -> { + expandServerlessApi(logicalId, mergeGlobals(globals, "Api", properties), expandedResources); + copyResourceLevelAttributes(resDef, (ObjectNode) expandedResources.path(logicalId)); + } + case "AWS::Serverless::HttpApi" -> { + expandServerlessHttpApi(logicalId, mergeGlobals(globals, "HttpApi", properties), + httpApiRoutes, expandedResources); + copyResourceLevelAttributes(resDef, (ObjectNode) expandedResources.path(logicalId)); + } + case "AWS::Serverless::StateMachine" -> + // Globals.StateMachine is intentionally not merged in: SAM's schema accepts + // exactly one key there (PropagateTags), unimplemented here, and + // mergeGlobals deep-merges any key it is given, which would make floci + // honour a Globals.StateMachine.Role that AWS itself rejects. + // copyResourceLevelAttributes runs inside expandServerlessStateMachine + // itself (its one caller already owning the source resDef). + expandServerlessStateMachine(logicalId, resDef, expandedResources); default -> LOG.debugv("Unsupported SAM resource type: {0} ({1})", type, logicalId); } } @@ -212,16 +245,11 @@ class SamTransformProcessor { copyIfPresent(properties, "Description", apiProps); // Preserve inline OpenAPI route definitions so the ApiGatewayV2 provisioner can - // materialize the routes and integrations declared by SAM DefinitionBody. - JsonNode definitionBody = properties.path("DefinitionBody"); - if (!definitionBody.isMissingNode() && !definitionBody.isNull()) { - apiProps.set("Body", definitionBody.deepCopy()); - } else { - ObjectNode bodyS3Location = buildHttpApiBodyS3Location(properties.path("DefinitionUri")); - if (bodyS3Location != null) { - apiProps.set("BodyS3Location", bodyS3Location); - } - } + // materialize the routes and integrations declared by SAM DefinitionBody. An HttpApi + // declaring neither DefinitionBody nor DefinitionUri is also accepted: measured against + // real AWS, us-east-1, create-change-set, it still expands to a bare + // AWS::ApiGatewayV2::Api and its default stage, carrying no Body and no BodyS3Location. + applyDefinitionSource(logicalId, properties, apiProps); apiDef.set("Properties", apiProps); resources.set(logicalId, apiDef); @@ -1051,6 +1079,15 @@ class SamTransformProcessor { } copyIfPresent(properties, "Description", apiProps); + // Preserve the inline OpenAPI document so the REST API provisioner can materialize the + // resources and methods declared by SAM DefinitionBody. An Api declaring neither + // DefinitionBody nor DefinitionUri is also accepted: measured against real AWS, + // us-east-1, create-change-set, it synthesizes a Body of {"swagger": "2.0", "info": { + // "version": "1.0", "title": {"Ref": "AWS::StackName"}}, "paths": {}}, while floci emits + // no Body and no BodyS3Location for that case. The paths are empty either way, so the + // runtime outcome (no method reachable) is the same, even though the stored Body differs. + applyDefinitionSource(logicalId, properties, apiProps); + apiDef.set("Properties", apiProps); resources.set(logicalId, apiDef); @@ -1091,45 +1128,255 @@ class SamTransformProcessor { } /** - * {@code DefinitionUri} is SAM's S3-backed OpenAPI source. ApiGatewayV2 accepts the same - * source through {@code BodyS3Location}, with the S3 URI split into its bucket and key. + * Expands {@code AWS::Serverless::StateMachine} into {@code AWS::StepFunctions::StateMachine}. + * Every mapped value is copied as a node, never read with {@code asText()}: {@code RoleArn} + * and {@code StateMachineName} are commonly intrinsics ({@code Fn::GetAtt}, {@code Fn::Sub}) + * in the templates SAM itself produces, and {@code JsonNode.asText()} on an object node + * silently returns {@code ""}, dropping the intrinsic instead of failing loudly. + * + *

Every sibling key of {@code Type} and {@code Properties} on the SAM resource node (for + * example {@code Metadata}, {@code DependsOn}, {@code Condition}, {@code DeletionPolicy}, + * {@code UpdateReplacePolicy}) is carried onto the emitted native resource, the way + * CloudFormation itself carries a transformed resource's own attributes through. + * + *

Does not handle {@code Events}, {@code Policies}, {@code PermissionsBoundary}, + * {@code AutoPublishAlias} or {@code UseAliasAsEventTarget}: none appeared in the + * {@code AWS::Serverless::StateMachine} declarations measured against real AWS. */ - private ObjectNode buildHttpApiBodyS3Location(JsonNode definitionUri) { - if (definitionUri == null || definitionUri.isMissingNode() || definitionUri.isNull()) { - return null; + private void expandServerlessStateMachine(String logicalId, JsonNode samResource, ObjectNode resources) { + resources.remove(logicalId); + JsonNode properties = samResource.path("Properties"); + + JsonNode definition = properties.path("Definition"); + JsonNode definitionUri = properties.path("DefinitionUri"); + boolean hasDefinition = isPropertyPresent(definition); + boolean hasDefinitionUri = isPropertyPresent(definitionUri); + rejectBothDefinitionSources(logicalId, "Definition", "DefinitionUri", hasDefinition && hasDefinitionUri); + if (!hasDefinition && !hasDefinitionUri) { + throw new AwsException("ValidationError", + "Resource with id [" + logicalId + "] is invalid. Either 'Definition' or " + + "'DefinitionUri' property must be specified.", 400); } - ObjectNode location = objectMapper.createObjectNode(); + + ObjectNode stateMachineDef = objectMapper.createObjectNode(); + stateMachineDef.put("Type", "AWS::StepFunctions::StateMachine"); + copyResourceLevelAttributes(samResource, stateMachineDef); + ObjectNode smProps = objectMapper.createObjectNode(); + + copyRenamed(properties, "Name", smProps, "StateMachineName"); + copyRenamed(properties, "Type", smProps, "StateMachineType"); + copyRenamed(properties, "Role", smProps, "RoleArn"); + copyRenamed(properties, "Logging", smProps, "LoggingConfiguration"); + copyRenamed(properties, "Tracing", smProps, "TracingConfiguration"); + copyIfPresent(properties, "DefinitionSubstitutions", smProps); + if (hasDefinition) { + smProps.set("Definition", definition.deepCopy()); + } else { + resolveDefinitionUriOrThrow(definitionUri, "DefinitionS3Location", logicalId, smProps); + } + + smProps.set("Tags", samTagsToCfnTags(properties.path("Tags"))); + + stateMachineDef.set("Properties", smProps); + resources.set(logicalId, stateMachineDef); + } + + /** + * Copies every sibling key of {@code Type} and {@code Properties} from {@code source} onto + * {@code target}, the way CloudFormation carries a resource's {@code Metadata}, + * {@code DependsOn}, {@code Condition}, {@code DeletionPolicy} and + * {@code UpdateReplacePolicy} through a transform unchanged. + */ + private void copyResourceLevelAttributes(JsonNode source, ObjectNode target) { + Iterator> fields = source.fields(); + while (fields.hasNext()) { + Map.Entry field = fields.next(); + String key = field.getKey(); + if ("Type".equals(key) || "Properties".equals(key)) { + continue; + } + target.set(key, field.getValue().deepCopy()); + } + } + + /** + * Converts SAM's string-to-string {@code Tags} map into the {@code {Key, Value}} list + * {@code AWS::StepFunctions::StateMachine} reads (see {@code parseCfnTags} in + * {@code CloudFormationResourceProvisioner}, which returns an empty set for anything that is + * not an array; a verbatim map copy would silently tag nothing). Emitted unconditionally, + * even for an absent or empty {@code Tags} map: measured against real AWS, us-east-1, a + * change set's Processed template for a state machine with no source {@code Tags} declared + * still carried exactly {@code [{"Key": "stateMachine:createdBy", "Value": "SAM"}]}, so real + * SAM adds this tag regardless of what the template declares. + * + *

A tag value keeps its own JSON type (number, intrinsic) in this expanded template. The + * native provisioner's {@code parseCfnTags} still reads every value with {@code asText("")} + * once it applies the tags to the state machine, so the type is preserved only up to the + * expanded template, not into the deployed resource. + */ + private ArrayNode samTagsToCfnTags(JsonNode tagsMap) { + ArrayNode tags = objectMapper.createArrayNode(); + ObjectNode samTag = objectMapper.createObjectNode(); + samTag.put("Key", "stateMachine:createdBy"); + samTag.put("Value", "SAM"); + tags.add(samTag); + + if (tagsMap.isObject()) { + Iterator> fields = tagsMap.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + ObjectNode tag = objectMapper.createObjectNode(); + tag.put("Key", entry.getKey()); + tag.set("Value", entry.getValue().deepCopy()); + tags.add(tag); + } + } + return tags; + } + + /** Copies {@code source.} to {@code target.} when present and non-null. */ + private void copyRenamed(JsonNode source, String field, ObjectNode target, String targetField) { + JsonNode value = source.path(field); + if (isPropertyPresent(value)) { + target.set(targetField, value.deepCopy()); + } + } + + /** True when {@code value} is neither an absent property nor an explicit JSON null. */ + private boolean isPropertyPresent(JsonNode value) { + return !value.isMissingNode() && !value.isNull(); + } + + /** + * Resolves a resource's {@code Body} or {@code BodyS3Location} from its {@code DefinitionBody} + * or {@code DefinitionUri} properties and sets it on {@code apiProps}, rejecting a resource + * that declares both. Shared by {@link #expandServerlessApi} ({@code AWS::ApiGateway::RestApi}'s + * {@code Body}/{@code BodyS3Location}) and {@link #expandServerlessHttpApi} + * ({@code AWS::ApiGatewayV2::Api}'s {@code Body}/{@code BodyS3Location}): both resource types + * accept the identical {@code DefinitionBody}/{@code DefinitionUri} shape and the identical + * mutual-exclusion rule. + */ + private void applyDefinitionSource(String logicalId, JsonNode properties, ObjectNode apiProps) { + JsonNode definitionBody = properties.path("DefinitionBody"); + JsonNode definitionUri = properties.path("DefinitionUri"); + boolean hasDefinitionBody = isPropertyPresent(definitionBody); + boolean hasDefinitionUri = isPropertyPresent(definitionUri); + rejectBothDefinitionSources(logicalId, "DefinitionUri", "DefinitionBody", hasDefinitionUri && hasDefinitionBody); + + if (hasDefinitionBody) { + apiProps.set("Body", definitionBody.deepCopy()); + } else if (hasDefinitionUri) { + resolveDefinitionUriOrThrow(definitionUri, "BodyS3Location", logicalId, apiProps); + } + } + + /** + * Rejects a resource that declares both of a pair of mutually exclusive definition-source + * properties, with AWS's own two-property wording. Shared by {@link #expandServerlessStateMachine} + * (for {@code Definition}/{@code DefinitionUri}) and {@link #applyDefinitionSource} (for + * {@code DefinitionUri}/{@code DefinitionBody}, itself shared by the + * {@code AWS::Serverless::Api} and {@code AWS::Serverless::HttpApi} arms): measured against + * real AWS, us-east-1, {@code create-change-set}, both resource types are rejected before a + * single resource is provisioned, and each names its two properties in its own order, + * {@code firstPropertyName} before {@code secondPropertyName}. + */ + private void rejectBothDefinitionSources(String logicalId, String firstPropertyName, + String secondPropertyName, boolean bothDeclared) { + if (bothDeclared) { + throw new AwsException("ValidationError", + "Resource with id [" + logicalId + "] is invalid. Specify either '" + firstPropertyName + + "' or '" + secondPropertyName + "' property and not both.", 400); + } + } + + /** + * Splits a SAM {@code *Uri} property into the literal {@code {Bucket, Key}} (or + * {@code {Bucket, Key, Version}}) shape the native ApiGatewayV2 {@code BodyS3Location} and + * Step Functions {@code DefinitionS3Location} properties both accept. Accepts a textual + * {@code s3://bucket/key} URI, optionally suffixed with {@code ?versionId=}, or an object + * form carrying non-null {@code Bucket} and {@code Key} values. Shared by + * {@link #applyDefinitionSource} (for {@code DefinitionUri} to {@code BodyS3Location}, itself + * shared by the {@code AWS::Serverless::Api} and {@code AWS::Serverless::HttpApi} arms) and + * {@link #expandServerlessStateMachine} (for {@code DefinitionUri} to + * {@code DefinitionS3Location}); {@link #resolveDefinitionUriOrThrow} is every caller's single + * entry point, so this predicate for "an S3 location is a literal Bucket and a literal Key" + * lives here once. + * + *

Returns {@code null} whenever the value cannot be resolved to a literal Bucket and Key: + * an absent or null property; a textual value that is not a valid {@code s3://bucket/key} + * URI (a local path or an {@code s3://} value with no key); an object missing {@code Bucket} + * or {@code Key}, or carrying either as an explicit JSON null (YAML's {@code Key:} with no + * value parses this way); or a value of any other JSON type (array, number, boolean). An + * object whose {@code Bucket}/{@code Key} is itself an unresolved intrinsic (for example + * {@code Ref} or {@code Fn::Sub}) is not distinguished from one carrying a literal value + * here: {@link #resolveDefinitionUriOrThrow} only calls this method for the top-level + * {@code DefinitionUri} node, and an intrinsic at that level (rather than nested inside + * {@code Bucket}/{@code Key}) is the shape measured against real AWS and rejected. + */ + private ObjectNode samUriToS3Location(JsonNode definitionUri) { if (definitionUri.isTextual()) { - String uri = definitionUri.asText(); - if (!uri.startsWith("s3://")) { + Matcher matcher = S3_DEFINITION_URI.matcher(definitionUri.asText()); + if (!matcher.matches()) { return null; } - String withoutScheme = uri.substring("s3://".length()); - int slash = withoutScheme.indexOf('/'); - if (slash <= 0 || slash == withoutScheme.length() - 1) { - return null; + ObjectNode location = objectMapper.createObjectNode(); + location.put("Bucket", matcher.group("bucket")); + location.put("Key", matcher.group("key")); + String version = matcher.group("version"); + if (version != null) { + location.put("Version", version); } - location.put("Bucket", withoutScheme.substring(0, slash)); - location.put("Key", withoutScheme.substring(slash + 1)); return location; } if (definitionUri.isObject()) { + ObjectNode location = objectMapper.createObjectNode(); copyIfPresent(definitionUri, "Bucket", location); copyIfPresent(definitionUri, "Key", location); copyIfPresent(definitionUri, "Version", location); - // An intrinsic expression (for example Ref or Fn::Sub) cannot be split until the - // CloudFormation engine resolves it during provisioning. Preserve it as-is instead - // of silently dropping the HttpApi definition and its routes. - return location.has("Bucket") && location.has("Key") ? location : definitionUri.deepCopy(); + return location.has("Bucket") && location.has("Key") ? location : null; } return null; } - private void copyIfPresent(JsonNode source, String field, ObjectNode target) { - JsonNode value = source.path(field); - if (!value.isMissingNode() && !value.isNull()) { - target.set(field, value.deepCopy()); + /** + * Resolves {@code definitionUri} to a literal Bucket/Key location and sets it on + * {@code target.}, or throws when it cannot be resolved. Shared by + * {@code AWS::Serverless::StateMachine} and {@link #applyDefinitionSource} (itself shared by + * the {@code AWS::Serverless::Api} and {@code AWS::Serverless::HttpApi} arms): real AWS + * (measured against us-east-1 via {@code create-change-set}) rejects every unresolvable + * {@code DefinitionUri} shape with the same wording on both resource types, before + * CloudFormation ever sees the resource, so both fail the SAM transform itself rather than + * reaching provisioning with no usable definition. + * + *

Both callers check {@code definitionUri} for presence before calling this method: + * {@link #expandServerlessStateMachine} only reaches this call once it has rejected the + * "neither Definition nor DefinitionUri" and "both" shapes, and {@link #applyDefinitionSource} + * only reaches it once it knows {@code DefinitionBody} is absent and {@code DefinitionUri} is + * present. {@code definitionUri} here is therefore always present and non-null. + */ + private void resolveDefinitionUriOrThrow(JsonNode definitionUri, String propertyName, String logicalId, + ObjectNode target) { + ObjectNode s3Location = samUriToS3Location(definitionUri); + if (s3Location != null) { + target.set(propertyName, s3Location); + return; } + String reason; + if (definitionUri.isTextual()) { + reason = "'DefinitionUri' is not a valid S3 Uri of the form 's3://bucket/key' " + + "with optional versionId query parameter."; + } else if (definitionUri.isObject()) { + reason = "'DefinitionUri' requires Bucket and Key properties to be specified."; + } else { + reason = "Type of property 'DefinitionUri' is invalid."; + } + throw new AwsException("ValidationError", + "Resource with id [" + logicalId + "] is invalid. " + reason, 400); + } + + /** Copies {@code source.} to {@code target.} when present and non-null. */ + private void copyIfPresent(JsonNode source, String field, ObjectNode target) { + copyRenamed(source, field, target, field); } private String mapSamAttributeType(String samType) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java index 9d23766664..cff7ecced7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java @@ -5125,6 +5125,84 @@ class CloudFormationIntegrationTest { .body("item[0].type", equalTo("TOKEN")); } + // A native AWS::ApiGateway::RestApi's Body is not SAM-only: the same provisioner materializes + // it for a hand-written template, so a declared Body must create the resources and methods + // its OpenAPI document describes, not sit ignored as it did before. + @Test + void createStack_withApiGatewayRestApiBody_createsMethodFromOpenApiDocument() { + String stackName = "cfn-apigw-restapi-body-stack"; + String template = """ + { + "Resources": { + "RestApi": { + "Type": "AWS::ApiGateway::RestApi", + "Properties": { + "Name": "cfn-apigw-restapi-body-api", + "Body": { + "openapi": "3.0.1", + "paths": { + "/hello": { + "get": { + "x-amazon-apigateway-integration": { "type": "MOCK" } + } + } + } + } + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CREATE_COMPLETE")); + + String resourcesXml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + + String apiId = physicalIdByLogicalId(resourcesXml, "RestApi"); + + String helloResourceId = given() + .when() + .get("/restapis/" + apiId + "/resources") + .then() + .statusCode(200) + .body("item.path", hasItem("/hello")) + .extract() + .path("item.find { it.path == '/hello' }.id"); + + given() + .when() + .get("/restapis/" + apiId + "/resources/" + helloResourceId + "/methods/GET/integration") + .then() + .statusCode(200) + .body("type", equalTo("MOCK")); + } + // ── Issue #1163: AWS::ApiGateway::Deployment with inline StageName creates the stage ── @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStepFunctionsCleanupIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStepFunctionsCleanupIntegrationTest.java index 5c8b2cc81f..438f67699b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStepFunctionsCleanupIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStepFunctionsCleanupIntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.cloudformation; +import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; @@ -13,6 +14,7 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -161,6 +163,121 @@ class CloudFormationStepFunctionsCleanupIntegrationTest { deleteStack(stackName); } + @Test + void updateAfterStubUpgradeProvisionsTheRealStateMachine() { + // A stack that was created by a floci build that did not yet expand + // AWS::Serverless::StateMachine had this resource stubbed with a non-ARN physical id + // (-<8 hex>, see CloudFormationResourceProvisioner's default provisioning arm). + // Its next update must provision the real state machine instead of failing with InvalidArn + // when findStateMachine tries to describe that non-ARN value. + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "sfn-stub-upgrade-" + suffix; + String logicalId = "MyMachine"; + String stateMachineName = "sfn-stub-upgrade-machine-" + suffix; + + String stubbedTemplate = """ + { + "Resources": { + "%s": { + "Type": "AWS::Foo::Bar", + "Properties": {} + } + } + } + """.formatted(logicalId); + createStack(stackName, stubbedTemplate); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("" + logicalId + "-")); + + String upgradedTemplate = """ + { + "Resources": { + "%s": { + "Type": "AWS::StepFunctions::StateMachine", + "Properties": { + "StateMachineName": "%s", + "RoleArn": "arn:aws:iam::000000000000:role/sfn-stub-upgrade-role", + "DefinitionString": "{\\"StartAt\\":\\"Done\\",\\"States\\":{\\"Done\\":{\\"Type\\":\\"Pass\\",\\"End\\":true}}}" + } + } + } + } + """.formatted(logicalId, stateMachineName); + updateStack(stackName, upgradedTemplate); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("UPDATE_COMPLETE")); + + assertStateMachine(stateMachineArn(stateMachineName), "Done"); + + deleteStack(stackName); + } + + @Test + void replacementCleanupWithMalformedPreviousArnReportsFailureInsteadOfSilentSuccess() { + // findStateMachine's InvalidArn widening exists for the stub-upgrade path above (the + // provisioning entry point, :4144, reading a pre-SAM-expansion stub physical id). The + // cleanup snapshot read here (:4512) carries an ARN this floci build itself recorded, so + // an InvalidArn from describeStateMachine on it is a real anomaly, not a legitimate + // "already gone" case, and must not be read as cleanup success. The first + // describeStateMachine(oldArn) call belongs to the provisioning entry point (real + // behaviour, the old machine genuinely still exists there); only the second, from cleanup, + // is forced to simulate the anomaly. + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "sfn-cleanup-invalidarn-" + suffix; + String oldName = "sfn-cleanup-invalidarn-old-" + suffix; + String newName = "sfn-cleanup-invalidarn-new-" + suffix; + String exportName = "sfn-cleanup-invalidarn-export-" + suffix; + String oldArn = stateMachineArn(oldName); + String newArn = stateMachineArn(newName); + + createStack(stackName, template(oldName, "old-definition", "old-output", exportName)); + + Mockito.doCallRealMethod() + .doThrow(new AwsException("InvalidArn", "simulated malformed ARN", 400)) + .when(stepFunctionsService) + .describeStateMachine(eq(oldArn)); + + updateStack(stackName, template(newName, "new-definition", "new-output", exportName)); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("UPDATE_COMPLETE")) + .body(containsString("")) + .body(containsString(oldArn)); + + verify(stepFunctionsService, never()) + .deleteStateMachineIfRevisionMatches(eq(oldArn), anyString()); + assertStateMachine(newArn, "new-definition"); + + Mockito.doCallRealMethod() + .when(stepFunctionsService) + .describeStateMachine(eq(oldArn)); + deleteStack(stackName); + stepFunctionsService.deleteStateMachine(oldArn); + } + private static void createStack(String stackName, String templateBody) { given() .contentType("application/x-www-form-urlencoded") 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.java index 1a0a98da98..c9f15f3acf 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java @@ -17,6 +17,7 @@ import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.Matchers.nullValue; @QuarkusTest @@ -469,6 +470,149 @@ class SamTransformIntegrationTest { assertThat(resourcesXml, not(containsString("AWS::Serverless::Api"))); } + @Test + void samApi_definitionBodyCreatesApiGatewayMethods() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "sam-api-body-" + suffix; + String apiName = "sam-api-body-" + suffix; + stacksToDelete.add(stackName); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + MyApi: + Type: AWS::Serverless::Api + Properties: + Name: %s + StageName: prod + DefinitionBody: + openapi: 3.0.1 + paths: + /hello: + get: + x-amazon-apigateway-integration: + type: MOCK + /widgets: + post: + x-amazon-apigateway-integration: + type: MOCK + """.formatted(apiName); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + waitForStackStatus(stackName, "CREATE_COMPLETE"); + + String apiId = given() + .when() + .get("/restapis") + .then() + .statusCode(200) + .body("item.find { it.name == '" + apiName + "' }.name", equalTo(apiName)) + .extract() + .path("item.find { it.name == '" + apiName + "' }.id"); + + String helloResourceId = given() + .when() + .get("/restapis/" + apiId + "/resources") + .then() + .statusCode(200) + .body("item.path", hasItems("/hello", "/widgets")) + .extract() + .path("item.find { it.path == '/hello' }.id"); + + given() + .when() + .get("/restapis/" + apiId + "/resources/" + helloResourceId + "/methods/GET/integration") + .then() + .statusCode(200) + .body("type", equalTo("MOCK")); + } + + @Test + void samApi_declaredNameAndDescriptionSurviveMaterializedDefinitionBody() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "sam-api-name-" + suffix; + String apiName = "sam-api-name-" + suffix; + String apiDescription = "declared-description-" + suffix; + stacksToDelete.add(stackName); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + MyApi: + Type: AWS::Serverless::Api + Properties: + Name: %s + Description: %s + DefinitionBody: + openapi: 3.0.1 + info: {title: title-from-document, description: description-from-document, version: '1.0'} + paths: + /hello: + get: + x-amazon-apigateway-integration: + type: MOCK + """.formatted(apiName, apiDescription); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + waitForStackStatus(stackName, "CREATE_COMPLETE"); + + // putRestApi overwrites Name and Description from the DefinitionBody's info, so the + // provisioner re-applies the declared Name and Description immediately after: this + // proves what floci's provisioner does with the processed template, not what real + // AWS's runtime prefers. The /hello method assertion below proves the reapply runs on + // the same path that also turns the DefinitionBody into resources and methods, so a + // provisioner that never reads DefinitionBody at all cannot pass this test. + String apiId = given() + .when() + .get("/restapis") + .then() + .statusCode(200) + .body("item.name", hasItem(apiName)) + .body("item.name", not(hasItem("title-from-document"))) + .body("item.find { it.name == '" + apiName + "' }.description", equalTo(apiDescription)) + .body("item.description", not(hasItem("description-from-document"))) + .extract() + .path("item.find { it.name == '" + apiName + "' }.id"); + + String helloResourceId = given() + .when() + .get("/restapis/" + apiId + "/resources") + .then() + .statusCode(200) + .body("item.path", hasItem("/hello")) + .extract() + .path("item.find { it.path == '/hello' }.id"); + + given() + .when() + .get("/restapis/" + apiId + "/resources/" + helloResourceId + "/methods/GET/integration") + .then() + .statusCode(200) + .body("type", equalTo("MOCK")); + } + @Test void samHttpApi_definitionBodyCreatesApiGatewayV2Routes() { String suffix = Long.toString(System.nanoTime(), 36); @@ -607,7 +751,60 @@ class SamTransformIntegrationTest { } @Test - void samHttpApi_intrinsicDefinitionUriCreatesApiGatewayV2Routes() { + void samHttpApi_intrinsicDefinitionUriIsRejected() { + // Real AWS (measured against us-east-1 via create-change-set) rejects an HttpApi + // DefinitionUri that never resolves to a literal Bucket/Key the same way it rejects that + // shape on a StateMachine: expandServerlessHttpApi shares the DefinitionUri guard with + // expandServerlessStateMachine, so the transform fails before a single resource is + // provisioned, rather than importing the intrinsic as an unusable BodyS3Location. + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "sam-http-api-uri-" + suffix; + String apiName = "sam-http-api-uri-" + suffix; + stacksToDelete.add(stackName); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + HttpApi: + Type: AWS::Serverless::HttpApi + Properties: + Name: %s + DefinitionUri: + Fn::Sub: s3://${SpecBucket}/openapi.json + """.formatted(apiName); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + waitForStackStatus(stackName, "CREATE_FAILED"); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString("CREATE_COMPLETE"))) + // XmlBuilder.elem escapes the single quotes AWS's own wording uses around + // 'DefinitionUri' to '. + .body(containsString("Resource with id [HttpApi] is invalid. " + + "'DefinitionUri' requires Bucket and Key properties to be " + + "specified.")); + } + + @Test + void samHttpApi_definitionUriCreatesApiGatewayV2Routes() { String suffix = Long.toString(System.nanoTime(), 36); String stackName = "sam-http-api-uri-" + suffix; String apiName = "sam-http-api-uri-" + suffix; @@ -638,8 +835,7 @@ class SamTransformIntegrationTest { Type: AWS::Serverless::HttpApi Properties: Name: %s - DefinitionUri: - Fn::Sub: s3://%s/openapi.json + DefinitionUri: s3://%s/openapi.json """.formatted(apiName, bucketName); given() @@ -962,6 +1158,412 @@ class SamTransformIntegrationTest { .body("Configuration.FunctionName", equalTo("sam-changeset-func")); } + @Test + void samStateMachine_createsStepFunctionsStateMachine() { + String stackName = "sam-sfn-stack"; + stacksToDelete.add(stackName); + + given() + .when() + .put("/sam-asl-bucket") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .body("{\"StartAt\":\"Done\",\"States\":{\"Done\":{\"Type\":\"Pass\",\"End\":true}}}") + .when() + .put("/sam-asl-bucket/orders.asl.json") + .then() + .statusCode(200); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + OrdersStateMachine: + Type: AWS::Serverless::StateMachine + Properties: + Name: sam-orders-sm + Type: STANDARD + Role: arn:aws:iam::000000000000:role/orders-sfn-role + DefinitionUri: s3://sam-asl-bucket/orders.asl.json + Outputs: + MachineArn: + Value: !GetAtt OrdersStateMachine.Arn + MachineName: + Value: !GetAtt OrdersStateMachine.Name + MachineRevisionId: + Value: !GetAtt OrdersStateMachine.StateMachineRevisionId + """; + + 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("")); + + waitForStackStatus(stackName, "CREATE_COMPLETE"); + + String describeStacks = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + + // AGENTS.md:289-291 asks for the exact Fn::GetAtt key set the provisioner publishes + // (CloudFormationResourceProvisioner.java:4231-4233): Arn, Name, StateMachineRevisionId. + // Asserting only "not a stub ARN" (as red loop 2 did) would also pass on an empty Output. + String machineArn = stackOutputValue(describeStacks, "MachineArn"); + assertThat(machineArn, startsWith("arn:aws:states:")); + assertThat(machineArn, not(containsString("arn:aws:stub:::"))); + assertThat(stackOutputValue(describeStacks, "MachineName"), equalTo("sam-orders-sm")); + assertThat(stackOutputValue(describeStacks, "MachineRevisionId"), not(equalTo(""))); + + given() + .header("X-Amz-Target", "AWSStepFunctions.ListStateMachines") + .contentType("application/x-amz-json-1.0") + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("stateMachines.name", hasItem("sam-orders-sm")); + } + + @Test + void samStateMachine_withLocalDefinitionUri_createFails() { + // This is the shape all 172 source templates measured across 19 repositories carry: + // `sam package` never ran, so DefinitionUri is still a local path. Real SAM rejects this + // the same way, and here the ValidationError is thrown by expandServerlessStateMachine + // inside expandSamTemplate, called before the per-resource provisioning loop starts. With + // no resource attempted, there is nothing to roll back: the stack lands directly on + // CREATE_FAILED, not ROLLBACK_COMPLETE. + String stackName = "sam-sfn-local-uri-stack"; + stacksToDelete.add(stackName); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + OrdersStateMachine: + Type: AWS::Serverless::StateMachine + Properties: + Name: sam-orders-local-sm + Role: arn:aws:iam::000000000000:role/orders-sfn-role + DefinitionUri: ./src/stepFunctions/orders.asl.json + """; + + 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("")); + + waitForStackStatus(stackName, "CREATE_FAILED"); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString("CREATE_COMPLETE"))) + // XmlBuilder.elem escapes the single quotes AWS's own wording uses around + // 'DefinitionUri' and 's3://bucket/key' to '. + .body(containsString("Resource with id [OrdersStateMachine] is invalid. " + + "'DefinitionUri' is not a valid S3 Uri of the form " + + "'s3://bucket/key' with optional versionId query parameter.")); + + // Nothing was provisioned: the transform rejects the whole template before the + // per-resource loop attempts a single resource, so no state machine (stub or real) + // ever appears in the resource list. + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString(""))) + .body(not(containsString("AWS::StepFunctions::StateMachine"))); + } + + @Test + void samStateMachine_withLocalDefinitionUri_createChangeSetReportsFailedStatus() { + // Measured against real AWS, us-east-1, aws cloudformation create-change-set + // does not reject this API call with an HTTP error: it creates the change set and marks + // it FAILED, reporting the transform's own message in StatusReason with 0 Changes. + String stackName = "sam-sfn-changeset-local-uri-stack"; + stacksToDelete.add(stackName); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + OrdersStateMachine: + Type: AWS::Serverless::StateMachine + Properties: + Name: sam-orders-changeset-local-sm + Role: arn:aws:iam::000000000000:role/orders-sfn-role + DefinitionUri: ./src/stepFunctions/orders.asl.json + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "initial") + .formParam("ChangeSetType", "CREATE") + .formParam("TemplateBody", template) + .formParam("Capabilities.member.1", "CAPABILITY_IAM") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "initial") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("FAILED")) + .body(containsString("UNAVAILABLE")) + .body(containsString("Transform AWS::Serverless-2016-10-31 failed " + + "with: Invalid Serverless Application Specification document. Number of " + + "errors found: 1. Resource with id [OrdersStateMachine] is invalid. " + + "'DefinitionUri' is not a valid S3 Uri of the form " + + "'s3://bucket/key' with optional versionId query " + + "parameter.")) + .body(not(containsString(""))); + } + + @Test + void samStateMachine_withIntrinsicDefinitionUri_createChangeSetReportsFailedStatus() { + // Measured against real AWS, us-east-1: DefinitionUri as an intrinsic (no literal + // Bucket/Key) fails the SAM transform itself with the object-form wording, the same + // Status: FAILED / ExecutionStatus: UNAVAILABLE / 0 Changes shape as the local-path and + // bucket-only cases. Left unrejected, this shape reaches CREATE_COMPLETE against floci + // while real AWS already reports FAILED at create-change-set time. + String stackName = "sam-sfn-changeset-intrinsic-uri-stack"; + stacksToDelete.add(stackName); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + OrdersStateMachine: + Type: AWS::Serverless::StateMachine + Properties: + Name: sam-orders-changeset-intrinsic-sm + Role: arn:aws:iam::000000000000:role/orders-sfn-role + DefinitionUri: + Fn::Sub: s3://${SpecBucket}/orders.asl.json + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "initial") + .formParam("ChangeSetType", "CREATE") + .formParam("TemplateBody", template) + .formParam("Capabilities.member.1", "CAPABILITY_IAM") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "initial") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("FAILED")) + .body(containsString("UNAVAILABLE")) + .body(containsString("Transform AWS::Serverless-2016-10-31 failed " + + "with: Invalid Serverless Application Specification document. Number of " + + "errors found: 1. Resource with id [OrdersStateMachine] is invalid. " + + "'DefinitionUri' requires Bucket and Key properties to be " + + "specified.")) + .body(not(containsString(""))); + } + + @Test + void samStateMachine_withLocalDefinitionUri_executeChangeSetIsRejected() { + // A change set a failed SAM transform already marked FAILED/UNAVAILABLE cannot be + // executed. Real CloudFormation refuses ExecuteChangeSet with InvalidChangeSetStatus, + // naming the change set's ARN and its current status, instead of running it and landing + // CREATE_FAILED, which would burn the stack name (see #2207). + String stackName = "sam-sfn-changeset-execute-rejected-stack"; + stacksToDelete.add(stackName); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + OrdersStateMachine: + Type: AWS::Serverless::StateMachine + Properties: + Name: sam-orders-execute-rejected-sm + Role: arn:aws:iam::000000000000:role/orders-sfn-role + DefinitionUri: ./src/stepFunctions/orders.asl.json + """; + + String createChangeSetXml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "initial") + .formParam("ChangeSetType", "CREATE") + .formParam("TemplateBody", template) + .formParam("Capabilities.member.1", "CAPABILITY_IAM") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")) + .extract().asString(); + String changeSetId = createChangeSetXml.split("")[1].split("")[0]; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ExecuteChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "initial") + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("InvalidChangeSetStatus")) + .body(containsString("ChangeSet [" + changeSetId + "] cannot be executed in " + + "its current status of [FAILED]")); + + // The AWS CLI's has_stack treats a REVIEW_IN_PROGRESS stack as nonexistent (see + // createChangeSetForRequest's javadoc); the rejected execute must leave the stack there, + // never CREATE_FAILED, so the name stays reusable rather than requiring an explicit + // DeleteStack. + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("REVIEW_IN_PROGRESS")) + .body(not(containsString("CREATE_FAILED"))); + } + + @Test + void samStateMachine_withDefinitionSubstitutions_resolvesPlaceholders() { + String stackName = "sam-sfn-subs-stack"; + stacksToDelete.add(stackName); + + given() + .when() + .put("/sam-asl-subs-bucket") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .body("{\"StartAt\":\"Done\",\"States\":{\"Done\":{\"Type\":\"Pass\",\"Result\":\"${TableName}\",\"End\":true}}}") + .when() + .put("/sam-asl-subs-bucket/orders.asl.json") + .then() + .statusCode(200); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + OrdersStateMachine: + Type: AWS::Serverless::StateMachine + Properties: + Name: sam-orders-subs-sm + Role: arn:aws:iam::000000000000:role/orders-sfn-role + DefinitionUri: s3://sam-asl-subs-bucket/orders.asl.json + DefinitionSubstitutions: + TableName: my-orders-table + Outputs: + MachineArn: + Value: !GetAtt OrdersStateMachine.Arn + """; + + 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("")); + + waitForStackStatus(stackName, "CREATE_COMPLETE"); + + String describeStacks = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + String machineArn = stackOutputValue(describeStacks, "MachineArn"); + + given() + .header("X-Amz-Target", "AWSStepFunctions.DescribeStateMachine") + .contentType("application/x-amz-json-1.0") + .body("{\"stateMachineArn\":\"" + machineArn + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("definition", containsString("my-orders-table")) + .body("definition", not(containsString("${TableName}"))); + } + + private static String stackOutputValue(String describeStacksXml, String outputKey) { + return describeStacksXml + .split("" + outputKey + "")[1] + .split("")[1] + .split("")[0]; + } + private static byte[] buildHandlerZip() { try { var baos = new java.io.ByteArrayOutputStream(); 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.java index 59203d5873..537cc603f2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java @@ -2,6 +2,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 org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -410,6 +411,34 @@ class SamTransformProcessorTest { assertEquals("code.zip", code.path("S3Key").asText()); } + @Test + void expandSamTemplate_functionPreservesMetadata() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersFunction": { + "Type": "AWS::Serverless::Function", + "Metadata": { "SamResourceId": "OrdersFunction" }, + "Properties": { + "Handler": "index.handler", + "Runtime": "nodejs20.x", + "CodeUri": "s3://code-bucket/orders.zip" + } + } + } + } + """); + + JsonNode function = processor.expandSamTemplate(template).path("Resources").path("OrdersFunction"); + + // SAM CLI writes SamResourceId in Metadata for every AWS::Serverless::* resource it + // transforms, not only state machines; copyResourceLevelAttributes is called from every + // arm's switch case (Function, SimpleTable, Api, HttpApi, StateMachine) so each carries it. + assertEquals("OrdersFunction", function.path("Metadata").path("SamResourceId").asText(), + "Metadata must survive the transform on the Function arm too"); + } + @Test void expandSamTemplate_functionWithCodeUriObject() throws Exception { JsonNode template = objectMapper.readTree(""" @@ -528,6 +557,118 @@ class SamTransformProcessorTest { resources.path("MyApiStage").path("Properties").path("StageName").asText()); } + @Test + void expandSamTemplate_apiPreservesDefinitionBodyAsBody() throws Exception { + // A route-bearing Api carries its routes in the inline OpenAPI DefinitionBody, which + // must survive as the RestApi's Body: otherwise the deployed API serves no method. + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyApi": { + "Type": "AWS::Serverless::Api", + "Properties": { + "DefinitionBody": { + "openapi": "3.0.1", + "paths": { + "/hello": { "get": { "x-amazon-apigateway-integration": { "type": "MOCK" } } } + } + } + } + } + } + } + """); + + JsonNode resources = processor.expandSamTemplate(template).path("Resources"); + + JsonNode api = resources.path("MyApi"); + assertEquals("AWS::ApiGateway::RestApi", api.path("Type").asText()); + JsonNode body = api.path("Properties").path("Body"); + assertFalse(body.isMissingNode(), "DefinitionBody must be preserved as the RestApi Body"); + assertEquals("3.0.1", body.path("openapi").asText()); + assertTrue(body.path("paths").has("/hello"), "route definitions must survive the transform"); + } + + @Test + void expandSamTemplate_apiMapsDefinitionUriToBodyS3Location() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyApi": { + "Type": "AWS::Serverless::Api", + "Properties": { "DefinitionUri": "s3://api-specs/openapi.yaml" } + } + } + } + """); + + JsonNode properties = processor.expandSamTemplate(template) + .path("Resources").path("MyApi").path("Properties"); + + assertTrue(properties.path("Body").isMissingNode(), "DefinitionUri must not become an inline Body"); + assertEquals("api-specs", properties.path("BodyS3Location").path("Bucket").asText()); + assertEquals("openapi.yaml", properties.path("BodyS3Location").path("Key").asText()); + } + + @Test + void expandSamTemplate_apiWithBothDefinitionBodyAndDefinitionUriIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyApi": { + "Type": "AWS::Serverless::Api", + "Properties": { + "DefinitionBody": { "openapi": "3.0.1", "paths": {} }, + "DefinitionUri": "s3://api-specs/openapi.yaml" + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // Measured against real AWS, us-east-1, create-change-set: an Api declaring both + // DefinitionBody and DefinitionUri is rejected, DefinitionUri named first, the same + // order as the equivalent HttpApi message. floci must not silently prefer DefinitionBody + // and emit Body with no error. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [MyApi] is invalid. Specify either 'DefinitionUri' " + + "or 'DefinitionBody' property and not both.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_apiWithLocalDefinitionUriIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyApi": { + "Type": "AWS::Serverless::Api", + "Properties": { "DefinitionUri": "./openapi.yaml" } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // Measured against real AWS, us-east-1, create-change-set: a local-path DefinitionUri is + // rejected with the same string-form wording the StateMachine and HttpApi arms already + // carry, not silently accepted with no Body and no BodyS3Location. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [MyApi] is invalid. 'DefinitionUri' is not a valid S3 " + + "Uri of the form 's3://bucket/key' with optional versionId query " + + "parameter.", + exception.getMessage()); + } + @Test void expandSamTemplate_mixedResources() throws Exception { JsonNode template = objectMapper.readTree(""" @@ -1107,8 +1248,33 @@ class SamTransformProcessorTest { assertEquals("api-specs", properties.path("BodyS3Location").path("Bucket").asText()); assertEquals("openapi.yaml", properties.path("BodyS3Location").path("Key").asText()); } + @Test - void expandSamTemplate_httpApiPreservesIntrinsicDefinitionUriForProvisioning() throws Exception { + void expandSamTemplate_httpApiMapsVersionedDefinitionUriToBodyS3LocationWithVersion() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyHttpApi": { + "Type": "AWS::Serverless::HttpApi", + "Properties": { "DefinitionUri": "s3://api-specs/openapi.yaml?versionId=abc123" } + } + } + } + """); + + JsonNode bodyS3Location = processor.expandSamTemplate(template) + .path("Resources").path("MyHttpApi").path("Properties").path("BodyS3Location"); + + // samUriToS3Location is shared with expandServerlessStateMachine (see its javadoc); a + // versioned DefinitionUri must carry Version through on the HttpApi arm the same way. + assertEquals("api-specs", bodyS3Location.path("Bucket").asText()); + assertEquals("openapi.yaml", bodyS3Location.path("Key").asText()); + assertEquals("abc123", bodyS3Location.path("Version").asText()); + } + + @Test + void expandSamTemplate_httpApiWithIntrinsicDefinitionUriIsRejected() throws Exception { JsonNode template = objectMapper.readTree(""" { "Transform": "AWS::Serverless-2016-10-31", @@ -1123,9 +1289,659 @@ class SamTransformProcessorTest { } """); - JsonNode bodyS3Location = processor.expandSamTemplate(template) - .path("Resources").path("MyHttpApi").path("Properties").path("BodyS3Location"); + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); - assertEquals("s3://${SpecBucket}/openapi.yaml", bodyS3Location.path("Fn::Sub").asText()); + // Measured against real AWS, us-east-1, create-change-set: an HttpApi DefinitionUri that + // never resolves to a literal Bucket/Key is rejected with the same object-form wording as + // the equivalent StateMachine case, not preserved unresolved for the ApiGatewayV2 + // provisioner to import as a BodyS3Location it cannot use. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [MyHttpApi] is invalid. 'DefinitionUri' requires " + + "Bucket and Key properties to be specified.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_httpApiWithObjectDefinitionUriMissingKeyIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyHttpApi": { + "Type": "AWS::Serverless::HttpApi", + "Properties": { + "DefinitionUri": { "Bucket": "api-specs" } + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // A Bucket-only DefinitionUri on an HttpApi must not fall through to BodyS3Location: the + // native ApiGatewayV2 provisioner cannot import a location with no Key, so this is + // rejected here instead of surfacing later as a provisioner-side error. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [MyHttpApi] is invalid. 'DefinitionUri' requires " + + "Bucket and Key properties to be specified.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_httpApiWithArrayDefinitionUriIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyHttpApi": { + "Type": "AWS::Serverless::HttpApi", + "Properties": { + "DefinitionUri": ["s3://api-specs/openapi.yaml"] + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // Measured against real AWS, us-east-1, create-change-set: an array DefinitionUri on an + // HttpApi fails with the same third wording as the StateMachine case below, not silently + // with no Body and no BodyS3Location. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [MyHttpApi] is invalid. Type of property " + + "'DefinitionUri' is invalid.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_httpApiWithBothDefinitionBodyAndDefinitionUriIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyHttpApi": { + "Type": "AWS::Serverless::HttpApi", + "Properties": { + "DefinitionBody": { "openapi": "3.0.1", "paths": {} }, + "DefinitionUri": "s3://api-specs/openapi.yaml" + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // Measured against real AWS, us-east-1, create-change-set: an HttpApi declaring both + // DefinitionBody and DefinitionUri is rejected, DefinitionUri named first, the reverse + // order from the equivalent StateMachine message below. floci must not silently prefer + // DefinitionBody and emit Body with no error. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [MyHttpApi] is invalid. Specify either 'DefinitionUri' " + + "or 'DefinitionBody' property and not both.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_httpApiWithLocalDefinitionUriIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyHttpApi": { + "Type": "AWS::Serverless::HttpApi", + "Properties": { + "DefinitionUri": "./openapi.yaml" + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // Measured against real AWS, us-east-1, create-change-set: a local-path DefinitionUri + // (the shape an unpackaged `sam` template carries) is rejected with the same string-form + // wording the StateMachine arm already carries, not silently accepted with no Body and + // no BodyS3Location. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [MyHttpApi] is invalid. 'DefinitionUri' is not a valid S3 " + + "Uri of the form 's3://bucket/key' with optional versionId query " + + "parameter.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_stateMachineBecomesStepFunctionsStateMachine() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Name": "orders-sm", + "Type": "EXPRESS", + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": "s3://asl-definitions/orders.asl.json", + "DefinitionSubstitutions": { "OrdersTable": "orders" }, + "Tracing": { "Enabled": true }, + "Logging": { + "Level": "ALL", + "IncludeExecutionData": true, + "Destinations": [ + { "CloudWatchLogsLogGroup": { "LogGroupArn": "arn:aws:logs:us-east-1:000000000000:log-group:/orders:*" } } + ] + }, + "Tags": { "team": "orders" } + } + } + } + } + """); + + JsonNode resources = processor.expandSamTemplate(template).path("Resources"); + + assertFalse(resources.path("OrdersStateMachine").isMissingNode(), + "SAM StateMachine must survive the transform under the same logical id, not vanish"); + JsonNode machine = resources.path("OrdersStateMachine"); + assertEquals("AWS::StepFunctions::StateMachine", machine.path("Type").asText()); + JsonNode props = machine.path("Properties"); + assertEquals("orders-sm", props.path("StateMachineName").asText()); + assertEquals("EXPRESS", props.path("StateMachineType").asText()); + assertEquals("arn:aws:iam::000000000000:role/orders-sfn-role", props.path("RoleArn").asText()); + assertEquals("asl-definitions", props.path("DefinitionS3Location").path("Bucket").asText()); + assertEquals("orders.asl.json", props.path("DefinitionS3Location").path("Key").asText()); + assertEquals("orders", props.path("DefinitionSubstitutions").path("OrdersTable").asText()); + assertTrue(props.path("TracingConfiguration").path("Enabled").asBoolean()); + assertEquals("ALL", props.path("LoggingConfiguration").path("Level").asText()); + + JsonNode tags = props.path("Tags"); + assertTrue(tags.isArray(), "SAM's Tags map must become the native list-of-{Key,Value} shape"); + assertEquals(2, tags.size()); + assertEquals("stateMachine:createdBy", tags.get(0).path("Key").asText()); + assertEquals("SAM", tags.get(0).path("Value").asText()); + assertEquals("team", tags.get(1).path("Key").asText()); + assertEquals("orders", tags.get(1).path("Value").asText()); + } + + @Test + void expandSamTemplate_stateMachineWithLocalDefinitionUriIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Name": "orders-sm", + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": "./src/stepFunctions/orders.asl.json" + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // Measured against real AWS, us-east-1, create-change-set does not + // reject the API call: it creates the change set and marks it FAILED with this exact + // sentence in StatusReason. The message is asserted as a literal, not a substring, so an + // invented wording can no longer pass this test. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [OrdersStateMachine] is invalid. 'DefinitionUri' is not a " + + "valid S3 Uri of the form 's3://bucket/key' with optional versionId " + + "query parameter.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_stateMachineWithQuestionMarkInKeyIsAccepted() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": "s3://asl-definitions/orders.asl.json?foo=1" + } + } + } + } + """); + + JsonNode location = processor.expandSamTemplate(template) + .path("Resources").path("OrdersStateMachine").path("Properties").path("DefinitionS3Location"); + + // S3 permits a literal '?' in a key; only a trailing '?versionId=' is a query separator, + // so a key carrying an unrelated query string must still match, keeping the '?' in Key. + assertEquals("asl-definitions", location.path("Bucket").asText()); + assertEquals("orders.asl.json?foo=1", location.path("Key").asText(), + "a '?' not followed by 'versionId=' belongs to the key, not a stripped query string"); + assertTrue(location.path("Version").isMissingNode(), "no versionId means no Version field"); + } + + @Test + void expandSamTemplate_stateMachineWithS3UriMissingKeyIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": "s3://asl-definitions" + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // A bucket-only DefinitionUri fails the same 's3://bucket/key' shape check as a local + // path; the two must not be told apart into different messages, and the failure must + // surface here rather than downstream from the provisioner's generic "Specify exactly + // one of Definition, DefinitionString, or DefinitionS3Location", which names neither the + // logical id nor DefinitionUri nor the value. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [OrdersStateMachine] is invalid. 'DefinitionUri' is not a " + + "valid S3 Uri of the form 's3://bucket/key' with optional versionId " + + "query parameter.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_stateMachineWithIntrinsicDefinitionUriIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": { "Fn::Sub": "s3://${SpecBucket}/orders.asl.json" } + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // Measured against real AWS, us-east-1, create-change-set: an intrinsic DefinitionUri + // (no literal Bucket/Key) fails the SAM transform with the object-form wording, distinct + // from the string-form wording the local-path and bucket-only cases above carry. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [OrdersStateMachine] is invalid. 'DefinitionUri' requires " + + "Bucket and Key properties to be specified.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_stateMachineWithObjectDefinitionUriMissingKeyIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": { "Bucket": "asl-definitions" } + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // An object DefinitionUri that names Bucket but not Key must be rejected the same way as + // one that names neither: only a Bucket-and-Key pair resolves to a location the native + // DefinitionS3Location property accepts. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [OrdersStateMachine] is invalid. 'DefinitionUri' requires " + + "Bucket and Key properties to be specified.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_stateMachineWithNullKeyDefinitionUriIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": { "Bucket": "asl-definitions", "Key": null } + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // YAML `Key:` with no value (and JSON's explicit null) parses to a NullNode. Jackson's + // has("Key") returns true for a null-valued field, so the guard must check the resolved + // location actually carries a Key value, not merely that the field is present. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [OrdersStateMachine] is invalid. 'DefinitionUri' requires " + + "Bucket and Key properties to be specified.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_stateMachineWithArrayDefinitionUriIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": ["s3://asl-definitions/orders.asl.json"] + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // Measured against real AWS, us-east-1, create-change-set: a DefinitionUri of any JSON + // type other than string or object (array, number, boolean) fails with this third + // wording, distinct from both the string-form and object-form messages above. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [OrdersStateMachine] is invalid. Type of property " + + "'DefinitionUri' is invalid.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_stateMachineWithVersionedDefinitionUriSplitsVersion() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": "s3://asl-definitions/orders.asl.json?versionId=abc123" + } + } + } + } + """); + + JsonNode location = processor.expandSamTemplate(template) + .path("Resources").path("OrdersStateMachine").path("Properties").path("DefinitionS3Location"); + + // Measured against real AWS, us-east-1: a versioned DefinitionUri splits into a + // third field rather than folding the query string into Key: + // {"Bucket": "...", "Key": "...", "Version": "abc123"}. + assertEquals("asl-definitions", location.path("Bucket").asText()); + assertEquals("orders.asl.json", location.path("Key").asText(), + "the '?versionId=...' query string must not be folded into Key"); + assertEquals("abc123", location.path("Version").asText()); + } + + @Test + void expandSamTemplate_stateMachinePreservesMetadataAndDependsOn() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersRole": { + "Type": "AWS::IAM::Role", + "Properties": {} + }, + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Metadata": { "SamResourceId": "OrdersStateMachine" }, + "DependsOn": "OrdersRole", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": "s3://asl-definitions/orders.asl.json" + } + } + } + } + """); + + JsonNode machine = processor.expandSamTemplate(template).path("Resources").path("OrdersStateMachine"); + + // Measured against real AWS, us-east-1: Metadata carries through on 67 of 67 deployed + // state machines. CloudFormation, not SAM, writes it into the Processed template, so any + // sibling of Type/Properties on the SAM resource node must survive the same way. This + // measurement covers Metadata only; DependsOn survival is asserted below as the same + // generic sibling-copy behaviour, not as a separately measured claim. + assertEquals("OrdersStateMachine", machine.path("Metadata").path("SamResourceId").asText(), + "Metadata must survive the transform with its literal value"); + assertEquals("OrdersRole", machine.path("DependsOn").asText(), + "a declared DependsOn must survive the transform"); + } + + @Test + void expandSamTemplate_stateMachinePreservesIntrinsicNameAndRole() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersRole": { + "Type": "AWS::IAM::Role", + "Properties": {} + }, + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Name": { "Fn::Sub": "${Environment}-orders-sm" }, + "Role": { "Fn::GetAtt": ["OrdersRole", "Arn"] }, + "DefinitionUri": "s3://asl-definitions/orders.asl.json" + } + } + } + } + """); + + JsonNode props = processor.expandSamTemplate(template) + .path("Resources").path("OrdersStateMachine").path("Properties"); + + // copyRenamed must deep-copy the node, never read it with asText(): asText() on an object + // node silently returns "", which would collapse RoleArn/StateMachineName to an empty + // string instead of failing loudly. + assertTrue(props.path("StateMachineName").isObject(), + "an intrinsic Name must survive as an object, not be stringified"); + assertEquals("${Environment}-orders-sm", props.path("StateMachineName").path("Fn::Sub").asText()); + assertTrue(props.path("RoleArn").isObject(), + "an intrinsic Role must survive as an object, not be stringified"); + JsonNode getAtt = props.path("RoleArn").path("Fn::GetAtt"); + assertEquals("OrdersRole", getAtt.get(0).asText()); + assertEquals("Arn", getAtt.get(1).asText()); + } + + @Test + void expandSamTemplate_stateMachineWithEmptyTagMapEmitsOnlyTheSamTag() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": "s3://asl-definitions/orders.asl.json", + "Tags": {} + } + } + } + } + """); + + JsonNode tags = processor.expandSamTemplate(template) + .path("Resources").path("OrdersStateMachine").path("Properties").path("Tags"); + + assertTrue(tags.isArray()); + assertEquals(1, tags.size(), "an empty Tags map must not emit zero entries; SAM still adds its own"); + assertEquals("stateMachine:createdBy", tags.get(0).path("Key").asText()); + assertEquals("SAM", tags.get(0).path("Value").asText()); + } + + @Test + void expandSamTemplate_stateMachineTagValueKeepsItsJsonType() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "DefinitionUri": "s3://asl-definitions/orders.asl.json", + "Tags": { + "project-id": 12345678, + "environment": { "Ref": "Environment" } + } + } + } + } + } + """); + + JsonNode tags = processor.expandSamTemplate(template) + .path("Resources").path("OrdersStateMachine").path("Properties").path("Tags"); + + JsonNode projectIdTag = null; + JsonNode environmentTag = null; + for (JsonNode tag : tags) { + if ("project-id".equals(tag.path("Key").asText())) { + projectIdTag = tag; + } + if ("environment".equals(tag.path("Key").asText())) { + environmentTag = tag; + } + } + + assertTrue(projectIdTag.path("Value").isNumber(), + "a numeric tag value must survive as a JSON number, not be stringified"); + assertEquals(12345678, projectIdTag.path("Value").asInt()); + assertTrue(environmentTag.path("Value").isObject(), + "an intrinsic tag value must survive as an object, not be stringified"); + assertEquals("Environment", environmentTag.path("Value").path("Ref").asText()); + } + + @Test + void expandSamTemplate_stateMachineWithInlineDefinition() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "Definition": { + "StartAt": "Done", + "States": { "Done": { "Type": "Pass", "End": true } } + } + } + } + } + } + """); + + JsonNode machine = processor.expandSamTemplate(template).path("Resources").path("OrdersStateMachine"); + JsonNode props = machine.path("Properties"); + + assertEquals("AWS::StepFunctions::StateMachine", machine.path("Type").asText(), + "a Definition-only machine must still be expanded to the native type"); + assertTrue(props.path("DefinitionS3Location").isMissingNode(), + "no DefinitionUri was given, so no DefinitionS3Location must appear"); + assertEquals("Done", props.path("Definition").path("StartAt").asText()); + assertEquals("Pass", props.path("Definition").path("States").path("Done").path("Type").asText()); + } + + @Test + void expandSamTemplate_stateMachineWithNeitherDefinitionNorDefinitionUriIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role" + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // Measured against real AWS, us-east-1, create-change-set: a StateMachine with neither + // Definition nor DefinitionUri is rejected before a single resource is provisioned, + // rather than emitting an AWS::StepFunctions::StateMachine with no definition at all. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [OrdersStateMachine] is invalid. Either 'Definition' or " + + "'DefinitionUri' property must be specified.", + exception.getMessage()); + } + + @Test + void expandSamTemplate_stateMachineWithBothDefinitionAndDefinitionUriIsRejected() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "OrdersStateMachine": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Role": "arn:aws:iam::000000000000:role/orders-sfn-role", + "Definition": { + "StartAt": "Done", + "States": { "Done": { "Type": "Pass", "End": true } } + }, + "DefinitionUri": "s3://asl-definitions/orders.asl.json" + } + } + } + } + """); + + AwsException exception = assertThrows(AwsException.class, + () -> processor.expandSamTemplate(template)); + + // Measured against real AWS, us-east-1, create-change-set: a StateMachine declaring both + // Definition and a resolvable DefinitionUri is rejected, not expanded into one native + // resource carrying both Definition and DefinitionS3Location. + assertEquals("ValidationError", exception.getErrorCode()); + assertEquals("Resource with id [OrdersStateMachine] is invalid. Specify either " + + "'Definition' or 'DefinitionUri' property and not both.", + exception.getMessage()); } }