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

@@ -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());
}
@@ -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 <logicalId>-<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 <logicalId>-<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<String, Object> 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<String, String> replacePatchOp(String path, String value) {
Map<String, String> 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;
@@ -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<ResourceChange> 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.
*
* <p>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.
*
* <p>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);
@@ -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=<id>} 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://(?<bucket>[^/?]+)/(?<key>.+?)(?:\\?versionId=(?<version>.+))?$");
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.
*
* <p>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.
*
* <p>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<Map.Entry<String, JsonNode>> fields = source.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> 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.
*
* <p>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<Map.Entry<String, JsonNode>> fields = tagsMap.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> 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.<field>} to {@code target.<targetField>} 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=<id>}, 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.
*
* <p>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.<propertyName>}, 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.
*
* <p>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.<field>} to {@code target.<field>} when present and non-null. */
private void copyIfPresent(JsonNode source, String field, ObjectNode target) {
copyRenamed(source, field, target, field);
}
private String mapSamAttributeType(String samType) {
@@ -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());
}
}