diff --git a/Makefile b/Makefile index 1f5df1a4f0..588ff96c6c 100644 --- a/Makefile +++ b/Makefile @@ -310,6 +310,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s $(PYTHON) tools/aws/regen_securityhub_shapes.py $(PYTHON) tools/aws/regen_rekognition_shapes.py $(PYTHON) tools/aws/regen_kinesis_shapes.py + $(PYTHON) tools/aws/regen_eventbridgev2_shapes.py $(PYTHON) tools/aws/regen_config_shapes.py $(PYTHON) tools/aws/regen_iam_shapes.py $(PYTHON) tools/aws/regen_sts_shapes.py @@ -454,6 +455,10 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres echo "error: Kinesis request shapes are out of date; run 'make aws-data-sync'."; \ exit 1; \ } + @$(PYTHON) tools/aws/regen_eventbridgev2_shapes.py --check || { \ + echo "error: EventBridge V2 request shapes are out of date; run 'make aws-data-sync'."; \ + exit 1; \ + } @$(PYTHON) tools/aws/regen_config_shapes.py --check || { \ echo "error: AWS Config request shapes are out of date; run 'make aws-data-sync'."; \ exit 1; \ diff --git a/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java b/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java index 30a40350ef..01d4a151a8 100644 --- a/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java +++ b/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java @@ -4,10 +4,15 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.TextNode; +import java.math.BigDecimal; +import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; /** @@ -17,6 +22,9 @@ import java.util.regex.Pattern; * pattern and an enum. A service supplies its own {@link Messages}, so each answers with its own * error code and wording. * + *

The check answers either way. {@link #check} throws the first violation in the service's own + * wording, {@link #violations} collects all of them in the Smithy wording. + * *

Paths start with the operation name: {@code PutReplicationConfiguration.replicationConfiguration.rules[]}, * with {@code []} for a list element and {@code .key} for a map key. */ @@ -24,6 +32,9 @@ public final class RequestConstraintCheck { private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final Set SCALAR_TYPES = + Set.of("string", "integer", "long", "boolean", "float", "double"); + /** How a service words each kind of violation. */ public interface Messages { /** {@code value} at {@code path} is not of the shape's JSON {@code type}. */ @@ -87,6 +98,7 @@ public final class RequestConstraintCheck { private final JsonNode model; private final Map patterns = new HashMap<>(); private final Messages messages; + private final Set wordable = ConcurrentHashMap.newKeySet(); private RequestConstraintCheck(JsonNode model, Messages messages) { this.model = model; @@ -220,4 +232,323 @@ public final class RequestConstraintCheck { throw messages.bounds(path, type, min, max, size); } } + + /** + * Every constraint {@code request} breaks for {@code operation}, worded as a Smithy validation + * error and in the model's member order, to be thrown with + * {@link SmithyValidationErrors#exception(String, List)}. Paths join the member names with a dot, + * each with its first letter lower-cased. A shape marked {@code sensitive} leaves its value out + * of the wording. A value of the wrong JSON type is thrown at once through {@link Messages#type}. + * + * @throws IllegalArgumentException when the model holds no input for {@code operation} + * @throws IllegalStateException when the operation's input holds a shape this walk cannot word yet + */ + public List violations(String operation, JsonNode request) { + if (!hasOperation(operation)) { + throw new IllegalArgumentException("No input shape for " + operation); + } + requireWordable(operation); + JsonNode body = request == null || request.isNull() ? MAPPER.createObjectNode() : request; + List found = new ArrayList<>(); + collectStructure(model.path("operations").get(operation).asText(), body, "", operation, found); + return found; + } + + private void requireWordable(String operation) { + if (wordable.contains(operation)) { + return; + } + Set seen = new HashSet<>(); + String input = model.path("operations").get(operation).asText(); + seen.add(input); + for (Map.Entry member : model.path("shapes").path(input).path("members").properties()) { + requireWordableMember(operation, member.getKey(), member.getValue().asText(), seen); + } + wordable.add(operation); + } + + private void requireWordableMember(String operation, String member, String name, Set seen) { + JsonNode shape = model.path("shapes").path(name); + String type = shape.path("type").asText(); + switch (type) { + case "string", "integer", "long", "float", "double", "boolean" -> { + } + case "structure" -> { + if (seen.add(name)) { + for (Map.Entry field : shape.path("members").properties()) { + requireWordableMember(operation, member + "." + field.getKey(), + field.getValue().asText(), seen); + } + } + } + case "list" -> { + JsonNode element = model.path("shapes").path(shape.path("member").asText()); + String elementType = element.path("type").asText(); + boolean bounded = element.has("min") || element.has("max"); + if (!SCALAR_TYPES.contains(elementType) || bounded && !"string".equals(elementType)) { + throw unwordable(operation, member + "[]", elementType); + } + if (element.path("sensitive").asBoolean(false)) { + throw unwordable(operation, member + "[]", "sensitive " + elementType); + } + } + case "map" -> { + for (String side : List.of("key", "value")) { + JsonNode sideShape = model.path("shapes").path(shape.path(side).asText()); + String sideType = sideShape.path("type").asText(); + if (!"string".equals(sideType)) { + throw unwordable(operation, member + "." + side, sideType); + } + if (sideShape.path("sensitive").asBoolean(false)) { + throw unwordable(operation, member + "." + side, "sensitive " + sideType); + } + } + } + default -> throw unwordable(operation, member, type); + } + } + + private static IllegalStateException unwordable(String operation, String member, String type) { + return new IllegalStateException(operation + "'s " + member + " is a " + type + + ", which this check does not word yet"); + } + + private void collectStructure(String name, JsonNode value, String path, String errorPath, List found) { + JsonNode shape = model.path("shapes").path(name); + if (!value.isObject()) { + throw messages.type(errorPath, "structure"); + } + Set required = new HashSet<>(); + shape.path("required").forEach(member -> required.add(member.asText())); + for (Map.Entry member : shape.path("members").properties()) { + String field = member.getKey(); + String memberPath = (path.isEmpty() ? "" : path + ".") + lowerFirst(field); + JsonNode child = value.get(field); + if (child == null || child.isNull()) { + if (required.contains(field)) { + found.add(SmithyValidationErrors.notNull(memberPath)); + } + continue; + } + collectValue(member.getValue().asText(), child, memberPath, errorPath + "." + field, found); + } + } + + private void collectValue(String name, JsonNode value, String path, String errorPath, List found) { + JsonNode shape = model.path("shapes").path(name); + String type = shape.path("type").asText(); + SmithyValidationErrors.Violations form = formOf(shape); + switch (type) { + case "structure" -> collectStructure(name, value, path, errorPath, found); + case "string" -> { + if (!value.isTextual()) { + throw messages.type(errorPath, type); + } + collectString(name, shape, value.textValue(), path, form, found); + } + case "integer", "long" -> collectInteger(shape, type, value, path, errorPath, form, found); + case "float", "double" -> { + if (!value.isNumber()) { + throw messages.type(errorPath, type); + } + BigDecimal number = value.decimalValue(); + if (shape.has("min") && number.compareTo(BigDecimal.valueOf(shape.get("min").asLong())) < 0) { + found.add(form.valueTooSmall(path, value.asText(), shape.get("min").asLong())); + } else if (shape.has("max") && number.compareTo(BigDecimal.valueOf(shape.get("max").asLong())) > 0) { + found.add(form.valueTooLarge(path, value.asText(), shape.get("max").asLong())); + } + } + case "boolean" -> { + if (!value.isBoolean()) { + throw messages.type(errorPath, type); + } + } + case "list" -> collectList(shape, value, path, errorPath, form, found); + case "map" -> collectMap(shape, value, path, errorPath, form, found); + default -> throw unwordable(errorPath, path, type); + } + } + + private void collectInteger(JsonNode shape, String type, JsonNode value, String path, String errorPath, + SmithyValidationErrors.Violations form, List found) { + if (!value.isIntegralNumber()) { + throw messages.type(errorPath, type); + } + BigInteger number = value.bigIntegerValue(); + if (shape.has("min") && number.compareTo(BigInteger.valueOf(shape.get("min").asLong())) < 0) { + found.add(form.valueTooSmall(path, value.asText(), shape.get("min").asLong())); + } else if (shape.has("max") && number.compareTo(BigInteger.valueOf(shape.get("max").asLong())) > 0) { + found.add(form.valueTooLarge(path, value.asText(), shape.get("max").asLong())); + } else if (!("integer".equals(type) ? value.canConvertToInt() : value.canConvertToLong())) { + throw messages.type(errorPath, type); + } + } + + private void collectString(String name, JsonNode shape, String text, String path, + SmithyValidationErrors.Violations form, List found) { + String length = form.lengthOutOfRange(path, text, shape.path("min").asInt(0), + shape.has("max") ? shape.get("max").asInt() : Integer.MAX_VALUE); + if (length != null) { + found.add(length); + } + if (patternBroken(name, text)) { + found.add(form.pattern(path, text, VendoredPatterns.quoted(shape))); + } + if (shape.has("enum") && !inEnum(shape, text)) { + found.add(form.notInEnum(text, path, enumValues(shape))); + } + } + + private void collectList(JsonNode shape, JsonNode value, String path, String errorPath, + SmithyValidationErrors.Violations form, List found) { + if (!value.isArray()) { + throw messages.type(errorPath, "list"); + } + String listText = elementsText(value); + String size = sizeViolation(shape, value.size()); + if (size != null) { + found.add(form.constraint(path, listText, size)); + } + String memberName = shape.path("member").asText(); + boolean broken = false; + for (JsonNode item : value) { + broken |= item.isNull() || scalarBroken(memberName, item, errorPath + "[]"); + } + if (broken) { + found.add(form.constraint(path, listText, "Member must satisfy constraint: " + nullableRules(memberName))); + } + } + + private void collectMap(JsonNode shape, JsonNode value, String path, String errorPath, + SmithyValidationErrors.Violations form, List found) { + if (!value.isObject()) { + throw messages.type(errorPath, "map"); + } + List entries = new ArrayList<>(); + for (Map.Entry entry : value.properties()) { + entries.add(entry.getKey() + "=" + elementText(entry.getValue())); + } + String mapText = "{" + String.join(", ", entries) + "}"; + String size = sizeViolation(shape, value.size()); + if (size != null) { + found.add(form.constraint(path, mapText, size)); + } + String keyName = shape.path("key").asText(); + String valueName = shape.path("value").asText(); + boolean brokenKey = false; + boolean brokenValue = false; + for (Map.Entry entry : value.properties()) { + brokenKey |= scalarBroken(keyName, TextNode.valueOf(entry.getKey()), errorPath + ".key"); + brokenValue |= entry.getValue().isNull() + || scalarBroken(valueName, entry.getValue(), errorPath + "." + entry.getKey()); + } + if (brokenKey) { + found.add(form.mapKeys(path, mapText, rulesOf(keyName))); + } + if (brokenValue) { + found.add(form.mapValues(path, mapText, nullableRules(valueName))); + } + } + + /** Whether a non-null scalar breaks its shape's rules. A value of another JSON type is a type error. */ + private boolean scalarBroken(String name, JsonNode item, String errorPath) { + JsonNode shape = model.path("shapes").path(name); + String type = shape.path("type").asText(); + boolean fits = switch (type) { + case "string" -> item.isTextual(); + case "boolean" -> item.isBoolean(); + case "integer" -> item.isIntegralNumber() && item.canConvertToInt(); + case "long" -> item.isIntegralNumber() && item.canConvertToLong(); + default -> item.isNumber(); + }; + if (!fits) { + throw messages.type(errorPath, type); + } + if (!"string".equals(type)) { + return false; + } + String text = item.textValue(); + return lengthBroken(shape, text) || patternBroken(name, text) + || shape.has("enum") && !inEnum(shape, text); + } + + private static boolean lengthBroken(JsonNode shape, String text) { + int length = text.codePointCount(0, text.length()); + return shape.has("min") && length < shape.get("min").asInt() + || shape.has("max") && length > shape.get("max").asInt(); + } + + private boolean patternBroken(String name, String text) { + return patterns.containsKey(name) && !patterns.get(name).matcher(text).matches(); + } + + private static boolean inEnum(JsonNode shape, String text) { + for (JsonNode choice : shape.get("enum")) { + if (choice.asText().equals(text)) { + return true; + } + } + return false; + } + + private static List enumValues(JsonNode shape) { + List values = new ArrayList<>(); + shape.get("enum").forEach(choice -> values.add(choice.asText())); + return values; + } + + /** The rules a string shape declares, a minimum of zero included, in the order AWS lists them. */ + private List rulesOf(String name) { + JsonNode shape = model.path("shapes").path(name); + List rules = new ArrayList<>(); + if (shape.has("max")) { + rules.add("Member must have length less than or equal to " + shape.get("max").asLong()); + } + if (shape.has("min")) { + rules.add("Member must have length greater than or equal to " + shape.get("min").asLong()); + } + if (shape.has("pattern")) { + rules.add("Member must satisfy regular expression pattern: " + VendoredPatterns.quoted(shape)); + } + if (shape.has("enum")) { + rules.add("Member must satisfy enum value set: " + enumValues(shape)); + } + return rules; + } + + private List nullableRules(String name) { + List rules = rulesOf(name); + rules.add("Member must not be null"); + return rules; + } + + private static String sizeViolation(JsonNode shape, int size) { + if (shape.has("min") && size < shape.get("min").asLong()) { + return "Member must have length greater than or equal to " + shape.get("min").asLong(); + } + if (shape.has("max") && size > shape.get("max").asLong()) { + return "Member must have length less than or equal to " + shape.get("max").asLong(); + } + return null; + } + + private static String elementsText(JsonNode list) { + List texts = new ArrayList<>(); + list.forEach(item -> texts.add(elementText(item))); + return texts.toString(); + } + + private static String elementText(JsonNode item) { + return item.isNull() ? "null" : item.asText(); + } + + private static SmithyValidationErrors.Violations formOf(JsonNode shape) { + return shape.path("sensitive").asBoolean(false) + ? SmithyValidationErrors.Violations.WITHOUT_VALUES + : SmithyValidationErrors.Violations.QUOTED; + } + + private static String lowerFirst(String name) { + return Character.toLowerCase(name.charAt(0)) + name.substring(1); + } } diff --git a/src/main/resources/aws/eventbridgev2-request-shapes.json b/src/main/resources/aws/eventbridgev2-request-shapes.json new file mode 100644 index 0000000000..39b9b157f7 --- /dev/null +++ b/src/main/resources/aws/eventbridgev2-request-shapes.json @@ -0,0 +1,369 @@ +{ + "_source": { + "generator": "tools/aws/regen_eventbridgev2_shapes.py", + "botocore": "botocore 1.44.9 (installed package)" + }, + "operations": { + "CreateEventSource": "CreateEventSourceRequest", + "DeleteEventSource": "DeleteEventSourceRequest", + "DescribeEventSource": "DescribeEventSourceRequest", + "UpdateEventSource": "UpdateEventSourceRequest" + }, + "shapes": { + "AwsServiceEventsSourceConfiguration": { + "type": "structure", + "required": [ + "AwsService" + ], + "members": { + "AwsService": "AwsServiceSource", + "Pattern": "AwsServiceEventsSourceConfigurationPatternString", + "OnFailureConfiguration": "OnFailureConfiguration" + } + }, + "AwsServiceEventsSourceConfigurationPatternString": { + "type": "string", + "min": 0, + "max": 3753, + "sensitive": true + }, + "AwsServiceSource": { + "type": "string", + "min": 1, + "max": 256, + "pattern": "aws\\.[a-z0-9\\-]+" + }, + "ClientToken": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "[\\u0021-\\u007E]+" + }, + "CreateEventSourceRequest": { + "type": "structure", + "required": [ + "Name", + "EventBusArn", + "Configuration" + ], + "members": { + "Name": "EventSourceName", + "EventBusArn": "EventBusArn", + "Configuration": "EventSourceConfiguration", + "Description": "Description", + "Tags": "TagMap", + "ClientToken": "ClientToken" + } + }, + "DeadLetterQueueArn": { + "type": "string", + "min": 1, + "max": 1600, + "pattern": "arn:aws(-[a-z0-9]+)*:sqs:[a-z][a-z0-9]*(-[a-z0-9]+)*:[0-9]{12}:([A-Za-z0-9_-]{1,80}|[A-Za-z0-9_-]{1,75}\\.fifo)(?![\\s\\S]).*" + }, + "DeleteEventSourceRequest": { + "type": "structure", + "required": [ + "EventSourceArn" + ], + "members": { + "EventSourceArn": "EventSourceArn" + } + }, + "DescribeEventSourceRequest": { + "type": "structure", + "required": [ + "EventSourceArn" + ], + "members": { + "EventSourceArn": "EventSourceArn" + } + }, + "Description": { + "type": "string", + "min": 0, + "max": 512, + "pattern": "[^\\u0000-\\u001F\\u007F-\\u009F\\u2028\\u2029]*(?![\\s\\S]).*" + }, + "EventBusArn": { + "type": "string", + "min": 1, + "max": 1011, + "pattern": "arn:aws(-[a-z0-9]+)*:events:[a-z][a-z0-9]*(-[a-z0-9]+)*:([0-9]{12}):event-busv2\\/[A-Za-z0-9][\\.\\-_A-Za-z0-9]{0,255}\\/[a-z0-9]{25}" + }, + "EventSourceArn": { + "type": "string", + "min": 1, + "max": 1011, + "pattern": "arn:aws(-[a-z0-9]+)*:events:[a-z][a-z0-9]*(-[a-z0-9]+)*:([0-9]{12}):event-sourcev2\\/(aws\\.service|aws\\.partner|webhook)\\/[A-Za-z0-9][\\.\\-_A-Za-z0-9]{0,255}\\/[a-z0-9]{25}" + }, + "EventSourceConfiguration": { + "type": "structure", + "members": { + "AwsServiceEventsConfiguration": "AwsServiceEventsSourceConfiguration", + "PartnerEventsConfiguration": "PartnerEventsSourceConfiguration", + "WebhookEventsConfiguration": "WebhookEventsSourceConfiguration" + } + }, + "EventSourceName": { + "type": "string", + "min": 1, + "max": 256, + "pattern": "(?!aws\\.)[A-Za-z0-9][\\.\\-_A-Za-z0-9]*" + }, + "IncludePayload": { + "type": "string", + "enum": [ + "FULL", + "ON_ERROR_ONLY" + ] + }, + "KmsKeyIdentifier": { + "type": "string", + "min": 0, + "max": 2048, + "pattern": "[a-zA-Z0-9_\\-/:]*" + }, + "LogConfiguration": { + "type": "structure", + "members": { + "Level": "LogLevel", + "IncludePayload": "IncludePayload" + } + }, + "LogLevel": { + "type": "string", + "enum": [ + "ERROR", + "INFO", + "OFF" + ] + }, + "OnFailureConfiguration": { + "type": "structure", + "members": { + "Arn": "DeadLetterQueueArn" + } + }, + "PartnerEventSourceArn": { + "type": "string", + "min": 1, + "max": 1600, + "pattern": "arn:aws(-[a-z0-9]+)*:events:[a-z][a-z0-9]*(-[a-z0-9]+)*:([0-9]{12})?:event-source\\/aws\\.partner(\\/[\\.\\-_A-Za-z0-9]+){2,}" + }, + "PartnerEventsSourceConfiguration": { + "type": "structure", + "required": [ + "PartnerEventSourceArn" + ], + "members": { + "PartnerEventSourceArn": "PartnerEventSourceArn", + "Pattern": "PartnerEventsSourceConfigurationPatternString", + "PartnerBusKmsKeyIdentifier": "KmsKeyIdentifier", + "OnFailureConfiguration": "OnFailureConfiguration" + } + }, + "PartnerEventsSourceConfigurationPatternString": { + "type": "string", + "min": 0, + "max": 3753, + "sensitive": true + }, + "RoleArn": { + "type": "string", + "min": 1, + "max": 1600, + "pattern": "arn:aws(-[a-z0-9]+)*:iam::\\d{12}:role\\/[\\w+=,.@/-]+" + }, + "TagKey": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "\\S([\\s\\S]*\\S)?(?![\\s\\S]).*" + }, + "TagMap": { + "type": "map", + "min": 0, + "max": 200, + "key": "TagKey", + "value": "TagValue" + }, + "TagValue": { + "type": "string", + "min": 0, + "max": 256, + "pattern": "(\\S([\\s\\S]*\\S)?)?(?![\\s\\S]).*" + }, + "UpdateEventSourceRequest": { + "type": "structure", + "required": [ + "EventSourceArn" + ], + "members": { + "EventSourceArn": "EventSourceArn", + "Configuration": "EventSourceConfiguration", + "Description": "Description" + } + }, + "WebhookAuthConfiguration": { + "type": "structure", + "members": { + "StaticTokenAuthConfiguration": "WebhookStaticTokenAuthConfiguration", + "BasicHttpAuthConfiguration": "WebhookBasicHttpAuthConfiguration", + "HmacAuthConfiguration": "WebhookHmacAuthConfiguration" + } + }, + "WebhookBasicHttpAuthConfiguration": { + "type": "structure", + "members": { + "Username": "WebhookUsername", + "Password": "WebhookSecretValue" + } + }, + "WebhookDeduplicationConfiguration": { + "type": "structure", + "required": [ + "DeduplicationType" + ], + "members": { + "DeduplicationType": "WebhookDeduplicationType" + } + }, + "WebhookDeduplicationType": { + "type": "string", + "enum": [ + "CONTENT_BASED" + ] + }, + "WebhookDelimiter": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "[\\u0020-\\u007E]+" + }, + "WebhookEventsSourceConfiguration": { + "type": "structure", + "required": [ + "AuthConfiguration", + "RoleArn" + ], + "members": { + "AuthConfiguration": "WebhookAuthConfiguration", + "KmsKeyIdentifier": "KmsKeyIdentifier", + "RoleArn": "RoleArn", + "MetadataHttpHeaders": "WebhookMetadataHttpHeaderList", + "DeduplicationConfiguration": "WebhookDeduplicationConfiguration", + "LogConfiguration": "LogConfiguration" + } + }, + "WebhookHeaderName": { + "type": "string", + "min": 1, + "max": 512, + "pattern": "[!#$%&'*+\\-.^_`|~0-9A-Za-z]+" + }, + "WebhookHmacAlgorithm": { + "type": "string", + "enum": [ + "SHA1", + "SHA256" + ] + }, + "WebhookHmacAuthConfiguration": { + "type": "structure", + "required": [ + "Algorithm", + "Encoding", + "SignatureHttpHeader", + "SignedMessageComposition" + ], + "members": { + "Algorithm": "WebhookHmacAlgorithm", + "Encoding": "WebhookHmacEncoding", + "SignatureHttpHeader": "WebhookHeaderName", + "SignaturePrefix": "WebhookSignaturePrefix", + "Delimiter": "WebhookDelimiter", + "TimestampHttpHeader": "WebhookHeaderName", + "TimestampPrefix": "WebhookTimestampPrefix", + "TimestampToleranceInSeconds": "WebhookTimestampToleranceInSeconds", + "MessageIdHttpHeader": "WebhookHeaderName", + "SignedMessageComposition": "WebhookSignedMessageComposition", + "SecretValue": "WebhookSecretValue", + "SecretEncoding": "WebhookSecretEncoding" + } + }, + "WebhookHmacEncoding": { + "type": "string", + "enum": [ + "BASE64", + "HEX" + ] + }, + "WebhookMetadataHttpHeaderList": { + "type": "list", + "min": 0, + "max": 20, + "member": "WebhookMetadataHttpHeaderName" + }, + "WebhookMetadataHttpHeaderName": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "[!#$%&'*+\\-.^_`|~0-9A-Za-z]+" + }, + "WebhookSecretEncoding": { + "type": "string", + "enum": [ + "BASE64", + "RAW" + ] + }, + "WebhookSecretValue": { + "type": "string", + "min": 6, + "max": 512, + "sensitive": true + }, + "WebhookSignaturePrefix": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "[\\u0020-\\u007E]+" + }, + "WebhookSignedMessageComposition": { + "type": "string", + "enum": [ + "BODY", + "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY", + "TIMESTAMP_DOT_BODY" + ] + }, + "WebhookStaticTokenAuthConfiguration": { + "type": "structure", + "required": [ + "TokenHttpHeader" + ], + "members": { + "TokenHttpHeader": "WebhookHeaderName", + "SecretValue": "WebhookSecretValue" + } + }, + "WebhookTimestampPrefix": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "[\\u0020-\\u007E]+" + }, + "WebhookTimestampToleranceInSeconds": { + "type": "integer", + "min": 1, + "max": 900 + }, + "WebhookUsername": { + "type": "string", + "min": 1, + "max": 512, + "pattern": "[^:\\s]+" + } + } +} diff --git a/src/test/java/io/floci/aws/core/common/RequestConstraintCheckViolationsTest.java b/src/test/java/io/floci/aws/core/common/RequestConstraintCheckViolationsTest.java new file mode 100644 index 0000000000..a16ee95ccf --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/RequestConstraintCheckViolationsTest.java @@ -0,0 +1,351 @@ +package io.floci.aws.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** The collecting walk: every violation at once, worded as Smithy words them. */ +class RequestConstraintCheckViolationsTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static final String MODEL = """ + {"operations": {"Put": "PutInput", "Blobby": "BlobbyInput", "Listy": "ListyInput", "Mappy": "MappyInput", + "Loop": "LoopInput", "Bounded": "BoundedInput"}, + "shapes": { + "PutInput": {"type": "structure", "required": ["Name", "Inner"], + "members": {"Name": "Name", "Inner": "Inner", "Kind": "Kind", "Count": "Count", + "Ratio": "Ratio", "Flag": "Flag", "Secret": "Secret", "Wide": "Wide", + "Tags": "Tags", "Names": "Names", "Pairs": "Pairs"}}, + "Inner": {"type": "structure", "required": ["Leaf"], "members": {"Leaf": "Name", "Other": "Name"}}, + "Name": {"type": "string", "min": 2, "max": 5, "pattern": "[a-z]+"}, + "Kind": {"type": "string", "enum": ["B", "A"]}, + "Count": {"type": "integer", "min": 1, "max": 900}, + "Wide": {"type": "long", "min": 1}, + "Ratio": {"type": "double", "min": 0, "max": 1}, + "Flag": {"type": "boolean"}, + "Secret": {"type": "string", "min": 6, "sensitive": true}, + "Tags": {"type": "map", "min": 0, "max": 2, "key": "TagKey", "value": "TagValue"}, + "TagKey": {"type": "string", "min": 1, "max": 3, "pattern": "[a-z]+"}, + "TagValue": {"type": "string", "min": 0, "max": 4, "pattern": "[a-z]*"}, + "Names": {"type": "list", "min": 1, "max": 2, "member": "Name"}, + "Pairs": {"type": "list", "member": "Flag"}, + "Longs": {"type": "list", "member": "Wide"}, + "BoundedInput": {"type": "structure", "members": {"Longs": "Longs"}}, + "BlobbyInput": {"type": "structure", "members": {"Data": "Data"}}, + "Data": {"type": "blob"}, + "ListyInput": {"type": "structure", "members": {"Items": "Items"}}, + "Items": {"type": "list", "member": "Inner"}, + "MappyInput": {"type": "structure", "members": {"Marks": "Marks"}}, + "Marks": {"type": "map", "key": "Name", "value": "Inner"}, + "LoopInput": {"type": "structure", "members": {"Self": "LoopInput", "Name": "Name"}} + }} + """; + + private static final RequestConstraintCheck CHECK = RequestConstraintCheck.of(json(MODEL), + RequestConstraintCheck.standardMessages("InvalidInputException")); + + private static final String REQUIRED_OK = "\"Name\": \"abc\", \"Inner\": {\"Leaf\": \"abc\"}"; + + @Test + void emptyRequestReportsEveryRequiredMemberInModelOrder() { + assertEquals(List.of( + "Value null at 'name' failed to satisfy constraint: Member must not be null", + "Value null at 'inner' failed to satisfy constraint: Member must not be null"), + CHECK.violations("Put", json("{}"))); + } + + @Test + void nullAndMissingRequestsAreEmptyStructures() { + List expected = CHECK.violations("Put", json("{}")); + + assertEquals(expected, CHECK.violations("Put", null)); + assertEquals(expected, CHECK.violations("Put", json("null"))); + } + + @Test + void jsonNullMemberIsAbsentAndUnknownMembersAreIgnored() { + assertEquals(List.of("Value null at 'inner' failed to satisfy constraint: Member must not be null"), + CHECK.violations("Put", json("{\"Name\": \"abc\", \"Inner\": null, \"Kind\": null, \"Extra\": 1}"))); + } + + @Test + void nestedMemberPathLowerCasesEachFirstLetter() { + assertEquals(List.of( + "Value null at 'inner.leaf' failed to satisfy constraint: Member must not be null"), + CHECK.violations("Put", json("{\"Name\": \"abc\", \"Inner\": {}}"))); + } + + @Test + void stringReportsLengthThenPatternThenEnumEachIndependently() { + assertEquals(List.of( + "Value 'A' at 'name' failed to satisfy constraint: Member must have length greater than or equal to 2", + "Value 'A' at 'name' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-z]+"), + CHECK.violations("Put", json("{\"Name\": \"A\", \"Inner\": {\"Leaf\": \"abc\"}}"))); + assertEquals(List.of( + "Value 'abcdef' at 'name' failed to satisfy constraint: Member must have length less than or equal to 5"), + CHECK.violations("Put", json("{\"Name\": \"abcdef\", \"Inner\": {\"Leaf\": \"abc\"}}"))); + } + + @Test + void stringLengthCountsCodePoints() { + String sixEmoji = "\\ud83d\\ude00".repeat(6); + + assertEquals(List.of(), CHECK.violations("Put", + json("{" + REQUIRED_OK + ", \"Secret\": \"" + sixEmoji + "\"}"))); + } + + @Test + void enumValuesKeepTheVendoredOrder() { + assertEquals(List.of( + "Value 'C' at 'kind' failed to satisfy constraint: Member must satisfy enum value set: [B, A]"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Kind\": \"C\"}"))); + } + + @Test + void sensitiveStringLeavesItsValueOut() { + assertEquals(List.of( + "Value at 'secret' failed to satisfy constraint: Member must have length greater than or equal to 6"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Secret\": \"abc\"}"))); + } + + @Test + void integerAboveMaxAndBelowMinAreRangeViolations() { + assertEquals(List.of("Value '901' at 'count' failed to satisfy constraint: " + + "Member must have value less than or equal to 900"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Count\": 901}"))); + assertEquals(List.of("Value '0' at 'count' failed to satisfy constraint: " + + "Member must have value greater than or equal to 1"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Count\": 0}"))); + } + + @Test + void integerTooBigForLongIsStillARangeViolation() { + assertEquals(List.of("Value '99999999999999999999' at 'count' failed to satisfy constraint: " + + "Member must have value less than or equal to 900"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Count\": 99999999999999999999}"))); + } + + @Test + void integerWithoutDeclaredBoundThatDoesNotFitTheTypeIsATypeError() { + AwsException error = assertThrows(AwsException.class, + () -> CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Wide\": 99999999999999999999}"))); + + assertEquals("Invalid parameter at 'Wide' failed to satisfy constraint: 'Member must be a long'", + error.getMessage()); + } + + @Test + void fractionalNumberWhereIntegerIsModeledIsATypeError() { + AwsException error = assertThrows(AwsException.class, + () -> CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Count\": 1.5}"))); + + assertEquals("Invalid parameter at 'Count' failed to satisfy constraint: 'Member must be a integer'", + error.getMessage()); + } + + @Test + void doubleUsesTheNumbersTextAgainstItsBounds() { + assertEquals(List.of("Value '1.5' at 'ratio' failed to satisfy constraint: " + + "Member must have value less than or equal to 1"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Ratio\": 1.5}"))); + assertEquals(List.of("Value '-0.5' at 'ratio' failed to satisfy constraint: " + + "Member must have value greater than or equal to 0"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Ratio\": -0.5}"))); + } + + @Test + void booleanChecksTheTypeOnly() { + assertEquals(List.of(), CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Flag\": false}"))); + AwsException error = assertThrows(AwsException.class, + () -> CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Flag\": \"yes\"}"))); + + assertEquals("Invalid parameter at 'Flag' failed to satisfy constraint: 'Member must be a boolean'", + error.getMessage()); + } + + @Test + void wrongTypeThrowsAtOnceWithTheModelSpelledPath() { + AwsException structure = assertThrows(AwsException.class, + () -> CHECK.violations("Put", json("{\"Name\": \"abc\", \"Inner\": \"x\"}"))); + AwsException element = assertThrows(AwsException.class, + () -> CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Names\": [\"abc\", 3]}"))); + AwsException root = assertThrows(AwsException.class, () -> CHECK.violations("Put", json("[]"))); + + assertEquals("Invalid parameter at 'Inner' failed to satisfy constraint: 'Member must be a structure'", + structure.getMessage()); + assertEquals("Invalid parameter at 'Names' failed to satisfy constraint: 'Member must be a string'", + element.getMessage()); + assertEquals("Invalid parameter at '' failed to satisfy constraint: 'Member must be a structure'", + root.getMessage()); + } + + @Test + void listSizeViolationQuotesTheWholeListAndDropsNullAsText() { + assertEquals(List.of("Value '[abc, abc, null]' at 'names' failed to satisfy constraint: " + + "Member must have length less than or equal to 2", + "Value '[abc, abc, null]' at 'names' failed to satisfy constraint: " + + "Member must satisfy constraint: [Member must have length less than or equal to 5, " + + "Member must have length greater than or equal to 2, " + + "Member must satisfy regular expression pattern: [a-z]+, Member must not be null]"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Names\": [\"abc\", \"abc\", null]}"))); + } + + @Test + void listBelowItsMinimumSizeIsReported() { + assertEquals(List.of("Value '[]' at 'names' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Names\": []}"))); + } + + @Test + void listMemberBreakingItsShapeIsOneViolationForTheWholeList() { + assertEquals(List.of("Value '[ok, B]' at 'names' failed to satisfy constraint: " + + "Member must satisfy constraint: [Member must have length less than or equal to 5, " + + "Member must have length greater than or equal to 2, " + + "Member must satisfy regular expression pattern: [a-z]+, Member must not be null]"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Names\": [\"ok\", \"B\"]}"))); + } + + @Test + void listOfBooleansWithANullMemberHasOnlyTheNullRule() { + assertEquals(List.of("Value '[true, null]' at 'pairs' failed to satisfy constraint: " + + "Member must satisfy constraint: [Member must not be null]"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Pairs\": [true, null]}"))); + } + + @Test + void mapSizeViolationQuotesTheWholeMapInRequestOrder() { + assertEquals(List.of("Value '{b=x, a=y, c=z}' at 'tags' failed to satisfy constraint: " + + "Member must have length less than or equal to 2"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Tags\": {\"b\": \"x\", \"a\": \"y\", \"c\": \"z\"}}"))); + } + + @Test + void mapKeyThenValueViolationsAreOneEachAndOnlyValuesCarryNotNull() { + assertEquals(List.of( + "Value '{ k= v}' at 'tags' failed to satisfy constraint: Map keys must satisfy constraint: " + + "[Member must have length less than or equal to 3, " + + "Member must have length greater than or equal to 1, " + + "Member must satisfy regular expression pattern: [a-z]+]", + "Value '{ k= v}' at 'tags' failed to satisfy constraint: Map value must satisfy constraint: " + + "[Member must have length less than or equal to 4, " + + "Member must have length greater than or equal to 0, " + + "Member must satisfy regular expression pattern: [a-z]*, Member must not be null]"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Tags\": {\" k\": \" v\"}}"))); + } + + @Test + void mapValueThatIsNullIsAValueViolation() { + assertEquals(List.of( + "Value '{k=null}' at 'tags' failed to satisfy constraint: Map value must satisfy constraint: " + + "[Member must have length less than or equal to 4, " + + "Member must have length greater than or equal to 0, " + + "Member must satisfy regular expression pattern: [a-z]*, Member must not be null]"), + CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Tags\": {\"k\": null}}"))); + } + + @Test + void mapValueOfTheWrongTypeThrowsWithTheKeyInThePath() { + AwsException error = assertThrows(AwsException.class, + () -> CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Tags\": {\"k\": 1}}"))); + + assertEquals("Invalid parameter at 'Tags.k' failed to satisfy constraint: 'Member must be a string'", + error.getMessage()); + } + + @Test + void everyViolationIsCollectedInMemberOrder() { + List found = CHECK.violations("Put", + json("{\"Name\": \"A\", \"Kind\": \"C\", \"Count\": 0, \"Secret\": \"x\"}")); + + assertEquals(List.of( + "Value 'A' at 'name' failed to satisfy constraint: Member must have length greater than or equal to 2", + "Value 'A' at 'name' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-z]+", + "Value null at 'inner' failed to satisfy constraint: Member must not be null", + "Value 'C' at 'kind' failed to satisfy constraint: Member must satisfy enum value set: [B, A]", + "Value '0' at 'count' failed to satisfy constraint: Member must have value greater than or equal to 1", + "Value at 'secret' failed to satisfy constraint: Member must have length greater than or equal to 6"), + found); + } + + @Test + void unknownOperationIsRefused() { + assertThrows(IllegalArgumentException.class, () -> CHECK.violations("Nope", json("{}"))); + } + + @Test + void operationHoldingABlobIsRefusedNamingTheMember() { + IllegalStateException error = assertThrows(IllegalStateException.class, + () -> CHECK.violations("Blobby", json("{}"))); + + assertEquals("Blobby's Data is a blob, which this check does not word yet", error.getMessage()); + } + + @Test + void listOfStructuresIsRefused() { + IllegalStateException error = assertThrows(IllegalStateException.class, + () -> CHECK.violations("Listy", json("{}"))); + + assertEquals("Listy's Items[] is a structure, which this check does not word yet", error.getMessage()); + } + + @Test + void mapWithStructureValuesIsRefused() { + IllegalStateException error = assertThrows(IllegalStateException.class, + () -> CHECK.violations("Mappy", json("{}"))); + + assertEquals("Mappy's Marks.value is a structure, which this check does not word yet", error.getMessage()); + } + + @Test + void listOfBoundedNumbersIsRefused() { + IllegalStateException error = assertThrows(IllegalStateException.class, + () -> CHECK.violations("Bounded", json("{}"))); + assertEquals("Bounded's Longs[] is a long, which this check does not word yet", error.getMessage()); + } + + @Test + void listOrMapHoldingASensitiveStringIsRefused() { + RequestConstraintCheck check = RequestConstraintCheck.of(json(""" + {"operations": {"Listy": "ListyInput", "Mappy": "MappyInput"}, + "shapes": { + "ListyInput": {"type": "structure", "members": {"Tokens": "Tokens"}}, + "Tokens": {"type": "list", "member": "Token"}, + "MappyInput": {"type": "structure", "members": {"Marks": "Marks"}}, + "Marks": {"type": "map", "key": "Plain", "value": "Token"}, + "Plain": {"type": "string"}, + "Token": {"type": "string", "sensitive": true}}} + """), RequestConstraintCheck.standardMessages("InvalidInputException")); + + assertEquals("Listy's Tokens[] is a sensitive string, which this check does not word yet", + assertThrows(IllegalStateException.class, () -> check.violations("Listy", json("{}"))).getMessage()); + assertEquals("Mappy's Marks.value is a sensitive string, which this check does not word yet", + assertThrows(IllegalStateException.class, () -> check.violations("Mappy", json("{}"))).getMessage()); + } + + @Test + void shapeHoldingItselfIsWalkedOnce() { + assertEquals(List.of(), CHECK.violations("Loop", + json("{\"Name\": \"abc\", \"Self\": {\"Name\": \"abc\", \"Self\": {}}}"))); + } + + @Test + void refusalDoesNotAffectCheckOrOtherOperations() { + CHECK.check("Blobby", json("{}")); + assertEquals(List.of(), CHECK.violations("Put", json("{" + REQUIRED_OK + "}"))); + } + + private static JsonNode json(String text) { + try { + return MAPPER.readTree(text); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapesTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapesTest.java new file mode 100644 index 0000000000..ff300e604e --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapesTest.java @@ -0,0 +1,192 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.RequestConstraintCheck; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** The measured AWS answers for CreateEventSource, read through the vendored request shapes. */ +class EventBridgeV2RequestShapesTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load( + "aws/eventbridgev2-request-shapes.json", "EventBridge V2 request shapes", + RequestConstraintCheck.standardMessages("InvalidInputException")); + + private static final String WEBHOOK = "configuration.webhookEventsConfiguration"; + + @Test + void emptyRequestNamesEveryRequiredMember() { + assertEquals(List.of( + "Value null at 'name' failed to satisfy constraint: Member must not be null", + "Value null at 'eventBusArn' failed to satisfy constraint: Member must not be null", + "Value null at 'configuration' failed to satisfy constraint: Member must not be null"), + CHECK.violations("CreateEventSource", MAPPER.createObjectNode())); + } + + @Test + void descriptionWithAControlCharacterBreaksItsPattern() { + ObjectNode request = validRequest(); + request.put("Description", "a\u0001b"); + + assertEquals(List.of("Value 'a\u0001b' at 'description' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: " + + "[^\\u0000-\\u001F\\u007F-\\u009F\\u2028\\u2029]*(?![\\s\\S]).*"), + CHECK.violations("CreateEventSource", request)); + } + + @Test + void tagsBreakingTheirKeyAndValueShapesAreTwoViolations() { + ObjectNode request = validRequest(); + request.putObject("Tags").put(" k", " v"); + + assertEquals(List.of( + "Value '{ k= v}' at 'tags' failed to satisfy constraint: Map keys must satisfy constraint: " + + "[Member must have length less than or equal to 128, " + + "Member must have length greater than or equal to 1, " + + "Member must satisfy regular expression pattern: \\S([\\s\\S]*\\S)?(?![\\s\\S]).*]", + "Value '{ k= v}' at 'tags' failed to satisfy constraint: Map value must satisfy constraint: " + + "[Member must have length less than or equal to 256, " + + "Member must have length greater than or equal to 0, " + + "Member must satisfy regular expression pattern: (\\S([\\s\\S]*\\S)?)?(?![\\s\\S]).*, " + + "Member must not be null]"), + CHECK.violations("CreateEventSource", request)); + } + + @Test + void moreThanTwoHundredTagsIsOneSizeViolation() { + ObjectNode request = validRequest(); + ObjectNode tags = request.putObject("Tags"); + for (int i = 0; i < 201; i++) { + tags.put("k" + i, "v"); + } + + List found = CHECK.violations("CreateEventSource", request); + + assertEquals(1, found.size()); + assertTrue(found.get(0).endsWith("' at 'tags' failed to satisfy constraint: " + + "Member must have length less than or equal to 200"), found.get(0)); + } + + @Test + void logLevelOutsideItsEnumListsTheValuesSorted() { + ObjectNode request = validRequest(); + webhook(request).putObject("LogConfiguration").put("Level", "DEBUG"); + + assertEquals(List.of("Value 'DEBUG' at '" + WEBHOOK + ".logConfiguration.level' failed to satisfy " + + "constraint: Member must satisfy enum value set: [ERROR, INFO, OFF]"), + CHECK.violations("CreateEventSource", request)); + } + + @Test + void shortSecretLeavesItsValueOut() { + ObjectNode request = validRequest(); + ObjectNode token = auth(request).putObject("StaticTokenAuthConfiguration"); + token.put("TokenHttpHeader", "x-token"); + token.put("SecretValue", "abc"); + + assertEquals(List.of("Value at '" + WEBHOOK + ".authConfiguration.staticTokenAuthConfiguration.secretValue' " + + "failed to satisfy constraint: Member must have length greater than or equal to 6"), + CHECK.violations("CreateEventSource", request)); + } + + @Test + void metadataHeaderBreakingItsShapeIsOneViolationForTheList() { + ObjectNode request = validRequest(); + webhook(request).set("MetadataHttpHeaders", strings("ok", "bad header")); + + assertEquals(List.of("Value '[ok, bad header]' at '" + WEBHOOK + ".metadataHttpHeaders' failed to satisfy " + + "constraint: Member must satisfy constraint: [Member must have length less than or equal to 128, " + + "Member must have length greater than or equal to 1, " + + "Member must satisfy regular expression pattern: [!#$%&'*+\\-.^_`|~0-9A-Za-z]+, " + + "Member must not be null]"), + CHECK.violations("CreateEventSource", request)); + } + + @Test + void twentyOneMetadataHeadersAreOneSizeViolation() { + ObjectNode request = validRequest(); + String[] names = new String[21]; + for (int i = 0; i < names.length; i++) { + names[i] = "h" + (i + 1); + } + webhook(request).set("MetadataHttpHeaders", strings(names)); + + assertEquals(List.of("Value '[" + String.join(", ", names) + "]' at '" + WEBHOOK + + ".metadataHttpHeaders' failed to satisfy constraint: Member must have length less than or equal to 20"), + CHECK.violations("CreateEventSource", request)); + } + + @Test + void timestampToleranceOutsideItsRangeIsReportedWithItsValue() { + String path = WEBHOOK + ".authConfiguration.hmacAuthConfiguration.timestampToleranceInSeconds"; + for (int value : new int[] {901, 0}) { + ObjectNode request = validRequest(); + ObjectNode hmac = auth(request).putObject("HmacAuthConfiguration"); + hmac.put("Algorithm", "SHA256"); + hmac.put("Encoding", "HEX"); + hmac.put("SignatureHttpHeader", "x-signature"); + hmac.put("SignedMessageComposition", "BODY"); + hmac.put("TimestampToleranceInSeconds", value); + + String bound = value > 900 + ? "less than or equal to 900" + : "greater than or equal to 1"; + assertEquals(List.of("Value '" + value + "' at '" + path + "' failed to satisfy constraint: " + + "Member must have value " + bound), CHECK.violations("CreateEventSource", request)); + } + } + + @Test + void longNameStartingWithASpaceBreaksLengthThenPattern() { + ObjectNode request = validRequest(); + String name = " " + "a".repeat(256); + request.put("Name", name); + + assertEquals(List.of( + "Value '" + name + "' at 'name' failed to satisfy constraint: " + + "Member must have length less than or equal to 256", + "Value '" + name + "' at 'name' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: (?!aws\\.)[A-Za-z0-9][\\.\\-_A-Za-z0-9]*"), + CHECK.violations("CreateEventSource", request)); + } + + @Test + void validRequestHasNoViolations() { + assertEquals(List.of(), CHECK.violations("CreateEventSource", validRequest())); + } + + private static ObjectNode validRequest() { + ObjectNode request = MAPPER.createObjectNode(); + request.put("Name", "source"); + request.put("EventBusArn", "arn:aws:events:us-east-1:123456789012:event-busv2/bus/abcdefghijklmnopqrstuvwxy"); + ObjectNode webhook = request.putObject("Configuration").putObject("WebhookEventsConfiguration"); + webhook.put("RoleArn", "arn:aws:iam::123456789012:role/role"); + webhook.putObject("AuthConfiguration"); + return request; + } + + private static ObjectNode webhook(ObjectNode request) { + return (ObjectNode) request.path("Configuration").path("WebhookEventsConfiguration"); + } + + private static ObjectNode auth(ObjectNode request) { + return (ObjectNode) webhook(request).path("AuthConfiguration"); + } + + private static JsonNode strings(String... values) { + ArrayNode array = MAPPER.createArrayNode(); + for (String value : values) { + array.add(value); + } + return array; + } +} diff --git a/tools/aws/regen_eventbridgev2_shapes.py b/tools/aws/regen_eventbridgev2_shapes.py new file mode 100644 index 0000000000..b78c37acc6 --- /dev/null +++ b/tools/aws/regen_eventbridgev2_shapes.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Vendor the EventBridge V2 event source operations' request constraints for RequestConstraintCheck. + +The shapes the model marks `sensitive` keep that mark, so a violation does not quote their value. +""" +from __future__ import annotations + +from pathlib import Path + +import request_shapes + +MODEL = Path("eventbridgev2/2025-05-15") +OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/eventbridgev2-request-shapes.json" + +OPERATIONS = ("CreateEventSource", "DeleteEventSource", "DescribeEventSource", "UpdateEventSource") + + +def sort_enums(model: dict) -> dict: + """The model, with every enum's values sorted. + + AWS lists the values of a violated enum sorted for this service. `LogLevel` is `[OFF, ERROR, INFO]` + in the model and `[ERROR, INFO, OFF]` in the message. + """ + for shape in model["shapes"].values(): + if "enum" in shape: + shape["enum"] = sorted(shape["enum"]) + return model + + +def main(argv: list[str] | None = None) -> int: + return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, + description=__doc__, operations=OPERATIONS, sensitive=True, + prepare=sort_enums) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/aws/request_shapes.py b/tools/aws/request_shapes.py index 013098ba5c..bd5493100a 100644 --- a/tools/aws/request_shapes.py +++ b/tools/aws/request_shapes.py @@ -120,11 +120,13 @@ def build(model: dict, provenance: str, generator: str, outputs: bool = False, r return document -def build_constraints(model: dict, operations: tuple[str, ...], provenance: str, generator: str) -> dict: +def build_constraints(model: dict, operations: tuple[str, ...], provenance: str, generator: str, + sensitive: bool = False) -> dict: """The input shapes of `operations` with the constraints `RequestConstraintCheck` reads: for every shape reachable from one, its type, required members, min, max, pattern, the pattern a violation quotes where that is not the one matched on, and enum, and the shapes of its members, list - elements or map keys and values. Unlike `build`, it keeps members bound to + elements or map keys and values. `sensitive` marks the shapes the model marks `sensitive`. + Unlike `build`, it keeps members bound to the URI, query string or headers, so it suits the JSON protocols, whose members all travel in the body.""" kept: dict[str, dict] = {} @@ -135,6 +137,8 @@ def build_constraints(model: dict, operations: tuple[str, ...], provenance: str, shape = model["shapes"][name] entry = {k: shape[k] for k in ("type", "required", "min", "max", "pattern", "quotedPattern", "enum") if k in shape} + if sensitive and shape.get("sensitive"): + entry["sensitive"] = True kept[name] = entry if shape["type"] == "structure": entry["members"] = {k: v["shape"] for k, v in shape.get("members", {}).items()} @@ -229,8 +233,8 @@ def main(argv: list[str] | None, *, script: str, model: Path, output: Path, it vendors in part: IAM reduces a paged request to its paging members, the rest of it keeping the reading it has today. - `results`, `sensitive`, `errors` and `check` are `build`'s, for a generator that keeps every - operation's member types.""" + `results`, `errors` and `check` are `build`'s, for a generator that keeps every + operation's member types. `sensitive` is `build`'s and `build_constraints`'s.""" parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation") parser.add_argument("--botocore-data", type=Path, help="botocore data directory") @@ -244,7 +248,8 @@ def main(argv: list[str] | None, *, script: str, model: Path, output: Path, if constraints and operations is None: operations = tuple(name for name, operation in sorted(loaded["operations"].items()) if "input" in operation) generator = generator_name(script) - fresh = render(build_constraints(loaded, operations, provenance, generator) if operations is not None + fresh = render(build_constraints(loaded, operations, provenance, generator, sensitive=sensitive) + if operations is not None else build(loaded, provenance, generator, outputs, required, results=results, sensitive=sensitive, errors=errors, check=check)) diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py index eb112f8bdf..b192ba1619 100644 --- a/tools/aws/test_request_shapes.py +++ b/tools/aws/test_request_shapes.py @@ -28,6 +28,7 @@ import regen_ecr_shapes import regen_ecs_shapes import regen_eks_shapes import regen_emr_containers_shapes +import regen_eventbridgev2_shapes import regen_emr_serverless_shapes import regen_iam_shapes import regen_cloudfront_keyvaluestore_shapes @@ -319,6 +320,18 @@ def test_build_constraints_keeps_the_named_operations_with_their_constraints(): assert doc["shapes"]["TagMap"] == {"type": "map", "key": "Name", "value": "Kind"} +def test_build_constraints_keeps_the_sensitive_mark_only_when_asked(): + model = deepcopy(CONSTRAINED_MODEL) + model["shapes"]["Name"]["sensitive"] = True + + asked = r.build_constraints(model, ("Put",), "botocore test", "tools/aws/regen_x_shapes.py", sensitive=True) + default = r.build_constraints(model, ("Put",), "botocore test", "tools/aws/regen_x_shapes.py") + + assert asked["shapes"]["Name"] == {"type": "string", "min": 1, "max": 5, "pattern": "[a-z]+", "sensitive": True} + assert "sensitive" not in default["shapes"]["Name"] + assert "sensitive" not in asked["shapes"]["Kind"] + + def test_build_constraints_refuses_an_operation_the_model_does_not_name(): # A misspelled name in a generator's OPERATIONS fails the generation rather than vendoring a # file quietly missing that operation, which --check would then call up to date. @@ -459,6 +472,7 @@ def vendored(script) -> tuple[str, ...]: regen_emr_containers_shapes, regen_lambda_microvm_shapes, regen_account_shapes, + regen_eventbridgev2_shapes, ]) def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_shapes(script): doc = json.loads(script.OUTPUT.read_text(encoding="utf-8")) @@ -574,6 +588,18 @@ def test_kinesis_shapes_keep_tag_bounds_and_leave_wire_types_to_handlers(): assert "Timestamp" not in shapes["GetShardIteratorInput"]["members"] +def test_eventbridgev2_shapes_keep_sorted_enums_and_the_sensitive_mark(): + doc = json.loads(regen_eventbridgev2_shapes.OUTPUT.read_text(encoding="utf-8")) + shapes = doc["shapes"] + + assert sorted(doc["operations"]) == ["CreateEventSource", "DeleteEventSource", "DescribeEventSource", + "UpdateEventSource"] + assert shapes["WebhookSecretValue"] == {"type": "string", "min": 6, "max": 512, "sensitive": True} + assert shapes["LogLevel"]["enum"] == ["ERROR", "INFO", "OFF"] + assert shapes["WebhookMetadataHttpHeaderList"]["max"] == 20 + assert shapes["TagMap"]["max"] == 200 + + def test_config_shapes_keep_arn_bounds_and_leave_timestamps_to_handlers(): doc = json.loads(regen_config_shapes.OUTPUT.read_text(encoding="utf-8")) shapes = doc["shapes"]