fix(cloudformation): expand AWS::Serverless::StateMachine, and reject every unresolvable DefinitionUri on both StateMachine and HttpApi (#2885)

* test(cloudformation): pin AWS::Serverless::StateMachine expansion against the deployed template

The expected values come from a deployed stack's processed template, read with
get-template --template-stage Processed, and from change-set probes against real
AWS. Every assertion states its expected value as a literal.

* fix(cloudformation): expand AWS::Serverless::StateMachine into the native resource

The SAM transform switched on four resource types. A state machine fell through
the default arm, kept its AWS::Serverless:: type, and was stubbed by the
provisioner with a physical id of <logicalId>-<8 hex> and an attribute Arn of
arn:aws:stub:::<logicalId>. The stack reported CREATE_COMPLETE, ListStateMachines
was empty, and Fn::GetAtt on the resource handed downstream resources an ARN that
named no state machine.

Measured against a deployed stack, both template stages: 67 AWS::Serverless::StateMachine
in the original template, 67 AWS::StepFunctions::StateMachine in the processed one,
0 AWS::Serverless:: survivors. Eight properties are mapped on 67 of 67: Name to
StateMachineName, Type to StateMachineType, Role to RoleArn, DefinitionUri to
DefinitionS3Location, Logging to LoggingConfiguration, Tracing to
TracingConfiguration, DefinitionSubstitutions unchanged, and the Tags map to a list
of {Key, Value} with stateMachine:createdBy first. Every mapped value stays an
unevaluated intrinsic and tag values keep their JSON type. Metadata is carried
through, not synthesized: it is already present in the original template on 67 of 67.

Three further behaviours come from change-set probes against real AWS. A local
DefinitionUri does not raise an HTTP error: the change set is created with
Status FAILED, ExecutionStatus UNAVAILABLE, zero changes, and the transform's own
sentence in StatusReason. ExecuteChangeSet on that change set is refused with
InvalidChangeSetStatus. A DefinitionUri carrying ?versionId= is accepted and split
into a third field, Version.

* test(cloudformation): pin rejection of an intrinsic DefinitionUri on AWS::Serverless::StateMachine

An intrinsic DefinitionUri (Fn::Sub, Ref, ...) with no literal Bucket/Key
carries neither key, so samUriToS3Location passes it through unchanged and
the SAM transform accepts it silently. CloudFormation later collapses the
intrinsic into a TextNode and CloudFormationResourceProvisioner throws
"DefinitionS3Location requires Bucket and Key" at provisioning, one step
later than real AWS's own change-set-time failure.

* fix(cloudformation): reject an intrinsic DefinitionUri on AWS::Serverless::StateMachine

samUriToS3Location passes an object DefinitionUri through unchanged when it
carries neither Bucket nor Key, so an intrinsic value (Fn::Sub, Ref, ...)
reached DefinitionS3Location unresolved. CloudFormation then collapsed it
into a TextNode, and CloudFormationResourceProvisioner only caught the
missing Bucket/Key once provisioning started, one step later than real
AWS's own change-set-time failure.

expandServerlessStateMachine now accepts DefinitionS3Location only when it
resolves to a literal Bucket and Key, and rejects both the textual and the
object shape with the SAM transform's own wording, matching the FAILED
change set AWS reports for either.

Also drops the SamTransformProcessorTest case that pinned the old
pass-through behaviour for an intrinsic DefinitionUri (it asserted the
exact defect this fixes: the value surviving unsplit into
DefinitionS3Location) and adds a companion case for an object DefinitionUri
that names Bucket but not Key, closing the boundary the new guard leaves
otherwise untested.

* test(cloudformation): pin DefinitionUri rejection for a null Key, a non-string/object shape, and HttpApi

expandSamTemplate_stateMachineWithNullKeyDefinitionUriIsRejected and
expandSamTemplate_stateMachineWithArrayDefinitionUriIsRejected pin real AWS's rejection of a
DefinitionUri whose Key is an explicit null and of a DefinitionUri that is neither a string nor
an object (array, number, boolean); today's guard silently accepts both.

expandSamTemplate_httpApiWithIntrinsicDefinitionUriIsRejected replaces
expandSamTemplate_httpApiPreservesIntrinsicDefinitionUriForProvisioning:
both assert an HttpApi DefinitionUri with no literal Bucket/Key, but the one it replaces asserted
the value was preserved unresolved for the provisioner, a behaviour measured against real AWS
(us-east-1, create-change-set) to be wrong. AWS rejects it with the object-form wording, the same
one the StateMachine arm already carries.

samHttpApi_intrinsicDefinitionUriIsRejected replaces
samHttpApi_intrinsicDefinitionUriCreatesApiGatewayV2Routes: the test it replaces asserted the
opposite outcome, that routes were successfully created from a real spec uploaded to S3 and
imported through the intrinsic DefinitionUri, which real AWS does not accept for this shape.

expandSamTemplate_httpApiWithObjectDefinitionUriMissingKeyIsRejected and
expandSamTemplate_httpApiWithArrayDefinitionUriIsRejected pin the same two shapes on the HttpApi
arm; the array case is measured directly against real AWS via create-change-set.

* fix(cloudformation): reject every unresolvable SAM DefinitionUri, on both StateMachine and HttpApi

samUriToS3Location's object branch checked has("Bucket") && has("Key") on its own passthrough
copy of DefinitionUri, so a Key present as an explicit null (YAML's Key: with no value) counted
as resolved; and a DefinitionUri that was neither textual nor an object (array, number, boolean)
matched neither disjunct of the guard, so nothing was thrown and no definition was set at all.

Both callers now go through one guard, applyDefinitionUri: samUriToS3Location returns null
whenever it cannot produce a literal, non-null Bucket and Key, and applyDefinitionUri throws for
every non-null return with the wording definitionUriRejectionReason selects from the shape of
DefinitionUri, matching real AWS (measured against us-east-1 via create-change-set) for all three
JSON shapes. The predicate for "an S3 location is a Bucket and a Key" lives once, in
samUriToS3Location.

This also closes the split between the two callers: the HttpApi arm used to preserve an
unresolved DefinitionUri (an intrinsic, or an object missing Key) as BodyS3Location for the
provisioner to fail on later, or silently emit no definition at all for a non-object,
non-string DefinitionUri. It now rejects every one of those shapes at transform time, the same
as the StateMachine arm, matching AWS's own transform-time rejection (measured directly for the
array/number/boolean shape via create-change-set, not previously measured on this branch).

* test(cloudformation): pin the missing Definition/DefinitionUri mutual-exclusion cases

expandSamTemplate_stateMachineWithNeitherDefinitionNorDefinitionUriIsRejected and
expandSamTemplate_stateMachineWithBothDefinitionAndDefinitionUriIsRejected pin real AWS's
rejection (measured via create-change-set) of a StateMachine declaring neither Definition nor
DefinitionUri, and of one declaring both; today's expandServerlessStateMachine handles neither
case, emitting a definition-less resource for the first and a resource carrying both Definition
and DefinitionS3Location for the second.

expandSamTemplate_httpApiWithBothDefinitionBodyAndDefinitionUriIsRejected pins the equivalent
HttpApi rejection, with AWS's own reversed property order in the message; the else at
expandServerlessHttpApi's DefinitionBody check hides this shape today, always preferring
DefinitionBody with no error.

expandSamTemplate_httpApiWithLocalDefinitionUriIsRejected and
samHttpApi_definitionUriCreatesApiGatewayV2Routes are coverage additions, not new pins: both
pass unmodified against the previous commit's production code. The first mirrors the existing
expandSamTemplate_stateMachineWithLocalDefinitionUriIsRejected on the HttpApi arm, the most
common real shape (an unpackaged sam template) and previously untested there. The second
restores the only end-to-end proof that a literal s3://bucket/key DefinitionUri creates routes,
lost when an earlier commit on this branch replaced
samHttpApi_intrinsicDefinitionUriCreatesApiGatewayV2Routes with
samHttpApi_intrinsicDefinitionUriIsRejected.

* fix(cloudformation): enforce Definition/DefinitionUri mutual exclusion on SAM StateMachine and HttpApi

expandServerlessStateMachine copied Definition and resolved DefinitionUri independently, so a
StateMachine declaring both ended up with one native resource carrying both Definition and
DefinitionS3Location, and one declaring neither expanded to a resource with no definition at
all. Real AWS (measured via create-change-set, us-east-1) rejects both shapes before a single
resource is provisioned. expandServerlessHttpApi's DefinitionBody check silently preferred
DefinitionBody over DefinitionUri with no error when a resource declared both; AWS rejects that
too, naming DefinitionUri first, the reverse of the StateMachine wording.

Both arms now check presence of their two definition-source properties up front and share a
rejectBothDefinitionSources helper for the "not both" wording; the StateMachine arm additionally
rejects "neither". A neither-property HttpApi is left alone: measured against real AWS via
create-change-set, that shape is accepted and expands to an empty ApiGatewayV2 API, unlike the
StateMachine arm.

Renames applyDefinitionUri to resolveDefinitionUriOrThrow, naming the effect its old name left
unstated (it either sets the target property or throws), and inlines its lone-caller helper
definitionUriRejectionReason: the merged function stays a handful of decision points, well under
the cognitive-complexity budget, and reads as one "resolve or throw" unit instead of two.

Both callers now guard DefinitionUri's presence before calling resolveDefinitionUriOrThrow, so
its own absent/null guard, and the duplicate of the same guard at the top of samUriToS3Location,
were both unreachable; deletes both and rewrites the javadoc that claimed a caller-side check
already existed for the state machine arm, which it did not.

SamTransformProcessorTest fixture updates: four pre-existing StateMachine tests exercising
Metadata/DependsOn/Tags/intrinsic-property preservation declared neither Definition nor
DefinitionUri, a shape the new guard now rejects; each gains a minimal literal DefinitionUri so
its own assertions keep exercising what they always asserted.

* refactor(cloudformation): collapse rejectBothDefinitionSources booleans and duplicated presence checks

rejectBothDefinitionSources took two independent booleans read only as their
conjunction; because && is commutative, swapping them at a call site went
undetectable, while swapping the two property name strings would silently
reverse AWS's own wording. Both callers now pass the conjunction they already
compute, so the signature no longer promises a per-argument correspondence the
body never used.

copyRenamed and isPropertyPresent asserted the identical "not missing, not
null" presence check in two places; copyRenamed now delegates to
isPropertyPresent so the predicate lives once. expandServerlessStateMachine's
Definition copy re-tested a presence its own hasDefinition guard already
established; it now copies the already-known-present node directly.

Reworded the HttpApi DefinitionBody/DefinitionUri comment: "Neither X nor Y is
accepted too" read as its own opposite of the fall-through it documents, where
an HttpApi declaring neither property is accepted and still expands to a bare
AWS::ApiGatewayV2::Api and its default Stage.

Realigned two continuation lines that sat one column past their opening paren
to the file's own prevailing continuation style.

Behaviour-neutral: no assertion or error message changes.

* test(cloudformation): pin AWS::Serverless::Api DefinitionBody/DefinitionUri expansion

Pins the RestApi Body/BodyS3Location expansion an AWS::Serverless::Api's
DefinitionBody or DefinitionUri must produce, the rejection of a
local-path DefinitionUri, and that the declared Name survives a
DefinitionBody carrying a different info.title, all currently unmet.

* fix(cloudformation): materialize AWS::Serverless::Api DefinitionBody/DefinitionUri

expandServerlessApi carried only Name and Description onto the emitted
AWS::ApiGateway::RestApi, silently dropping a declared OpenAPI document
so the stack reached CREATE_COMPLETE with an API serving no method.

The transform now maps DefinitionBody to Body and DefinitionUri to
BodyS3Location, rejecting both together or a local-path DefinitionUri,
mirroring the AWS::Serverless::HttpApi arm. The REST API provisioner
resolves that document (renaming the ApiGatewayV2-only resolver into
resolveRestApiOpenApiDocument, now shared by both API Gateway
versions) and runs it through the existing putRestApi/applyOpenApiSpec
OpenAPI materializer, then re-applies the resolved Name since
putRestApi overwrites it from the document's info, which real AWS
does not do.

* test(cloudformation): pin AWS::Serverless::Api both-Definition rejection wording

Measured against real AWS, us-east-1, create-change-set: an Api
declaring both DefinitionBody and DefinitionUri is rejected with
DefinitionUri named first. Nothing pinned this sentence's property
order, so it could be transposed silently; rejectBothDefinitionSources
already enforces it, this only adds the missing regression test.

* refactor(cloudformation): rename ApiGatewayV2BodyS3Location to OpenApiBodyS3Location

parseOpenApiBodyS3Location now feeds both the ApiGatewayV2 and the
native/SAM ApiGateway RestApi provisioning paths; its return type kept
the V2-only name after the parser itself was renamed, leaving one
representation of an S3 body location claiming to be v2-only. No
behaviour changes, five sites in one file, all within this record's
own declaration and its own callers.

* test(cloudformation): pin AWS::ApiGateway::RestApi Body materialization outside SAM

A native RestApi's Body was ignored before the provisioner started
resolving it for AWS::Serverless::Api's DefinitionBody, since both
paths share provisionApiGatewayRestApi. Nothing covered the
hand-written-template shape; this pins that a declared Body's OpenAPI
document creates its resources and methods, not only a SAM-expanded
one.

* test(cloudformation): pin SAM Api Description reapply and DefinitionBody materialization together

samApi_declaredNameSurvivesDefinitionBodyTitle only proved the Name-reapply
line against a partial revert, so it passed even with the entire fix
reverted: a provisioner that never reads DefinitionBody at all trivially
never overwrites Name either. Renamed and rewritten so it also asserts the
declared Description survives putRestApi (which overwrites Description from
DefinitionBody's info exactly the way it overwrites Name) and that the
/hello method from DefinitionBody actually materializes, so a provisioner
that skips DefinitionBody cannot pass. Red against both production files
reverted to cbdebe10: item.path doesn't match, expected a collection
containing "/hello", actual [/].

* refactor(cloudformation): rename resolveRestApiOpenApiDocument to resolveOpenApiDocument

The method is also the OpenAPI-document resolver for AWS::ApiGatewayV2::Api
(reconcileApiGatewayV2BodyRoutes), never called for a RestApi in that path:
"RestApi" in the name reintroduces the exact naming defect commit 7da9a7c4
existed to fix. No caller or behavior changes.

* fix(cloudformation): reapply Description after putRestApi overwrites it from DefinitionBody

putRestApi overwrites both Name and Description from the DefinitionBody's
info, but only Name was re-applied afterward: an undeclared Name falls back
to the generated physical name (a text field, never null), while an
undeclared Description resolves to null, and Map.of rejects a null value,
so the previous single-entry patch could not carry a Description operation
at all. Reapplies both through a HashMap-backed replace op that allows null,
clearing an undeclared Description rather than leaving whatever putRestApi
last wrote. Narrows the comment above the reapply to what the create-
change-set probe actually measured (the processed template keeps Name and
Description separate from Body.info) rather than a runtime-preference claim
the probe never tested, since create-change-set never executes the change.

Isolated red (only the Description reapply removed, Name reapply and
materialization intact): item.find { it.name == '<apiName>' }.description
doesn't match, expected the declared description, actual
"description-from-document".

* style(cloudformation): drop em-dash from committed test comment

AGENTS.md:314 forbids an em-dash or en-dash on any added line, and CI does
not catch it. Comment text only, no assertion changes.

* refactor(cloudformation): extract shared DefinitionBody/DefinitionUri handling, fix stale docs

Extracts the identical DefinitionBody/DefinitionUri resolution (reject-both
check plus the Body/BodyS3Location assignment) duplicated between
expandServerlessApi and expandServerlessHttpApi into applyDefinitionSource,
called from both arms. Updates the four javadoc caller lists that named
expandServerlessHttpApi as the sole AWS::Serverless::Api-adjacent caller of
rejectBothDefinitionSources, samUriToS3Location and
resolveDefinitionUriOrThrow, now inaccurate with applyDefinitionSource as
the actual (shared) caller. Corrects the expandServerlessApi comment on an
Api declaring neither DefinitionBody nor DefinitionUri: AWS does synthesize
a default Body in that case, floci does not, and the comment now says so
while noting the runtime outcome (no method reachable) is the same either
way, rather than claiming AWS leaves Body unset.

No behavior change: both arms' existing tests pass unedited.

* docs(cloudformation): drop the corpus size from the state machine javadoc

The unhandled-properties note carried a count a reader cannot verify. State
what was measured instead.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
This commit is contained in:
Facundo ParedesandFacundo Paredes authored and GitHub committed 2026-09-01 23:00:23 -05:00
1 parent 7095641e25
commit f2b4c08481
8 files changed
+2086 -60

No files matched your search

@@ -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("<StackStatus>CREATE_COMPLETE</StackStatus>"));
String resourcesXml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
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
@@ -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
// (<logicalId>-<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("<PhysicalResourceId>" + 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("<StackStatus>UPDATE_COMPLETE</StackStatus>"));
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("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.body(containsString("<StackStatusReason>"))
.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")
@@ -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("<StackId>"));
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("<StackId>"));
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("<StackId>"));
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("<StackStatus>CREATE_COMPLETE</StackStatus>")))
// XmlBuilder.elem escapes the single quotes AWS's own wording uses around
// 'DefinitionUri' to &apos;.
.body(containsString("Resource with id [HttpApi] is invalid. "
+ "&apos;DefinitionUri&apos; 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("<StackId>"));
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("<StackId>"));
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("<StackStatus>CREATE_COMPLETE</StackStatus>")))
// XmlBuilder.elem escapes the single quotes AWS's own wording uses around
// 'DefinitionUri' and 's3://bucket/key' to &apos;.
.body(containsString("Resource with id [OrdersStateMachine] is invalid. "
+ "&apos;DefinitionUri&apos; is not a valid S3 Uri of the form "
+ "&apos;s3://bucket/key&apos; 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("<member>")))
.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("<Id>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "initial")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<Status>FAILED</Status>"))
.body(containsString("<ExecutionStatus>UNAVAILABLE</ExecutionStatus>"))
.body(containsString("<StatusReason>Transform AWS::Serverless-2016-10-31 failed "
+ "with: Invalid Serverless Application Specification document. Number of "
+ "errors found: 1. Resource with id [OrdersStateMachine] is invalid. "
+ "&apos;DefinitionUri&apos; is not a valid S3 Uri of the form "
+ "&apos;s3://bucket/key&apos; with optional versionId query "
+ "parameter.</StatusReason>"))
.body(not(containsString("<member>")));
}
@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("<Id>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "initial")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<Status>FAILED</Status>"))
.body(containsString("<ExecutionStatus>UNAVAILABLE</ExecutionStatus>"))
.body(containsString("<StatusReason>Transform AWS::Serverless-2016-10-31 failed "
+ "with: Invalid Serverless Application Specification document. Number of "
+ "errors found: 1. Resource with id [OrdersStateMachine] is invalid. "
+ "&apos;DefinitionUri&apos; requires Bucket and Key properties to be "
+ "specified.</StatusReason>"))
.body(not(containsString("<member>")));
}
@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("<Id>"))
.extract().asString();
String changeSetId = createChangeSetXml.split("<Id>")[1].split("</Id>")[0];
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ExecuteChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "initial")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("<Code>InvalidChangeSetStatus</Code>"))
.body(containsString("<Message>ChangeSet [" + changeSetId + "] cannot be executed in "
+ "its current status of [FAILED]</Message>"));
// 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("<StackStatus>REVIEW_IN_PROGRESS</StackStatus>"))
.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("<StackId>"));
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>" + outputKey + "</OutputKey>")[1]
.split("<OutputValue>")[1]
.split("</OutputValue>")[0];
}
private static byte[] buildHandlerZip() {
try {
var baos = new java.io.ByteArrayOutputStream();
@@ -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());
}
}