mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(cloudformation): refuse a template body that does not parse (#6179)
* fix(cloudformation): refuse a template body that does not parse
ValidateTemplate answered success for a body that reads as neither JSON nor
YAML, since the null value check skipped a template it could not parse.
CloudFormation refuses such a body at the request, and so does Floci now, in
ValidateTemplate, CreateStack, UpdateStack, CreateChangeSet and
GetTemplateSummary, all measured with the same texts.
CloudFormation reads a body as YAML, of which JSON is a subset, so the new
CloudFormationTemplateParser tries strict JSON first (trailing tokens refused)
and falls back to the CF-aware YAML parser, which also reads JSON with a
trailing comma or unquoted keys, as AWS does. When both fail, a body that
starts with { and ends with } is "JSON not well-formed" at Jackson's position,
anything else "YAML not well-formed" at SnakeYAML's, both 1-based and taken
from the body as sent, so leading blank lines keep their line numbers. A body
that reads as a scalar or a list is "unsupported structure.".
Stack sets keep their null check skipping a body that does not parse, since
CreateStackSet was not measured with one. A template that reads but has no
Resources member is left as it was: that is a check of a template, not of
its format.
* fix(cloudformation): refuse a body that is no template in stack sets too
CreateStackSet and UpdateStackSet stored a body that does not parse, whose
instances then could not deploy: CreateStackInstances and UpdateStackSet
stopped halfway with the change set's 400. Measured on CloudFormation, both
refuse such a body before keeping it, with the same texts followed by the
service exception's details, as they refuse a null value, and an update
leaves the previous body in place. They now go through the same check as the
other operations, so a stored body always parses.
The JSON message also needs the body to start with {, not only to end with }:
[{"a": 1} is YAML not well-formed at line 1, column 10 on CloudFormation.
This commit is contained in:
1 parent
09343917c1
commit
a6433d521a
7 files changed
+245
-41
No files matched your search
+35
-26
@@ -401,7 +401,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
Map<String, String> tags, String region, String accountId,
|
||||
boolean attachToReviewInProgressStack, boolean fromPreviousTemplate) {
|
||||
String resolvedTemplate = resolveTemplate(templateBody, templateUrl);
|
||||
requireNoNullValues(resolvedTemplate);
|
||||
requireValidTemplate(resolvedTemplate);
|
||||
boolean isCreateType = "CREATE".equalsIgnoreCase(changeSetType);
|
||||
// An update names its stack by name or stack ID; the map is keyed by name. One that names no
|
||||
// live stack is keyed as given, so it lands in the missing-stack branch below.
|
||||
@@ -1567,13 +1567,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
"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);
|
||||
return buildTemplateSummary(readTemplate(resolvedBody));
|
||||
}
|
||||
|
||||
/** Each parameter the template declares, with its {@link #parameterType}. */
|
||||
@@ -3939,13 +3933,28 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode parseTemplate(String templateBody) throws Exception {
|
||||
String trimmed = templateBody != null ? templateBody.trim() : "{}";
|
||||
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
||||
return objectMapper.readTree(trimmed);
|
||||
private JsonNode parseTemplate(String templateBody) throws CloudFormationTemplateParser.TemplateFormatException {
|
||||
return new CloudFormationTemplateParser(objectMapper).parse(templateBody);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code templateBody} parsed, refused as CloudFormation refuses a body that is no template
|
||||
* (measured, eu-west-1, 2026-10-21, for ValidateTemplate, CreateStack, UpdateStack,
|
||||
* CreateChangeSet, GetTemplateSummary, CreateStackSet and UpdateStackSet):
|
||||
* one that reads as neither JSON nor YAML, with the parser's position, and one that reads as a
|
||||
* scalar or a list. A null template passes, for the checks that answer it.
|
||||
*/
|
||||
private JsonNode readTemplate(String templateBody) {
|
||||
JsonNode parsed;
|
||||
try {
|
||||
parsed = parseTemplate(templateBody);
|
||||
} catch (CloudFormationTemplateParser.TemplateFormatException e) {
|
||||
throw new AwsException("ValidationError", "Template format error: " + e.getMessage(), 400);
|
||||
}
|
||||
// YAML template — use CF-aware parser to handle !Sub, !Ref, !GetAtt etc.
|
||||
return new CloudFormationYamlParser(objectMapper).parse(trimmed);
|
||||
if (parsed != null && !parsed.isNull() && !parsed.isObject()) {
|
||||
throw new AwsException("ValidationError", "Template format error: unsupported structure.", 400);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private String resolveTemplate(String templateBody, String templateUrl) {
|
||||
@@ -4493,14 +4502,23 @@ public class CloudFormationService implements ResourceProvider {
|
||||
return value;
|
||||
}
|
||||
|
||||
/** ValidateTemplate's check of a template: the null values AWS refuses there. */
|
||||
/** ValidateTemplate's check of a template: one that is no template, and the null values AWS refuses there. */
|
||||
public void validateTemplate(String templateBody, String templateUrl) {
|
||||
String resolvedBody = resolveTemplateBody(templateBody, templateUrl);
|
||||
if (resolvedBody != null) {
|
||||
requireNoNullValues(resolvedBody);
|
||||
requireValidTemplate(resolvedBody);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The checks ValidateTemplate, CreateStack, UpdateStack, CreateChangeSet, CreateStackSet and
|
||||
* UpdateStackSet make of a template before anything is created or kept: a body that is no
|
||||
* template ({@link #readTemplate}), then its null values ({@link #requireNoNullValues}).
|
||||
*/
|
||||
void requireValidTemplate(String templateBody) {
|
||||
requireNoNullValues(readTemplate(templateBody));
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a template that holds a null value anywhere, as AWS does when ValidateTemplate,
|
||||
* CreateStack, UpdateStack or CreateChangeSet is requested, before anything is created
|
||||
@@ -4508,16 +4526,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* templates", naming the first null in document order. Below a resource's Properties the path
|
||||
* says Type where Properties would be, as AWS's does; a null Properties is named as it is.
|
||||
*/
|
||||
void requireNoNullValues(String templateBody) {
|
||||
JsonNode parsed;
|
||||
try {
|
||||
parsed = parseTemplate(templateBody);
|
||||
} catch (Exception e) {
|
||||
// As validateResourceDependencies: a template that does not parse fails where it is
|
||||
// processed, with the parser's error.
|
||||
LOG.debugv("Skipping null value validation; template did not parse: {0}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
private static void requireNoNullValues(JsonNode parsed) {
|
||||
if (parsed == null || parsed.isNull()) {
|
||||
// Measured: a template that is null as a whole ("null", "~") lacks its resources first.
|
||||
throw new AwsException("ValidationError",
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonLocation;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.yaml.snakeyaml.error.Mark;
|
||||
import org.yaml.snakeyaml.error.MarkedYAMLException;
|
||||
import org.yaml.snakeyaml.error.YAMLException;
|
||||
|
||||
/**
|
||||
* A template body read as CloudFormation reads it (measured, eu-west-1, 2026-10-21): as YAML, of
|
||||
* which JSON is a subset, so a body that is not strict JSON, such as {@code {a: 1}} or a trailing
|
||||
* comma, still reads as YAML's flow style. A body that reads as neither is "JSON not well-formed"
|
||||
* when it starts with {@code {} and ends with {@code }}, at the JSON parser's position, and "YAML
|
||||
* not well-formed" otherwise, at the YAML parser's; both positions are 1-based.
|
||||
*/
|
||||
final class CloudFormationTemplateParser {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
CloudFormationTemplateParser(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/** A body that reads as neither JSON nor YAML, with CloudFormation's words for it. */
|
||||
static final class TemplateFormatException extends Exception {
|
||||
|
||||
TemplateFormatException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
|
||||
JsonNode parse(String templateBody) throws TemplateFormatException {
|
||||
String body = templateBody != null ? templateBody : "{}";
|
||||
String trimmed = body.trim();
|
||||
JsonProcessingException jsonError = null;
|
||||
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
||||
try {
|
||||
return objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(body);
|
||||
} catch (JsonProcessingException e) {
|
||||
jsonError = e;
|
||||
}
|
||||
}
|
||||
try {
|
||||
// The CF-aware parser turns !Sub, !Ref, !GetAtt and the other short forms into their maps.
|
||||
return new CloudFormationYamlParser(objectMapper).parse(body);
|
||||
} catch (YAMLException yamlError) {
|
||||
if (jsonError != null && trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
||||
JsonLocation at = jsonError.getLocation();
|
||||
throw new TemplateFormatException("JSON not well-formed. (line " + at.getLineNr()
|
||||
+ ", column " + at.getColumnNr() + ")", jsonError);
|
||||
}
|
||||
throw new TemplateFormatException("YAML not well-formed." + position(yamlError), yamlError);
|
||||
}
|
||||
}
|
||||
|
||||
/** Where the YAML parser stopped, 1-based as CloudFormation counts; nothing for an error with no mark. */
|
||||
private static String position(YAMLException error) {
|
||||
if (!(error instanceof MarkedYAMLException marked)) {
|
||||
return "";
|
||||
}
|
||||
Mark mark = marked.getProblemMark() != null ? marked.getProblemMark() : marked.getContextMark();
|
||||
return mark == null ? "" : " (line " + (mark.getLine() + 1) + ", column " + (mark.getColumn() + 1) + ")";
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -30,7 +30,7 @@ public class CloudFormationYamlParser {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public JsonNode parse(String yamlContent) throws Exception {
|
||||
public JsonNode parse(String yamlContent) {
|
||||
LoaderOptions opts = new LoaderOptions();
|
||||
opts.setMaxAliasesForCollections(200);
|
||||
Yaml yaml = new Yaml(new CfnConstructor(opts));
|
||||
|
||||
+8
-7
@@ -133,7 +133,7 @@ public class StackSetService implements PassedRoleLookup {
|
||||
if ("SELF_MANAGED".equals(resolvedPermissionModel) && (autoDeploymentEnabled || retainStacksOnAccountRemoval)) {
|
||||
throw new AwsException("ValidationError", "AutoDeployment is valid only for SERVICE_MANAGED StackSets.", 400);
|
||||
}
|
||||
requireNoNullValues(templateBody);
|
||||
requireValidTemplate(templateBody);
|
||||
// Every instance is deployed with these parameters, so a template parameter left without a
|
||||
// value would fail each one; refuse the stack set instead.
|
||||
cfnService.requireParameterValues(templateBody, parameters);
|
||||
@@ -212,7 +212,7 @@ public class StackSetService implements PassedRoleLookup {
|
||||
// Checked against the template and parameters the update leaves the stack set with, before
|
||||
// either is changed or an operation is recorded.
|
||||
String keptTemplate = templateBody != null && !templateBody.isBlank() ? templateBody : ss.getTemplateBody();
|
||||
requireNoNullValues(keptTemplate);
|
||||
requireValidTemplate(keptTemplate);
|
||||
cfnService.requireParameterValues(keptTemplate,
|
||||
parameters != null && !parameters.isEmpty() ? parameters : ss.getParameters());
|
||||
String operationId = reserveOperation(name, "UPDATE", requestedOperationId).getOperationId();
|
||||
@@ -724,13 +724,14 @@ public class StackSetService implements PassedRoleLookup {
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a template holding a null value before the stack set stores it, as CreateStackSet and
|
||||
* UpdateStackSet do (measured, eu-west-1, 2026-10-20). StackSets passes CloudFormation's message
|
||||
* on with the details of the service exception it came in.
|
||||
* Refuses a body that is no template, or a template holding a null value, before the stack set
|
||||
* stores it, as CreateStackSet and UpdateStackSet do (measured, eu-west-1, 2026-10-20 and
|
||||
* 2026-10-21). StackSets passes CloudFormation's message on with the details of the service
|
||||
* exception it came in.
|
||||
*/
|
||||
private void requireNoNullValues(String templateBody) {
|
||||
private void requireValidTemplate(String templateBody) {
|
||||
try {
|
||||
cfnService.requireNoNullValues(templateBody);
|
||||
cfnService.requireValidTemplate(templateBody);
|
||||
} catch (AwsException e) {
|
||||
throw new AwsException(e.getErrorCode(), CloudFormationTemplateEngine.sdkErrorMessage(
|
||||
e.getMessage(), "AmazonCloudFormation", e.getHttpStatus(), e.getErrorCode()), e.getHttpStatus());
|
||||
|
||||
Reference in new issue
Block a user