mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): validate vendored properties in HandlerReader (#8733)
* fix(cloudformation): validate SES properties in HandlerReader * fix(cloudformation): apply HandlerReader validation across vendored types * test(cloudformation): share HandlerReader failure assertions
This commit is contained in:
1 parent
2906767f77
commit
70da9dfb0c
4 files changed
+177
-76
No files matched your search
+30
-34
@@ -82,35 +82,6 @@ final class CfnPropertyTypes {
|
||||
return shape;
|
||||
}
|
||||
|
||||
/** Reject unmodeled members for a provisioner that passes the whole schema-shaped object to a service. */
|
||||
static void rejectUnknownMembers(String resourceType, JsonNode properties) {
|
||||
String shape = Holder.MODEL.operations().get(resourceType);
|
||||
if (shape == null) {
|
||||
throw notVendored(resourceType);
|
||||
}
|
||||
rejectUnknownMembers(properties, shape);
|
||||
}
|
||||
|
||||
private static void rejectUnknownMembers(JsonNode value, String shapeName) {
|
||||
if (value == null || value.isNull()) {
|
||||
return;
|
||||
}
|
||||
Shape shape = Holder.MODEL.shapes().get(shapeName);
|
||||
if ("structure".equals(shape.type()) && value.isObject()) {
|
||||
value.properties().forEach(member -> {
|
||||
String nested = shape.members().get(member.getKey());
|
||||
if (nested == null) {
|
||||
throw new AwsException("ValidationError", "Unknown property: " + member.getKey(), 400);
|
||||
}
|
||||
rejectUnknownMembers(member.getValue(), nested);
|
||||
});
|
||||
} else if ("list".equals(shape.type()) && value.isArray()) {
|
||||
value.forEach(element -> rejectUnknownMembers(element, shape.element()));
|
||||
} else if ("map".equals(shape.type()) && value.isObject()) {
|
||||
value.forEach(element -> rejectUnknownMembers(element, shape.element()));
|
||||
}
|
||||
}
|
||||
|
||||
private static IllegalStateException notVendored(String what) {
|
||||
return new IllegalStateException(what + " is not in " + RESOURCE_NAME
|
||||
+ "; add the type to tools/aws/regen_cfn_property_types.py");
|
||||
@@ -170,9 +141,8 @@ final class CfnPropertyTypes {
|
||||
|
||||
/**
|
||||
* A walk over template values against the shapes the resource schemas declare, resolving them
|
||||
* on the way. What {@code AWS::NoValue} stands for is left out, and members a shape does not
|
||||
* declare are resolved as they are. How a scalar converts, and what a value of the wrong type
|
||||
* does, is each reader's own.
|
||||
* on the way. What {@code AWS::NoValue} stands for is left out. How an unmodeled member or a
|
||||
* scalar converts, and what a value of the wrong type does, is each reader's own.
|
||||
*/
|
||||
private abstract static class ShapeWalk {
|
||||
|
||||
@@ -200,6 +170,10 @@ final class CfnPropertyTypes {
|
||||
return value.properties();
|
||||
}
|
||||
|
||||
JsonNode readUnknown(String path, String name, JsonNode raw) {
|
||||
return engine.resolveNode(raw);
|
||||
}
|
||||
|
||||
JsonNode read(String path, String property, JsonNode raw, String shapeName) {
|
||||
if (raw == null || raw.isNull() || raw.isMissingNode()) {
|
||||
return null;
|
||||
@@ -240,7 +214,7 @@ final class CfnPropertyTypes {
|
||||
ObjectNode out = JsonNodeFactory.instance.objectNode();
|
||||
for (Map.Entry<String, JsonNode> member : members(value, shape)) {
|
||||
String memberShape = shape.members().get(member.getKey());
|
||||
JsonNode read = memberShape == null ? engine.resolveNode(member.getValue())
|
||||
JsonNode read = memberShape == null ? readUnknown(path, member.getKey(), member.getValue())
|
||||
: read(child(path, member.getKey()), member.getKey(), member.getValue(), memberShape);
|
||||
if (read != null) {
|
||||
out.set(member.getKey(), read);
|
||||
@@ -430,6 +404,7 @@ final class CfnPropertyTypes {
|
||||
|
||||
private final List<Violation> violations = new ArrayList<>();
|
||||
private boolean unconverted;
|
||||
private boolean preserveEcsHandlerSemantics;
|
||||
|
||||
HandlerReader(CloudFormationTemplateEngine engine) {
|
||||
this(engine, Holder.MODEL);
|
||||
@@ -445,6 +420,8 @@ final class CfnPropertyTypes {
|
||||
if (shape == null) {
|
||||
throw notVendored(resourceType);
|
||||
}
|
||||
// ECS forwards unmodeled members and uses presence-only required checks in its API path.
|
||||
preserveEcsHandlerSemantics = "AWS::ECS::TaskDefinition".equals(resourceType);
|
||||
JsonNode raw = props == null || props.isNull() ? JsonNodeFactory.instance.objectNode() : props;
|
||||
JsonNode read = read("", "", engine.omitNoValue(raw), shape);
|
||||
if (unconverted) {
|
||||
@@ -497,7 +474,17 @@ final class CfnPropertyTypes {
|
||||
@Override
|
||||
void checkRequired(String path, JsonNode value, Shape shape) {
|
||||
for (String member : shape.required()) {
|
||||
if (!value.has(member)) {
|
||||
JsonNode raw = value.get(member);
|
||||
boolean absent = raw == null;
|
||||
if (!absent && !preserveEcsHandlerSemantics) {
|
||||
absent = raw.isNull() || raw.isMissingNode();
|
||||
if (!absent && "string".equals(model.shapes().get(shape.members().get(member)).type())) {
|
||||
JsonNode resolved = engine.resolveNode(raw);
|
||||
absent = resolved == null || resolved.isNull() || resolved.isMissingNode()
|
||||
|| resolved.isTextual() && resolved.textValue().isBlank();
|
||||
}
|
||||
}
|
||||
if (absent) {
|
||||
record(new Violation(path, "required key [" + member + "] not found", true), true);
|
||||
}
|
||||
}
|
||||
@@ -516,6 +503,15 @@ final class CfnPropertyTypes {
|
||||
return ordered.entrySet();
|
||||
}
|
||||
|
||||
@Override
|
||||
JsonNode readUnknown(String path, String name, JsonNode raw) {
|
||||
if (preserveEcsHandlerSemantics) {
|
||||
return super.readUnknown(path, name, raw);
|
||||
}
|
||||
record(new Violation(path, "extraneous key [" + name + "] is not permitted", false), false);
|
||||
return null;
|
||||
}
|
||||
|
||||
private void record(Violation violation, boolean converts) {
|
||||
violations.add(violation);
|
||||
unconverted |= !converts;
|
||||
|
||||
-27
@@ -43,7 +43,6 @@ public class SesEventDestinationCfnProvisioner implements CfnResourceProvisioner
|
||||
if (resolved == null || !resolved.isObject()) {
|
||||
throw invalid("Properties must be an object.");
|
||||
}
|
||||
CfnPropertyTypes.rejectUnknownMembers(TYPE, resolved);
|
||||
if (resolved.has("Id")) {
|
||||
throw invalid("Unknown property: Id");
|
||||
}
|
||||
@@ -54,7 +53,6 @@ public class SesEventDestinationCfnProvisioner implements CfnResourceProvisioner
|
||||
if (!definition.isObject()) {
|
||||
throw invalid("EventDestination must be an object.");
|
||||
}
|
||||
validateNonblankRequiredValues(definition);
|
||||
String explicitName = optionalText(definition, "Name");
|
||||
Address prior = priorAddress(resource, ctx);
|
||||
String name = explicitName != null && !explicitName.isBlank() ? explicitName
|
||||
@@ -155,31 +153,6 @@ public class SesEventDestinationCfnProvisioner implements CfnResourceProvisioner
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateNonblankRequiredValues(JsonNode definition) {
|
||||
// HandlerReader checks schema types and missing members; these reject blank strings and nulls it omits.
|
||||
if (!definition.has("MatchingEventTypes")) {
|
||||
throw invalid("MatchingEventTypes is required.");
|
||||
}
|
||||
if (definition.path("SnsDestination").isObject()) {
|
||||
requiredText(definition.get("SnsDestination"), "TopicARN");
|
||||
}
|
||||
if (definition.path("KinesisFirehoseDestination").isObject()) {
|
||||
requiredText(definition.get("KinesisFirehoseDestination"), "IAMRoleARN");
|
||||
requiredText(definition.get("KinesisFirehoseDestination"), "DeliveryStreamARN");
|
||||
}
|
||||
if (definition.path("EventBridgeDestination").isObject()) {
|
||||
requiredText(definition.get("EventBridgeDestination"), "EventBusArn");
|
||||
}
|
||||
JsonNode dimensions = definition.path("CloudWatchDestination").path("DimensionConfigurations");
|
||||
if (dimensions.isArray()) {
|
||||
for (JsonNode dimension : dimensions) {
|
||||
requiredText(dimension, "DimensionName");
|
||||
requiredText(dimension, "DimensionValueSource");
|
||||
requiredText(dimension, "DefaultDimensionValue");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void rename(ObjectNode node, String from, String to) {
|
||||
JsonNode value = node.remove(from);
|
||||
if (value != null) {
|
||||
|
||||
+133
-5
@@ -114,11 +114,7 @@ class CfnPropertyTypesTest {
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@MethodSource("ecsTaskDefinitions")
|
||||
void anEcsTaskDefinitionFailsWhereTheEcsHandlerDoes(String measured, String properties, String violations) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> new CfnPropertyTypes.HandlerReader(engine())
|
||||
.read("AWS::ECS::TaskDefinition", json(properties)));
|
||||
|
||||
assertEquals("InvalidRequest", e.getErrorCode());
|
||||
assertEquals("Model validation failed (" + violations, e.getMessage());
|
||||
assertHandlerReaderFailure("AWS::ECS::TaskDefinition", properties, "Model validation failed (" + violations);
|
||||
}
|
||||
|
||||
static Stream<Arguments> ecsTaskDefinitions() {
|
||||
@@ -248,6 +244,138 @@ class CfnPropertyTypesTest {
|
||||
"""), read);
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@MethodSource("invalidSesRequiredValues")
|
||||
void handlerReaderRejectsNullAndBlankRequiredMembers(String caseName, String properties, String violation) {
|
||||
assertHandlerReaderFailure("AWS::SES::ConfigurationSetEventDestination", properties,
|
||||
"Model validation failed (" + violation + ")");
|
||||
}
|
||||
|
||||
static Stream<Arguments> invalidSesRequiredValues() {
|
||||
return Stream.of(
|
||||
Arguments.of("null root name",
|
||||
"{\"ConfigurationSetName\":null,\"EventDestination\":{\"MatchingEventTypes\":[\"SEND\"]}}",
|
||||
"#: required key [ConfigurationSetName] not found"),
|
||||
Arguments.of("blank root name",
|
||||
"{\"ConfigurationSetName\":\" \",\"EventDestination\":{\"MatchingEventTypes\":[\"SEND\"]}}",
|
||||
"#: required key [ConfigurationSetName] not found"),
|
||||
Arguments.of("resolved blank root name",
|
||||
"{\"ConfigurationSetName\":{\"Fn::Sub\":\"\"},\"EventDestination\":{\"MatchingEventTypes\":[\"SEND\"]}}",
|
||||
"#: required key [ConfigurationSetName] not found"),
|
||||
Arguments.of("omitted root name",
|
||||
"{\"ConfigurationSetName\":{\"Ref\":\"AWS::NoValue\"},\"EventDestination\":{\"MatchingEventTypes\":[\"SEND\"]}}",
|
||||
"#: required key [ConfigurationSetName] not found"),
|
||||
Arguments.of("null event list",
|
||||
"{\"ConfigurationSetName\":\"set\",\"EventDestination\":{\"MatchingEventTypes\":null}}",
|
||||
"#/EventDestination: required key [MatchingEventTypes] not found"),
|
||||
Arguments.of("null nested ARN",
|
||||
"{\"ConfigurationSetName\":\"set\",\"EventDestination\":{\"MatchingEventTypes\":[\"SEND\"],\"SnsDestination\":{\"TopicARN\":null}}}",
|
||||
"#/EventDestination/SnsDestination: required key [TopicARN] not found"),
|
||||
Arguments.of("blank nested ARN",
|
||||
"{\"ConfigurationSetName\":\"set\",\"EventDestination\":{\"MatchingEventTypes\":[\"SEND\"],\"SnsDestination\":{\"TopicARN\":\" \"}}}",
|
||||
"#/EventDestination/SnsDestination: required key [TopicARN] not found"));
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@MethodSource("unknownSesMembers")
|
||||
void handlerReaderRejectsExtraneousMembers(String caseName, String properties, String violation) {
|
||||
assertHandlerReaderFailure("AWS::SES::ConfigurationSetEventDestination", properties,
|
||||
"Model validation failed (" + violation + ")");
|
||||
}
|
||||
|
||||
static Stream<Arguments> unknownSesMembers() {
|
||||
return Stream.of(
|
||||
Arguments.of("top-level member",
|
||||
"{\"ConfigurationSetName\":\"set\",\"EventDestination\":{\"MatchingEventTypes\":[\"SEND\"]},\"Extra\":true}",
|
||||
"#: extraneous key [Extra] is not permitted"),
|
||||
Arguments.of("nested member",
|
||||
"{\"ConfigurationSetName\":\"set\",\"EventDestination\":{\"MatchingEventTypes\":[\"SEND\"],\"SnsDestination\":{\"TopicARN\":\"arn\",\"Extra\":true}}}",
|
||||
"#/EventDestination/SnsDestination: extraneous key [Extra] is not permitted"));
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@MethodSource("invalidLaunchConfigurationProperties")
|
||||
void handlerReaderValidatesAnotherVendoredType(String caseName, String properties, String violation) {
|
||||
assertHandlerReaderFailure("AWS::AutoScaling::LaunchConfiguration", properties,
|
||||
"Model validation failed (" + violation + ")");
|
||||
}
|
||||
|
||||
private static void assertHandlerReaderFailure(String resourceType, String properties, String expectedMessage) {
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> new CfnPropertyTypes.HandlerReader(engine())
|
||||
.read(resourceType, json(properties)));
|
||||
|
||||
assertEquals("InvalidRequest", failure.getErrorCode());
|
||||
assertEquals(expectedMessage, failure.getMessage());
|
||||
}
|
||||
|
||||
static Stream<Arguments> invalidLaunchConfigurationProperties() {
|
||||
return Stream.of(
|
||||
Arguments.of("null required ImageId",
|
||||
"{\"ImageId\":null,\"InstanceType\":\"t3.micro\"}",
|
||||
"#: required key [ImageId] not found"),
|
||||
Arguments.of("blank required InstanceType",
|
||||
"{\"ImageId\":\"ami-123\",\"InstanceType\":\" \"}",
|
||||
"#: required key [InstanceType] not found"),
|
||||
Arguments.of("extraneous root member",
|
||||
"{\"ImageId\":\"ami-123\",\"InstanceType\":\"t3.micro\",\"Extra\":true}",
|
||||
"#: extraneous key [Extra] is not permitted"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("strictVendoredTypes")
|
||||
void handlerReaderRejectsUnmodeledMembersAcrossVendoredTypes(String resourceType) {
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> new CfnPropertyTypes.HandlerReader(engine()).read(resourceType, json("{\"Extra\":true}")));
|
||||
|
||||
assertEquals("InvalidRequest", failure.getErrorCode());
|
||||
assertTrue(failure.getMessage().contains("#: extraneous key [Extra] is not permitted"), failure.getMessage());
|
||||
}
|
||||
|
||||
static Stream<Arguments> strictVendoredTypes() {
|
||||
return RequestShapeModel.load(CfnPropertyTypes.RESOURCE_NAME, "CloudFormation property types")
|
||||
.operations().keySet().stream()
|
||||
.filter(type -> !"AWS::ECS::TaskDefinition".equals(type))
|
||||
.map(Arguments::of);
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlerReaderLeavesMapEntriesAndFreeFormValuesAlone() {
|
||||
JsonNode read = new CfnPropertyTypes.HandlerReader(engine(), MODEL).read("AWS::Test::Thing",
|
||||
json("{\"Config\":{\"Headers\":{\"custom\":\"\"}},\"Pattern\":{\"custom\":{\"nested\":1}}}"));
|
||||
|
||||
assertEquals(json("{\"Config\":{\"Headers\":{\"custom\":\"\"}},\"Pattern\":{\"custom\":{\"nested\":1}}}"), read);
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlerReaderPassesUnmodeledEcsMembersThrough() {
|
||||
JsonNode properties = json("{\"ContainerDefinitions\":[{\"Name\":\"app\",\"Image\":\"busybox\",\"Extra\":true}]}");
|
||||
|
||||
assertEquals(properties, new CfnPropertyTypes.HandlerReader(engine())
|
||||
.read("AWS::ECS::TaskDefinition", properties));
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlerReaderReportsKnownMembersBeforeExtraneousMembers() {
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> new CfnPropertyTypes.HandlerReader(engine())
|
||||
.read("AWS::SES::ConfigurationSetEventDestination", json("""
|
||||
{"ConfigurationSetName":"set","EventDestination":{
|
||||
"Extra":true,"MatchingEventTypes":["SEND"],"Enabled":"bogus"}}
|
||||
""")));
|
||||
|
||||
assertEquals("Model validation failed (#/EventDestination/Enabled: expected type: Boolean, found: String\n"
|
||||
+ "#/EventDestination: extraneous key [Extra] is not permitted)", failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlerReaderLeavesEcsRequiredBlankStringsToItsExistingPath() {
|
||||
JsonNode properties = json("{\"ContainerDefinitions\":[{\"Name\":\"\",\"Image\":\" \"}]}");
|
||||
|
||||
assertEquals(properties, new CfnPropertyTypes.HandlerReader(engine())
|
||||
.read("AWS::ECS::TaskDefinition", properties));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aResourceTypeTheVendoredFileLacksIsAnErrorOfTheBuild() {
|
||||
assertThrows(IllegalStateException.class,
|
||||
|
||||
+14
-10
@@ -88,13 +88,17 @@ class SesEventDestinationCfnProvisionerTest {
|
||||
@Test
|
||||
void rejectsUnsupportedNestedDestinationProperties() {
|
||||
ObjectNode props = properties("first", "events", true);
|
||||
props.withObject("EventDestination").remove("Enabled");
|
||||
props.withObject("EventDestination").putObject("SnsDestination")
|
||||
.put("TopicARN", "arn:aws:sns:us-east-1:000000000000:events")
|
||||
.put("Unexpected", "ignored");
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, context(null)));
|
||||
verify(configurationSets, never()).createEventDestination(eq("first"), eq("events"),
|
||||
any(EventDestination.class), eq(ACCOUNT), eq(REGION), eq(true));
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource(), props, context(null)));
|
||||
assertEquals("InvalidRequest", failure.getErrorCode());
|
||||
assertEquals("Model validation failed (#/EventDestination/SnsDestination: extraneous key"
|
||||
+ " [Unexpected] is not permitted)", failure.getMessage());
|
||||
verifyNoInteractions(configurationSets);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -105,7 +109,7 @@ class SesEventDestinationCfnProvisionerTest {
|
||||
|
||||
ObjectNode blank = properties("first", "events", true);
|
||||
blank.withObject("EventDestination").putObject("SnsDestination").put("TopicARN", " ");
|
||||
assertInvalidWithoutSesCall(blank);
|
||||
assertSchemaInvalidWithoutSesCall(blank);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -119,7 +123,7 @@ class SesEventDestinationCfnProvisionerTest {
|
||||
blank.withObject("EventDestination").putObject("KinesisFirehoseDestination")
|
||||
.put("IAMRoleARN", " ")
|
||||
.put("DeliveryStreamARN", "arn:aws:firehose:us-east-1:000000000000:deliverystream/events");
|
||||
assertInvalidWithoutSesCall(blank);
|
||||
assertSchemaInvalidWithoutSesCall(blank);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -130,7 +134,7 @@ class SesEventDestinationCfnProvisionerTest {
|
||||
|
||||
ObjectNode blank = properties("first", "events", true);
|
||||
blank.withObject("EventDestination").putObject("EventBridgeDestination").put("EventBusArn", " ");
|
||||
assertInvalidWithoutSesCall(blank);
|
||||
assertSchemaInvalidWithoutSesCall(blank);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -140,7 +144,7 @@ class SesEventDestinationCfnProvisionerTest {
|
||||
assertSchemaInvalidWithoutSesCall(missingSet);
|
||||
|
||||
ObjectNode blankSet = properties("first", "events", true).put("ConfigurationSetName", " ");
|
||||
assertInvalidWithoutSesCall(blankSet);
|
||||
assertSchemaInvalidWithoutSesCall(blankSet);
|
||||
|
||||
ObjectNode nonObjectDestination = properties("first", "events", true)
|
||||
.put("EventDestination", "events");
|
||||
@@ -182,11 +186,11 @@ class SesEventDestinationCfnProvisionerTest {
|
||||
void rejectsNullRequiredMembersAndDimensionEntriesBeforeCallingSes() {
|
||||
ObjectNode nullEvents = properties("first", "events", true);
|
||||
nullEvents.withObject("EventDestination").putNull("MatchingEventTypes");
|
||||
assertInvalidWithoutSesCall(nullEvents);
|
||||
assertSchemaInvalidWithoutSesCall(nullEvents);
|
||||
|
||||
ObjectNode nullTopic = properties("first", "events", true);
|
||||
nullTopic.withObject("EventDestination").putObject("SnsDestination").putNull("TopicARN");
|
||||
assertInvalidWithoutSesCall(nullTopic);
|
||||
assertSchemaInvalidWithoutSesCall(nullTopic);
|
||||
|
||||
ObjectNode nullDimensionName = properties("first", "events", true);
|
||||
nullDimensionName.withObject("EventDestination").putObject("CloudWatchDestination")
|
||||
@@ -194,7 +198,7 @@ class SesEventDestinationCfnProvisionerTest {
|
||||
.put("DimensionValueSource", "messageTag")
|
||||
.put("DefaultDimensionValue", "unknown")
|
||||
.putNull("DimensionName");
|
||||
assertInvalidWithoutSesCall(nullDimensionName);
|
||||
assertSchemaInvalidWithoutSesCall(nullDimensionName);
|
||||
|
||||
ObjectNode nullDimensionEntry = properties("first", "events", true);
|
||||
nullDimensionEntry.withObject("EventDestination").putObject("CloudWatchDestination")
|
||||
|
||||
Reference in new issue
Block a user