feat(cloudformation): implement GetTemplateSummary (#2148)

* feat(cloudformation): implement GetTemplateSummary (#1964)

Adds the missing action to the CloudFormation Query allowlist and
computes Parameters, ResourceTypes, Version, DeclaredTransforms and an
informational Capabilities/CapabilitiesReason (derived from AWS::IAM::
resource types) from a stack's existing template, an inline
TemplateBody, or a TemplateURL. Without this, tools like sam deploy
that call GetTemplateSummary before UpdateStack failed with
UnsupportedOperation.

* fix(cloudformation): correct GetTemplateSummary for SAM stacks and named IAM resources

Addresses two review findings:

- StackName lookups summarized the persisted post-transform template,
  so an existing SAM stack lost its Transform declaration and reported
  expanded resource types (AWS::Lambda::Function) instead of the
  original submitted ones (AWS::Serverless::Function). Stack now keeps
  the pre-transform template body alongside the existing post-transform
  one, and GetTemplateSummary prefers it.
- Capabilities always reported CAPABILITY_IAM for any IAM resource,
  even ones with an explicit name (e.g. RoleName). CloudFormation
  requires CAPABILITY_NAMED_IAM for those; GetTemplateSummary now
  checks the relevant name property per IAM resource type.

* fix(cloudformation): detect named IAM resources set via intrinsic functions

The CAPABILITY_NAMED_IAM check only looked for a literal string value
on the name property, so a real-world RoleName/UserName/etc. set via
Ref, Fn::Sub, Fn::Join or another intrinsic (the common shape in SAM
and CDK output) was missed entirely, misclassifying the template as
only needing CAPABILITY_IAM. CloudFormation requires NAMED_IAM whenever
the property is present at all, regardless of how its value resolves,
so the check now looks for presence instead of a textual value.

* docs(cloudformation): clarify GetTemplateSummary's originalTemplateBody fallback

Spells out why the fallback to the post-transform templateBody exists
(originalTemplateBody has no data for stacks persisted before this
field was added) and that it self-heals on the stack's next
CreateChangeSet/UpdateStack call, in response to review feedback.
This commit is contained in:
Olamide Kosile authored and GitHub committed 2026-08-13 00:29:11 -05:00
1 parent 4ba854ab8c
commit a235b76835
7 files changed
+528 -1

No files matched your search

+1
View File
@@ -22,6 +22,7 @@
| `DescribeStackResources` | Get all resources in a stack |
| `ListStackResources` | List resource summaries |
| `GetTemplate` | Retrieve the template body |
| `GetTemplateSummary` | Summarize a template's Parameters, Resources and Transform sections, by StackName, TemplateBody or TemplateURL |
| `ValidateTemplate` | Accepted; returns success without validating (stub) |
| `ListStacks` | List stacks by status |
| `ListExports` | - |
@@ -373,7 +373,7 @@ public class AwsQueryController {
private static final Set<String> CLOUDFORMATION_ACTIONS = Set.of(
"CreateStack", "DeleteStack", "UpdateStack", "DescribeStacks", "UpdateTerminationProtection",
"ListStacks", "ListExports", "GetTemplate", "ValidateTemplate",
"ListStacks", "ListExports", "GetTemplate", "GetTemplateSummary", "ValidateTemplate",
"CreateChangeSet", "DeleteChangeSet", "DescribeChangeSet", "ExecuteChangeSet", "ListChangeSets",
"DescribeStackEvents", "DescribeStackResources", "ListStackResources", "DescribeStackResource",
"SetStackPolicy", "GetStackPolicy",
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackInstance;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.model.StackSet;
import io.github.hectorvent.floci.services.cloudformation.model.StackSetOperation;
import io.github.hectorvent.floci.services.cloudformation.model.TemplateSummary;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -59,6 +60,7 @@ public class CloudFormationQueryHandler {
case "DescribeStackResources" -> describeStackResources(params, region);
case "ListStackResources" -> listStackResources(params, region);
case "GetTemplate" -> getTemplate(params, region);
case "GetTemplateSummary" -> getTemplateSummary(params, region);
case "ValidateTemplate" -> validateTemplate(params);
case "ListStacks" -> listStacks(params, region);
case "ListExports" -> listExports(params, region);
@@ -438,6 +440,65 @@ public class CloudFormationQueryHandler {
}
}
// ── GetTemplateSummary ────────────────────────────────────────────────────
private Response getTemplateSummary(MultivaluedMap<String, String> params, String region) {
String stackName = params.getFirst("StackName");
String templateBody = params.getFirst("TemplateBody");
String templateUrl = params.getFirst("TemplateURL");
try {
TemplateSummary summary = cfnService.getTemplateSummary(stackName, templateBody, templateUrl, region);
var xml = new XmlBuilder()
.start("GetTemplateSummaryResponse", CF_NS)
.start("GetTemplateSummaryResult");
xml.start("ResourceTypes");
for (String type : summary.resourceTypes()) {
xml.elem("member", type);
}
xml.end("ResourceTypes");
xml.elem("Version", summary.version());
xml.elem("Description", summary.description());
xml.start("Parameters");
for (TemplateSummary.ParameterDeclaration p : summary.parameters()) {
xml.start("member")
.elem("ParameterKey", p.parameterKey())
.elem("DefaultValue", p.defaultValue())
.elem("NoEcho", p.noEcho())
.elem("Description", p.description())
.elem("ParameterType", p.parameterType())
.end("member");
}
xml.end("Parameters");
xml.start("Capabilities");
for (String capability : summary.capabilities()) {
xml.elem("member", capability);
}
xml.end("Capabilities");
xml.elem("CapabilitiesReason", summary.capabilitiesReason());
xml.start("DeclaredTransforms");
for (String transform : summary.declaredTransforms()) {
xml.elem("member", transform);
}
xml.end("DeclaredTransforms");
xml.start("ResourceIdentifierSummaries").end("ResourceIdentifierSummaries");
xml.elem("Metadata", summary.metadata());
xml.end("GetTemplateSummaryResult")
.raw(AwsQueryResponse.responseMetadata())
.end("GetTemplateSummaryResponse");
return Response.ok(xml.build()).type("text/xml").build();
} catch (AwsException e) {
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
}
// ── ValidateTemplate ──────────────────────────────────────────────────────
private Response validateTemplate(MultivaluedMap<String, String> params) {
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.model.TemplateSummary;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.s3.S3Service;
import com.fasterxml.jackson.core.type.TypeReference;
@@ -317,6 +318,124 @@ public class CloudFormationService {
return stack.getTemplateBody() != null ? stack.getTemplateBody() : "{}";
}
// ── GetTemplateSummary ────────────────────────────────────────────────────
// IAM resource types whose corresponding property, when a literal string, requires
// CAPABILITY_NAMED_IAM instead of the weaker CAPABILITY_IAM.
private static final Map<String, String> IAM_RESOURCE_NAME_PROPERTY = Map.of(
"AWS::IAM::Role", "RoleName",
"AWS::IAM::User", "UserName",
"AWS::IAM::Group", "GroupName",
"AWS::IAM::ManagedPolicy", "ManagedPolicyName",
"AWS::IAM::InstanceProfile", "InstanceProfileName");
/**
* Summarizes a template's Parameters, Resources, Transform and Metadata sections. Accepts the
* same three input modes as the real API: an existing stack by name, an inline TemplateBody, or
* a TemplateURL. Floci does not enforce IAM capabilities on CreateStack/UpdateStack, so the
* Capabilities/CapabilitiesReason fields here are informational only, derived by scanning for
* AWS::IAM:: resource types.
*/
public TemplateSummary getTemplateSummary(String stackName, String templateBody, String templateUrl,
String region) {
String resolvedBody;
if (stackName != null && !stackName.isBlank()) {
Stack stack = getStackOrThrow(stackName, region);
// Summarize the template as submitted, not the SAM-expanded version stack.getTemplateBody()
// holds post-transform. originalTemplateBody is only absent for stacks persisted by a
// floci version predating this field; there is no way to recover the pre-transform body
// for those, so this falls back to the (already-transformed) templateBody until the
// stack's next CreateChangeSet/UpdateStack call backfills the field.
resolvedBody = stack.getOriginalTemplateBody() != null
? stack.getOriginalTemplateBody()
: stack.getTemplateBody() != null ? stack.getTemplateBody() : "{}";
} else {
resolvedBody = resolveTemplateBody(templateBody, templateUrl);
if (resolvedBody == null) {
throw new AwsException("ValidationError",
"One of StackName, TemplateBody or TemplateURL must be specified.", 400);
}
}
JsonNode template;
try {
template = parseTemplate(resolvedBody);
} catch (Exception e) {
throw new AwsException("ValidationError", "Template format error: " + e.getMessage(), 400);
}
return buildTemplateSummary(template);
}
private TemplateSummary buildTemplateSummary(JsonNode template) {
String description = template.hasNonNull("Description") ? template.get("Description").asText() : null;
String version = template.hasNonNull("AWSTemplateFormatVersion")
? template.get("AWSTemplateFormatVersion").asText()
: "2010-09-09";
List<TemplateSummary.ParameterDeclaration> parameters = new ArrayList<>();
JsonNode paramsNode = template.path("Parameters");
if (paramsNode.isObject()) {
paramsNode.fields().forEachRemaining(entry -> {
JsonNode p = entry.getValue();
parameters.add(new TemplateSummary.ParameterDeclaration(
entry.getKey(),
p.hasNonNull("Default") ? p.get("Default").asText() : null,
p.path("NoEcho").asBoolean(false),
p.hasNonNull("Description") ? p.get("Description").asText() : null,
p.hasNonNull("Type") ? p.get("Type").asText() : "String"));
});
}
LinkedHashSet<String> resourceTypes = new LinkedHashSet<>();
boolean hasNamedIamResource = false;
JsonNode resourcesNode = template.path("Resources");
if (resourcesNode.isObject()) {
Iterator<Map.Entry<String, JsonNode>> resourceEntries = resourcesNode.fields();
while (resourceEntries.hasNext()) {
JsonNode resource = resourceEntries.next().getValue();
JsonNode typeNode = resource.path("Type");
if (!typeNode.isTextual()) {
continue;
}
String type = typeNode.asText();
resourceTypes.add(type);
String nameProperty = IAM_RESOURCE_NAME_PROPERTY.get(type);
// Presence alone counts as named, even when the value is an intrinsic function
// (Ref, Fn::Sub, Fn::Join, ...) that only resolves at deploy time - CloudFormation
// requires CAPABILITY_NAMED_IAM whenever the property is set at all.
if (nameProperty != null && resource.path("Properties").has(nameProperty)) {
hasNamedIamResource = true;
}
}
}
List<String> declaredTransforms = new ArrayList<>();
JsonNode transformNode = template.path("Transform");
if (transformNode.isTextual()) {
declaredTransforms.add(transformNode.asText());
} else if (transformNode.isArray()) {
transformNode.forEach(t -> {
if (t.isTextual()) {
declaredTransforms.add(t.asText());
}
});
}
List<String> iamResourceTypes = resourceTypes.stream()
.filter(t -> t.startsWith("AWS::IAM::"))
.toList();
List<String> capabilities = iamResourceTypes.isEmpty()
? List.of()
: List.of(hasNamedIamResource ? "CAPABILITY_NAMED_IAM" : "CAPABILITY_IAM");
String capabilitiesReason = iamResourceTypes.isEmpty()
? null
: "The following resource(s) require capabilities: [" + String.join(", ", iamResourceTypes) + "]";
String metadata = template.hasNonNull("Metadata") ? template.get("Metadata").toString() : null;
return new TemplateSummary(description, parameters, new ArrayList<>(resourceTypes), version,
declaredTransforms, capabilities, capabilitiesReason, metadata);
}
// ── DescribeStackEvents ───────────────────────────────────────────────────
public List<StackEvent> describeStackEvents(String stackName, String region) {
@@ -410,6 +529,7 @@ public class CloudFormationService {
String previousTemplateBody = stack.getTemplateBody();
try {
JsonNode template = parseTemplate(templateBody);
stack.setOriginalTemplateBody(templateBody);
// Apply SAM transform if the template declares AWS::Serverless-2016-10-31
if (samTransformProcessor.hasSamTransform(template)) {
@@ -17,6 +17,7 @@ public class Stack {
private Instant creationTime = Instant.now();
private Instant lastUpdatedTime;
private String templateBody;
private String originalTemplateBody;
private List<String> capabilities = new ArrayList<>();
private Map<String, String> parameters = new LinkedHashMap<>();
private Map<String, String> outputs = new LinkedHashMap<>();
@@ -45,6 +46,8 @@ public class Stack {
public void setLastUpdatedTime(Instant lastUpdatedTime) { this.lastUpdatedTime = lastUpdatedTime; }
public String getTemplateBody() { return templateBody; }
public void setTemplateBody(String templateBody) { this.templateBody = templateBody; }
public String getOriginalTemplateBody() { return originalTemplateBody; }
public void setOriginalTemplateBody(String originalTemplateBody) { this.originalTemplateBody = originalTemplateBody; }
public List<String> getCapabilities() { return capabilities; }
public void setCapabilities(List<String> capabilities) { this.capabilities = capabilities; }
public Map<String, String> getParameters() { return parameters; }
@@ -0,0 +1,27 @@
package io.github.hectorvent.floci.services.cloudformation.model;
import java.util.List;
/**
* Computed summary of a CloudFormation template, backing the GetTemplateSummary query action.
* All list fields default to an empty list rather than null so callers never need a null check.
*/
public record TemplateSummary(
String description,
List<ParameterDeclaration> parameters,
List<String> resourceTypes,
String version,
List<String> declaredTransforms,
List<String> capabilities,
String capabilitiesReason,
String metadata) {
/** One entry from the template's top level Parameters section. */
public record ParameterDeclaration(
String parameterKey,
String defaultValue,
boolean noEcho,
String description,
String parameterType) {
}
}
@@ -0,0 +1,315 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
/**
* Regression for github.com/floci-io/floci/issues/1964: GetTemplateSummary fell through to
* UnsupportedOperation, so sam deploy could not update an existing stack (it calls this action
* before UpdateStack). CloudFormation is the Query API (form-encoded request, XML response); no
* containers involved, so Docker-free.
*/
@QuarkusTest
class CloudFormationGetTemplateSummaryIntegrationTest {
@Test
void byTemplateBody_returnsResourceTypesParametersAndVersion() {
String template = """
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "A simple bucket stack",
"Parameters": {
"BucketNameParam": {
"Type": "String",
"Default": "my-default-bucket",
"Description": "Name of the bucket"
}
},
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {}
},
"MyQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {}
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplateSummary")
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<Version>2010-09-09</Version>"))
.body(containsString("<Description>A simple bucket stack</Description>"))
.body(containsString("<member>AWS::S3::Bucket</member>"))
.body(containsString("<member>AWS::SQS::Queue</member>"))
.body(containsString("<ParameterKey>BucketNameParam</ParameterKey>"))
.body(containsString("<DefaultValue>my-default-bucket</DefaultValue>"))
.body(containsString("<ParameterType>String</ParameterType>"));
}
@Test
void byStackName_reflectsTheDeployedStackTemplate() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "get-template-summary-stack-" + suffix;
String template = """
{
"Resources": {
"MyTopic": {
"Type": "AWS::SNS::Topic",
"Properties": {}
}
}
}
""";
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", "GetTemplateSummary")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<member>AWS::SNS::Topic</member>"));
}
@Test
void declaresSamTransform_soSamCliCanRecognizeIt() {
// The exact scenario from #1964: SAM templates declare this transform, and sam deploy
// calls GetTemplateSummary as part of its update flow before it will call UpdateStack.
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunction": {
"Type": "AWS::Serverless::Function",
"Properties": {}
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplateSummary")
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<member>AWS::Serverless-2016-10-31</member>"));
}
@Test
void byStackName_onDeployedSamStack_stillReflectsOriginalTransformAndTypes() {
// CreateStack expands AWS::Serverless::Function to AWS::Lambda::Function and drops the
// Transform key from the stored (post-transform) template body. GetTemplateSummary by
// StackName must still summarize the template as originally submitted, matching what
// sam deploy expects to see back for a stack it is about to update.
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "get-template-summary-sam-stack-" + suffix;
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunction": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "nodejs22.x",
"InlineCode": "exports.handler = async () => {};"
}
}
}
}
""";
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", "GetTemplateSummary")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<member>AWS::Serverless-2016-10-31</member>"))
.body(containsString("<member>AWS::Serverless::Function</member>"))
.body(not(containsString("AWS::Lambda::Function")));
}
@Test
void reportsCapabilityIam_whenTemplateHasIamResources() {
String template = """
{
"Resources": {
"MyRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": []
}
}
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplateSummary")
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<member>CAPABILITY_IAM</member>"))
.body(containsString("AWS::IAM::Role"));
}
@Test
void reportsCapabilityNamedIam_whenIamResourceHasExplicitName() {
String template = """
{
"Resources": {
"MyRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"RoleName": "my-explicit-role-name",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": []
}
}
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplateSummary")
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<member>CAPABILITY_NAMED_IAM</member>"))
.body(not(containsString("<member>CAPABILITY_IAM</member>")));
}
@Test
void reportsCapabilityNamedIam_whenRoleNameIsAnIntrinsicFunction() {
// RoleName set via Fn::Sub (or Ref, Fn::Join, ...) only resolves at deploy time, but
// CloudFormation still requires CAPABILITY_NAMED_IAM whenever the property is present at
// all - this is the common real-world shape (SAM/CDK rarely hardcode literal names).
String template = """
{
"Resources": {
"MyRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"RoleName": { "Fn::Sub": "${AWS::StackName}-role" },
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": []
}
}
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplateSummary")
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<member>CAPABILITY_NAMED_IAM</member>"))
.body(not(containsString("<member>CAPABILITY_IAM</member>")));
}
@Test
void withoutIamResources_reportsNoCapabilities() {
String template = """
{
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {}
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplateSummary")
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("CAPABILITY_IAM")));
}
@Test
void withoutAnyTemplateSource_returnsValidationError() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplateSummary")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("ValidationError"));
}
@Test
void unknownStackName_returnsValidationError() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplateSummary")
.formParam("StackName", "this-stack-does-not-exist")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("ValidationError"));
}
}