diff --git a/README.md b/README.md index 0c6cba6af3..253e5f7ee4 100644 --- a/README.md +++ b/README.md @@ -334,7 +334,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | SWF | In-process | Decision and activity tasks, timers, child workflows, timeouts, real Lambda invocation | | CloudFormation | In-process | Stacks, change sets, resource provisioning, StackSets (cross-account instances) | | EventBridge | In-process | Custom buses, rules, SQS, SNS and Lambda targets | -| EventBridge V2 | In-process | Event buses and filtered subscribers delivering to SQS | +| EventBridge V2 | In-process | Event buses, filtered subscribers delivering to SQS, and webhook event sources | | EventBridge Pipes | In-process | Poller-based integration connecting SQS, Kinesis, DynamoDB, and MSK sources to targets with optional filtering | | EventBridge Scheduler | In-process | Schedule groups, schedules, flexible time windows, retry policies, DLQs | | CloudWatch Logs | In-process | Log groups, streams, ingestion, filtering | diff --git a/docs/services/eventbridgev2.md b/docs/services/eventbridgev2.md index afdea75909..cdb8370663 100644 --- a/docs/services/eventbridgev2.md +++ b/docs/services/eventbridgev2.md @@ -18,13 +18,18 @@ The AWS CLI calls it `aws eventsv2` and the SDKs `EventBridgeV2`. | --- | --- | | `CreateEventBus` | Create an event bus, with an optional description, KMS key, retention period, and tags | | `DescribeEventBus` | Return an event bus's name, description, configuration, state and times | -| `DeleteEventBus` | Delete an event bus that has no subscribers | +| `DeleteEventBus` | Delete an event bus that has no subscribers or event sources | | `ListEventBuses` | List the Region's event buses in name order, filtered by name prefix, a page at a time | | `CreateSubscriber` | Create a subscriber that delivers the events its filters match to an Amazon SQS queue | | `DescribeSubscriber` | Return a subscriber's target, filters, transformer, delivery settings, state and times | | `ListSubscribers` | List the Region's subscribers, or one event bus's, filtered by name prefix, a page at a time | | `UpdateSubscriber` | Change a subscriber's settings, keeping those the request leaves out | | `DeleteSubscriber` | Delete a subscriber | +| `CreateEventSource` | Create a webhook event source on an event bus, with its URL and a managed secret | +| `DescribeEventSource` | Return a webhook event source's configuration, URL, secret ARN, state and times | +| `ListEventSources` | List the Region's event sources, or one event bus's, filtered by name prefix, a page at a time | +| `UpdateEventSource` | Replace a webhook event source's configuration and description | +| `DeleteEventSource` | Delete a webhook event source and schedule its secret for deletion | | `PutEvents` | Publish events in the EventBridge envelope to an event bus | @@ -38,7 +43,7 @@ Every other EventBridge V2 operation answers `UnsupportedOperation`. `ResourceAlreadyExistsException`. - A retried `CreateEventBus` or `CreateSubscriber` with the same `ClientToken` returns what the first call created. The same token with a different request fails with `IdempotentParameterMismatchException`. -- `DeleteEventBus` fails with `ResourceInUseException` while the bus has subscribers. +- `DeleteEventBus` fails with `ResourceInUseException` while the bus has subscribers or event sources. - `ListEventBuses` lists only your own buses. Floci does not share buses across accounts, so an `EventBusAccountId` naming another account lists none. - `EncryptionConfiguration.KmsKeyIdentifier` is stored and returned as given. AWS returns the key's ARN. @@ -93,6 +98,26 @@ the target parameters but has no `TargetArn`: a subscriber keeps its target. An request with one invalid setting changes nothing. `ResumePosition` is accepted and has no effect, since events are not retained. `DescribeSubscriber` and `ListSubscribers` always report `Revoked` as `false`. +## Webhook event sources + +Floci serves event sources of the `WebhookEventsConfiguration` kind. A request with an +`AwsServiceEventsConfiguration` or `PartnerEventsConfiguration` is refused with `InvalidInputException`. + +- A source is `ACTIVE` at once. Its ARN is + `arn:aws:events:::event-sourcev2/webhook//`. +- A source name is unique per account and Region, across event buses. +- The webhook URL is `://.c01.events-webhook..//`. The scheme and + authority are those of Floci's base URL. The URL does not accept requests yet. +- Each source has a Secrets Manager secret named `events-webhook!`, owned by `events-webhook`. It holds the + static token, the HMAC secret, or the Basic credential as `{"username":"...","password":"..."}`. A credential + the request leaves out is generated. The secret ARN is in `EventSourceDetails.WebhookDetails.SecretArn`. +- `DescribeEventSource` returns `Configuration` as given, without `SecretValue`, `Username` and `Password`. +- `UpdateEventSource` replaces the whole webhook configuration and keeps the URL, the secret and the + authentication type. It does not accept credentials. +- `KmsKeyIdentifier` is stored and returned. It is not used for the secret. +- `DeleteEventSource` schedules the secret for deletion at once. +- `DescribeEventSource` and `ListEventSources` do not return `Revoked`. + ## IAM Under IAM enforcement, EventBridge V2 operations are authorized as the `events` actions of the same diff --git a/docs/services/index.md b/docs/services/index.md index a09b97070a..655df73b80 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -57,7 +57,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CloudFormation](cloudformation.md) | `POST /` with `Action=` param | Query | 36 | | [Cloud Control API](cloudcontrol.md) | `POST /` + `X-Amz-Target: CloudApiService.*` | JSON 1.1 | 5 | | [EventBridge](eventbridge.md) | `POST /` + `X-Amz-Target: AmazonEventBridge.*` | JSON 1.1 | 41 | -| [EventBridge V2](eventbridgev2.md) | `POST /service/AWSEventsV2/operation/*` | Smithy RPC v2 CBOR | 10 | +| [EventBridge V2](eventbridgev2.md) | `POST /service/AWSEventsV2/operation/*` | Smithy RPC v2 CBOR | 15 | | [EventBridge Scheduler](scheduler.md) | `/schedules/*`, `/schedule-groups/*`, `/tags/*` | REST JSON | 12 | | [EventBridge Pipes](pipes.md) | `/v1/pipes/*` | REST JSON | 10 | | [CloudWatch OAM](oam.md) | REST paths such as `POST /CreateSink` and `POST /CreateLink` | REST JSON | 15 | 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 94c7087359..bcae2529f4 100644 --- a/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java +++ b/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java @@ -2,12 +2,15 @@ package io.floci.aws.core.common; 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 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.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -94,25 +97,83 @@ public final class RequestConstraintCheck { }; } + /** + * The orders of a violation list that the vendored file cannot say. A service measures them on AWS. + * + * @param patternBeforeLength a string reports its pattern before its length + * @param mapsInHashOrder a map is quoted in the order of a {@link HashMap} sized for its entries, not in + * request order + */ + public record ViolationOrder(boolean patternBeforeLength, boolean mapsInHashOrder) { + public static final ViolationOrder STANDARD = new ViolationOrder(false, false); + } + private final JsonNode model; private final Map patterns; private final Messages messages; + private final ViolationOrder order; private final Set wordable = ConcurrentHashMap.newKeySet(); - private RequestConstraintCheck(JsonNode model, Messages messages) { + private RequestConstraintCheck(JsonNode model, Messages messages, ViolationOrder order) { this.model = model; this.messages = messages; + this.order = order; this.patterns = VendoredShapes.patterns(model.path("shapes")); } /** The vendored resource {@code name}; {@code description} names it in a failure. */ public static RequestConstraintCheck load(String name, String description, Messages messages) { + return load(name, description, messages, ViolationOrder.STANDARD); + } + + public static RequestConstraintCheck load(String name, String description, Messages messages, + ViolationOrder order) { return VendoredResources.read(name, description, - input -> new RequestConstraintCheck(MAPPER.readTree(input), messages)); + input -> new RequestConstraintCheck(MAPPER.readTree(input), messages, order)); } public static RequestConstraintCheck of(JsonNode model, Messages messages) { - return new RequestConstraintCheck(model, messages); + return of(model, messages, ViolationOrder.STANDARD); + } + + public static RequestConstraintCheck of(JsonNode model, Messages messages, ViolationOrder order) { + return new RequestConstraintCheck(model, messages, order); + } + + /** + * A copy of {@code value} that keeps only the members {@code shapeName} declares. Structures and lists are + * walked and a map is copied as given. + */ + public JsonNode modeled(String shapeName, JsonNode value) { + JsonNode shape = model.path("shapes").path(shapeName); + switch (shape.path("type").asText()) { + case "structure" -> { + if (!value.isObject()) { + return value.deepCopy(); + } + ObjectNode copy = MAPPER.createObjectNode(); + for (Map.Entry field : value.properties()) { + JsonNode member = shape.path("members").get(field.getKey()); + if (member != null) { + copy.set(field.getKey(), modeled(member.asText(), field.getValue())); + } + } + return copy; + } + case "list" -> { + if (!value.isArray()) { + return value.deepCopy(); + } + ArrayNode copy = MAPPER.createArrayNode(); + for (JsonNode item : value) { + copy.add(modeled(shape.path("member").asText(), item)); + } + return copy; + } + default -> { + return value.deepCopy(); + } + } } /** Whether the vendored model declares an input for {@code operation}. */ @@ -230,7 +291,8 @@ public final class RequestConstraintCheck { /** * 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 + * error. Members come in the order the vendored shape lists them in, which a generator may set. A string's + * pattern and length, and the text a map is quoted as, follow the {@link ViolationOrder}. 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}. @@ -339,7 +401,8 @@ public final class RequestConstraintCheck { if (!value.isTextual()) { throw messages.type(errorPath, type); } - found.addAll(VendoredShapes.stringViolations(shape, patterns.get(name), value.textValue(), path, form)); + found.addAll(VendoredShapes.stringViolations(shape, patterns.get(name), value.textValue(), path, + form, order.patternBeforeLength())); } case "integer", "long" -> collectInteger(shape, type, value, path, errorPath, form, found); case "float", "double" -> { @@ -366,16 +429,16 @@ public final class RequestConstraintCheck { private void collectInteger(JsonNode shape, String type, JsonNode value, String path, String errorPath, SmithyValidationErrors.Violations form, List found) { - if (!value.isIntegralNumber()) { + boolean fits = "integer".equals(type) ? value.isIntegralNumber() && value.canConvertToInt() + : value.isIntegralNumber() && value.canConvertToLong(); + if (!fits) { throw messages.type(errorPath, type); } - BigInteger number = value.bigIntegerValue(); - if (shape.has("min") && number.compareTo(BigInteger.valueOf(shape.get("min").asLong())) < 0) { + long number = value.longValue(); + if (shape.has("min") && number < shape.get("min").asLong()) { 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) { + } else if (shape.has("max") && number > shape.get("max").asLong()) { 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); } } @@ -404,11 +467,7 @@ public final class RequestConstraintCheck { 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 mapText = mapText(value); String size = sizeViolation(shape, value.size()); if (size != null) { found.add(form.constraint(path, mapText, size)); @@ -486,6 +545,14 @@ public final class RequestConstraintCheck { return null; } + private String mapText(JsonNode map) { + Map quoted = order.mapsInHashOrder() ? new HashMap<>(map.size()) : new LinkedHashMap<>(); + for (Map.Entry entry : map.properties()) { + quoted.put(entry.getKey(), elementText(entry.getValue())); + } + return quoted.toString(); + } + private static String elementsText(JsonNode list) { List texts = new ArrayList<>(); list.forEach(item -> texts.add(elementText(item))); diff --git a/src/main/java/io/floci/aws/core/common/VendoredShapes.java b/src/main/java/io/floci/aws/core/common/VendoredShapes.java index 17cb637e92..28dee000fd 100644 --- a/src/main/java/io/floci/aws/core/common/VendoredShapes.java +++ b/src/main/java/io/floci/aws/core/common/VendoredShapes.java @@ -43,20 +43,46 @@ final class VendoredShapes { */ static List stringViolations(JsonNode shape, Pattern pattern, String text, String path, SmithyValidationErrors.Violations messages) { + return stringViolations(shape, pattern, text, path, messages, false); + } + + /** {@link #stringViolations} that reports the pattern before the length when {@code patternBeforeLength}. */ + static List stringViolations(JsonNode shape, Pattern pattern, String text, String path, + SmithyValidationErrors.Violations messages, boolean patternBeforeLength) { List violations = new ArrayList<>(); + if (patternBeforeLength) { + addPattern(violations, shape, pattern, text, path, messages); + addLength(violations, shape, text, path, messages); + } else { + addLength(violations, shape, text, path, messages); + addPattern(violations, shape, pattern, text, path, messages); + } + addEnum(violations, shape, text, path, messages); + return violations; + } + + private static void addLength(List violations, JsonNode shape, String text, String path, + SmithyValidationErrors.Violations messages) { String length = messages.lengthOutOfRange(path, text, shape.path("min").asInt(0), shape.path("max").asInt(Integer.MAX_VALUE)); if (length != null) { violations.add(length); } + } + + private static void addPattern(List violations, JsonNode shape, Pattern pattern, String text, + String path, SmithyValidationErrors.Violations messages) { if (pattern != null && !pattern.matcher(text).matches()) { violations.add(messages.pattern(path, text, VendoredPatterns.quoted(shape))); } + } + + private static void addEnum(List violations, JsonNode shape, String text, String path, + SmithyValidationErrors.Violations messages) { List allowed = enumValues(shape); if (!allowed.isEmpty() && !allowed.contains(text)) { violations.add(messages.notInEnum(text, path, allowed)); } - return violations; } /** The values a shape's enum admits, in the model's order, or none for a shape without one. */ diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java new file mode 100644 index 0000000000..577de7fd8d --- /dev/null +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java @@ -0,0 +1,361 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Digests; +import io.floci.aws.core.common.PaginatedResult; +import io.floci.aws.core.common.Pagination; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.Resettable; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.eventbridgev2.model.EventBusV2; +import io.floci.aws.services.eventbridgev2.model.EventSourceV2; +import io.floci.aws.services.secretsmanager.SecretsManagerService; +import io.floci.aws.services.secretsmanager.model.Secret; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.net.URI; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; + +/** + * The webhook event sources of EventBridge V2: their storage, the secret each one keeps its credential in and the + * URL it is reached at. The event bus a source belongs to is the bus service's, so each call that needs one is + * given the lookup. + */ +@ApplicationScoped +public class EventBridgeV2EventSources implements Resettable { + private static final String OWNING_SERVICE = "events-webhook"; + + private static final Logger LOG = Logger.getLogger(EventBridgeV2EventSources.class); + private static final int GENERATED_SECRET_BYTES = 32; + private static final String TOKEN_NAMESPACE = "event-sourcev2"; + + private final AccountAwareStorageBackend sources; + private final SecretsManagerService secrets; + private final RegionResolver regionResolver; + private final Clock clock; + private final URI baseUrl; + private final SecureRandom random = new SecureRandom(); + + @Inject + public EventBridgeV2EventSources(StorageFactory storageFactory, SecretsManagerService secrets, + RegionResolver regionResolver, EmulatorConfig config) { + this(storageFactory.create("eventbridgev2", "eventbridgev2-event-sources.json", + new TypeReference>() {}), + secrets, regionResolver, Clock.systemUTC(), config.effectiveBaseUrl()); + } + + EventBridgeV2EventSources(AccountAwareStorageBackend sources, SecretsManagerService secrets, + RegionResolver regionResolver, Clock clock, String baseUrl) { + this.sources = sources; + this.secrets = secrets; + this.regionResolver = regionResolver; + this.clock = clock; + this.baseUrl = URI.create(baseUrl); + } + + /** + * Creates a webhook event source on a bus of the caller's, {@code ACTIVE} at once, with the secret that holds + * its credential. A retry with the {@code ClientToken} of an earlier create returns that source when it repeats + * the request, and fails when it changes it. + */ + EventSourceV2 create(JsonNode request, String region, Function> findBusByName) { + EventBridgeV2RequestShapes.check("CreateEventSource", request); + String name = request.get("Name").textValue(); + String eventBusArn = request.get("EventBusArn").textValue(); + JsonNode configuration = request.get("Configuration"); + String roleArn = configuration.path(WebhookEventsConfigurations.WEBHOOK).path("RoleArn").asText(null); + + requireEndpointRegion(eventBusArn, region, "EventBusArn"); + requireOwnAccount(eventBusArn); + if (roleArn != null) { + requireOwnAccount(roleArn); + } + String clientToken = request.path("ClientToken").textValue(); + if (clientToken == null) { + throw EventBridgeV2Service.invalidInput("ClientToken is required"); + } + JsonNode webhook = WebhookEventsConfigurations.validateForCreate(configuration); + + // The request carries credentials, so only its hash is kept. + String requestHash = Digests.sha256Hex(EventBridgeV2Service.withoutClientToken(request)); + Optional retried = EventBridgeV2Service.retried(() -> inRegion(region), + clientToken, requestHash, EventSourceV2::getClientToken, EventSourceV2::getCreateRequestHash, + () -> new AwsException("IdempotentParameterMismatchException", + "ClientToken was used by a previous request with different parameters", 409)); + if (retried.isPresent()) { + return retried.get(); + } + requireBus(eventBusArn, findBusByName); + String key = EventBridgeV2Service.storageKey(region, name); + if (sources.get(key).isPresent()) { + throw new AwsException("ResourceAlreadyExistsException", "Resource already exists", 409); + } + + String hostId = WebhookTokens.newHostId(random); + Instant now = clock.instant(); + EventSourceV2 source = new EventSourceV2(); + source.setName(name); + source.setArn(regionResolver.buildArn("events", region, + "event-sourcev2/webhook/" + name + "/" + EventBridgeV2Service.newId(random))); + source.setEventBusArn(eventBusArn); + source.setDescription(request.path("Description").textValue()); + source.setConfiguration(WebhookEventsConfigurations.echo(webhook)); + source.setState(EventBridgeV2Service.ACTIVE); + source.setCreationTime(now); + source.setLastModifiedTime(now); + source.setTags(tags(request.get("Tags"))); + source.setClientToken(clientToken); + source.setCreateRequestHash(requestHash); + source.setWebhookHostId(hostId); + source.setWebhookToken(WebhookTokens.newToken(hostId, random)); + source.setSecretArn(createSecret(webhook, region)); + try { + sources.put(key, source); + } catch (RuntimeException e) { + deleteOrphanedSecret(source.getSecretArn(), region); + throw e; + } + return source; + } + + /** + * Replaces the description the request gives and the whole webhook configuration. The credentials, the URL and + * the secret stay as they are. A refused update changes nothing. + */ + EventSourceV2 update(JsonNode request, String region) { + EventBridgeV2RequestShapes.check("UpdateEventSource", request); + String arn = request.get("EventSourceArn").textValue(); + checkArn(arn, region); + JsonNode configuration = request.hasNonNull("Configuration") ? request.get("Configuration") : null; + String roleArn = configuration == null ? null + : configuration.path(WebhookEventsConfigurations.WEBHOOK).path("RoleArn").asText(null); + if (roleArn != null) { + requireOwnAccount(roleArn); + } + EventSourceV2 source = require(arn, region); + JsonNode webhook = configuration == null ? null : WebhookEventsConfigurations.validateForUpdate( + configuration, WebhookEventsConfigurations.authType( + source.getConfiguration().get(WebhookEventsConfigurations.WEBHOOK))); + + EventSourceV2 changed = new EventSourceV2(); + changed.setName(source.getName()); + changed.setArn(source.getArn()); + changed.setEventBusArn(source.getEventBusArn()); + changed.setDescription(request.hasNonNull("Description") ? request.get("Description").textValue() + : source.getDescription()); + changed.setConfiguration(webhook == null ? source.getConfiguration() + : WebhookEventsConfigurations.echo(webhook)); + changed.setState(source.getState()); + changed.setCreationTime(source.getCreationTime()); + changed.setLastModifiedTime(clock.instant()); + changed.setTags(source.getTags()); + changed.setClientToken(source.getClientToken()); + changed.setCreateRequestHash(source.getCreateRequestHash()); + changed.setWebhookHostId(source.getWebhookHostId()); + changed.setWebhookToken(source.getWebhookToken()); + changed.setSecretArn(source.getSecretArn()); + sources.put(EventBridgeV2Service.storageKey(region, source.getName()), changed); + return changed; + } + + EventSourceV2 describe(JsonNode request, String region) { + return find("DescribeEventSource", request, region); + } + + private EventSourceV2 find(String operation, JsonNode request, String region) { + EventBridgeV2RequestShapes.check(operation, request); + String arn = request.get("EventSourceArn").textValue(); + checkArn(arn, region); + return require(arn, region); + } + + /** Deletes the source and schedules its secret for deletion, unless the secret is already scheduled. */ + void delete(JsonNode request, String region) { + EventSourceV2 source = find("DeleteEventSource", request, region); + try { + if (secrets.describeSecret(source.getSecretArn(), region).getDeletedDate() == null) { + secrets.deleteSecret(source.getSecretArn(), null, false, region); + } + } catch (AwsException e) { + if (!"ResourceNotFoundException".equals(e.getErrorCode())) { + throw e; + } + LOG.warnv("The secret {0} of event source {1} is already gone", source.getSecretArn(), source.getArn()); + } + sources.delete(EventBridgeV2Service.storageKey(region, source.getName())); + } + + /** + * One page of the Region's sources, or those of one bus, whose name starts with {@code NamePrefix}, in order of + * their ids. A token that is not one of ours is refused before the bus is looked up. + */ + PaginatedResult list(JsonNode request, String region, + Function> findBusByName) { + EventBridgeV2RequestShapes.check("ListEventSources", request); + String eventBusArn = request.path("EventBusArn").textValue(); + String namePrefix = request.path("NamePrefix").textValue(); + String nextToken = request.path("NextToken").textValue(); + if (eventBusArn != null) { + requireEndpointRegion(eventBusArn, region, "EventBusArn"); + } + String namespace = tokenNamespace(region, eventBusArn, namePrefix); + if (nextToken != null && !Pagination.tokenStartsWith(nextToken, namespace + ":")) { + throw invalidNextToken(); + } + if (eventBusArn != null) { + if (AwsArnUtils.isForeignAccount(AwsArnUtils.parse(eventBusArn), regionResolver.getAccountId())) { + throw busMissing(); + } + requireBus(eventBusArn, findBusByName); + } + List listed = inRegion(region).stream() + .filter(source -> eventBusArn == null || eventBusArn.equals(source.getEventBusArn())) + .filter(source -> namePrefix == null || source.getName().startsWith(namePrefix)) + .toList(); + int maxResults = request.hasNonNull("MaxResults") ? request.get("MaxResults").intValue() + : EventBridgeV2Service.MAX_LIST_RESULTS; + return Pagination.paginate(listed, EventBridgeV2EventSources::id, maxResults, nextToken, namespace, + token -> invalidNextToken()); + } + + private static String tokenNamespace(String region, String eventBusArn, String namePrefix) { + String filters = region + "\n" + (eventBusArn == null ? "-" : "+" + eventBusArn) + "\n" + + (namePrefix == null ? "-" : "+" + namePrefix); + return TOKEN_NAMESPACE + "-" + Digests.sha256Hex(filters); + } + + boolean hasSourcesOn(String eventBusArn, String region) { + return inRegion(region).stream().anyMatch(source -> eventBusArn.equals(source.getEventBusArn())); + } + + /** The URL a source receives its events at, in the scheme of Floci's own base URL. */ + String webhookUrl(EventSourceV2 source) { + return baseUrl.getScheme() + "://" + source.getWebhookHostId() + ".c01.events-webhook." + + AwsArnUtils.parse(source.getArn()).region() + "." + baseUrl.getAuthority() + "/" + + source.getWebhookToken() + "/"; + } + + @Override + public void clear() { + sources.clear(); + } + + private String createSecret(JsonNode webhook, String region) { + JsonNode auth = webhook.get("AuthConfiguration"); + String authType = WebhookEventsConfigurations.authType(webhook); + String secretString; + if (WebhookEventsConfigurations.BASIC.equals(authType)) { + JsonNode basic = auth.get(WebhookEventsConfigurations.BASIC); + ObjectNode credential = JsonNodeFactory.instance.objectNode(); + credential.put("username", basic.hasNonNull("Username") ? basic.get("Username").textValue() : generated()); + credential.put("password", basic.hasNonNull("Password") ? basic.get("Password").textValue() : generated()); + secretString = credential.toString(); + } else if (WebhookEventsConfigurations.HMAC.equals(authType)) { + String given = WebhookEventsConfigurations.hmacSecretValue(auth.get(WebhookEventsConfigurations.HMAC)); + secretString = given != null ? given : generated(); + } else { + JsonNode staticToken = auth.get(WebhookEventsConfigurations.STATIC_TOKEN); + secretString = staticToken.hasNonNull("SecretValue") ? staticToken.get("SecretValue").textValue() + : generated(); + } + return secrets.createSecret("events-webhook!" + UUID.randomUUID(), secretString, null, null, null, + List.of(new Secret.Tag("aws:secretsmanager:owningService", OWNING_SERVICE)), OWNING_SERVICE, + region).getArn(); + } + + private void deleteOrphanedSecret(String secretArn, String region) { + try { + secrets.deleteSecret(secretArn, null, true, region); + } catch (RuntimeException e) { + LOG.warnv(e, "The secret {0} of an event source that was not stored could not be deleted", secretArn); + } + } + + private String generated() { + byte[] bytes = new byte[GENERATED_SECRET_BYTES]; + random.nextBytes(bytes); + return Base64.getEncoder().encodeToString(bytes); + } + + private static void requireBus(String eventBusArn, Function> findBusByName) { + String busName = EventBridgeV2Service.busName(eventBusArn); + EventBusV2 bus = findBusByName.apply(busName).orElseThrow(EventBridgeV2EventSources::busMissing); + if (!eventBusArn.equals(bus.getArn())) { + throw new AwsException("ResourceNotFoundException", "Event bus not found: " + busName, 404); + } + } + + private static AwsException busMissing() { + return new AwsException("ResourceNotFoundException", "Resource does not exist", 404); + } + + private static AwsException invalidNextToken() { + return EventBridgeV2Service.invalidInput("Invalid nextToken"); + } + + private void checkArn(String eventSourceArn, String region) { + requireEndpointRegion(eventSourceArn, region, "EventSourceArn"); + requireOwnAccount(eventSourceArn); + } + + private EventSourceV2 require(String eventSourceArn, String region) { + String[] resource = AwsArnUtils.parse(eventSourceArn).resource().split("/"); + Optional found = resource.length == 4 && "event-sourcev2".equals(resource[0]) + ? sources.get(EventBridgeV2Service.storageKey(region, resource[2])) + .filter(source -> eventSourceArn.equals(source.getArn())) + : Optional.empty(); + return found.orElseThrow(() -> new AwsException("ResourceNotFoundException", + "EventSource not found: " + eventSourceArn, 404)); + } + + private void requireEndpointRegion(String arn, String region, String member) { + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + if (!parsed.region().equals(region) || !parsed.partition().equals(regionResolver.partitionForRegion(region))) { + throw EventBridgeV2Service.invalidInput( + "The region or partition in " + member + " does not match this endpoint"); + } + } + + private void requireOwnAccount(String arn) { + if (AwsArnUtils.isForeignAccount(AwsArnUtils.parse(arn), regionResolver.getAccountId())) { + throw new AwsException("AccessDeniedException", "Access denied.", 403); + } + } + + private List inRegion(String region) { + String prefix = region + "::"; + return sources.scan(key -> key.startsWith(prefix)); + } + + private static Map tags(JsonNode node) { + Map tags = new LinkedHashMap<>(); + if (node != null && node.isObject()) { + for (Map.Entry tag : node.properties()) { + tags.put(tag.getKey(), tag.getValue().textValue()); + } + } + return tags; + } + + static String id(EventSourceV2 source) { + return source.getArn().substring(source.getArn().length() - EventBridgeV2Service.ID_LENGTH); + } +} diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java index 1204c8d8de..edf2f04d0f 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java @@ -8,6 +8,7 @@ import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.services.eventbridgev2.model.EventBusV2; +import io.floci.aws.services.eventbridgev2.model.EventSourceV2; import io.floci.aws.services.eventbridgev2.model.SubscriberV2; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -52,6 +53,11 @@ public class EventBridgeV2Handler { case "ListSubscribers" -> handleListSubscribers(request, region); case "UpdateSubscriber" -> handleUpdateSubscriber(request, region); case "DeleteSubscriber" -> handleDeleteSubscriber(request, region); + case "CreateEventSource" -> handleCreateEventSource(request, region); + case "DescribeEventSource" -> handleDescribeEventSource(request, region); + case "ListEventSources" -> handleListEventSources(request, region); + case "UpdateEventSource" -> handleUpdateEventSource(request, region); + case "DeleteEventSource" -> handleDeleteEventSource(request, region); case "PutEvents" -> handlePutEvents(request, region); default -> throw new AwsException("UnsupportedOperation", "Operation " + operation + " is not supported.", 400); @@ -195,6 +201,82 @@ public class EventBridgeV2Handler { return Response.ok(objectMapper.createObjectNode()).build(); } + private Response handleCreateEventSource(JsonNode request, String region) { + EventSourceV2 source = service.createEventSource(request, region); + ObjectNode response = eventSourceIdentity(source); + response.set("EventSourceDetails", eventSourceDetails(source)); + response.put("CreationTime", epochSeconds(source.getCreationTime())); + return Response.ok(response).build(); + } + + private Response handleDescribeEventSource(JsonNode request, String region) { + EventSourceV2 source = service.describeEventSource(request, region); + ObjectNode response = objectMapper.createObjectNode(); + response.put("EventSourceArn", source.getArn()); + response.put("Name", source.getName()); + response.put("EventBusArn", source.getEventBusArn()); + response.set("Configuration", source.getConfiguration()); + if (source.getDescription() != null) { + response.put("Description", source.getDescription()); + } + response.put("State", source.getState()); + response.set("EventSourceDetails", eventSourceDetails(source)); + response.put("CreationTime", epochSeconds(source.getCreationTime())); + response.put("LastModifiedTime", epochSeconds(source.getLastModifiedTime())); + return Response.ok(response).build(); + } + + private Response handleUpdateEventSource(JsonNode request, String region) { + EventSourceV2 source = service.updateEventSource(request, region); + ObjectNode response = eventSourceIdentity(source); + response.put("LastModifiedTime", epochSeconds(source.getLastModifiedTime())); + return Response.ok(response).build(); + } + + private Response handleDeleteEventSource(JsonNode request, String region) { + service.deleteEventSource(request, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleListEventSources(JsonNode request, String region) { + PaginatedResult page = service.listEventSources(request, region); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode sources = response.putArray("EventSources"); + for (EventSourceV2 source : page.items()) { + ObjectNode summary = sources.addObject(); + summary.put("EventSourceArn", source.getArn()); + summary.put("Name", source.getName()); + summary.put("EventBusArn", source.getEventBusArn()); + summary.put("Type", "WEBHOOK_EVENTS"); + summary.put("State", source.getState()); + summary.put("CreationTime", epochSeconds(source.getCreationTime())); + summary.put("LastModifiedTime", epochSeconds(source.getLastModifiedTime())); + summary.put("EventSourceAccountId", AwsArnUtils.parse(source.getArn()).accountId()); + } + if (page.nextToken() != null) { + response.put("NextToken", page.nextToken()); + } + return Response.ok(response).build(); + } + + /** The members {@code CreateEventSource} and {@code UpdateEventSource} both answer with. */ + private ObjectNode eventSourceIdentity(EventSourceV2 source) { + ObjectNode response = objectMapper.createObjectNode(); + response.put("EventSourceArn", source.getArn()); + response.put("Name", source.getName()); + response.put("EventBusArn", source.getEventBusArn()); + response.put("State", source.getState()); + return response; + } + + private ObjectNode eventSourceDetails(EventSourceV2 source) { + ObjectNode details = objectMapper.createObjectNode(); + ObjectNode webhook = details.putObject("WebhookDetails"); + webhook.put("WebhookUrl", service.webhookUrl(source)); + webhook.put("SecretArn", source.getSecretArn()); + return details; + } + private Response handlePutEvents(JsonNode request, String region) { List results = service.putEvents(request, region); ObjectNode response = objectMapper.createObjectNode(); diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapes.java b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapes.java new file mode 100644 index 0000000000..eb97ab030e --- /dev/null +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapes.java @@ -0,0 +1,85 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RequestConstraintCheck; +import io.floci.aws.core.common.SmithyValidationErrors; + +import java.util.List; + +/** + * Checks EventBridge V2 event source requests against the constraints generated by + * {@code tools/aws/regen_eventbridgev2_shapes.py}. The first ten violations are answered together as + * {@code InvalidInputException}, in the wording AWS uses. A member of the wrong type is answered as + * {@code SerializationException} with no message. + */ +final class EventBridgeV2RequestShapes { + + private static final int MAX_VIOLATIONS = 10; + + private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load( + "aws/eventbridgev2-request-shapes.json", "EventBridge V2 request shapes", new Messages(), + new RequestConstraintCheck.ViolationOrder(true, true)); + + private EventBridgeV2RequestShapes() { + } + + /** {@code value} without the members that {@code shapeName} does not declare. */ + static JsonNode modeled(String shapeName, JsonNode value) { + return CHECK.modeled(shapeName, value); + } + + static void check(String operation, JsonNode request) { + List violations = CHECK.violations(operation, withoutWhsecPrefix(request)); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.exception("InvalidInputException", + violations.subList(0, Math.min(violations.size(), MAX_VIOLATIONS))); + } + } + + /** Only {@code violations} is used, and it reaches nothing but the type message. */ + private static final class Messages implements RequestConstraintCheck.Messages { + private final RequestConstraintCheck.Messages standard = + RequestConstraintCheck.standardMessages("InvalidInputException"); + + @Override + public AwsException type(String path, String type) { + return new AwsException("SerializationException", null, 400); + } + + @Override + public AwsException bounds(String path, String type, Long min, Long max, Number size) { + return standard.bounds(path, type, min, max, size); + } + + @Override + public AwsException pattern(String path, String pattern) { + return standard.pattern(path, pattern); + } + + @Override + public AwsException enumValue(String path, List values) { + return standard.enumValue(path, values); + } + + @Override + public AwsException required(String path) { + return standard.required(path); + } + } + + /** AWS judges the length of a Base64 HMAC secret without its {@code whsec_} prefix. */ + private static JsonNode withoutWhsecPrefix(JsonNode request) { + JsonNode hmac = request.path("Configuration").path(WebhookEventsConfigurations.WEBHOOK) + .path("AuthConfiguration").path(WebhookEventsConfigurations.HMAC); + String secret = WebhookEventsConfigurations.hmacSecretValue(hmac); + if (secret == null || secret.equals(hmac.path("SecretValue").textValue())) { + return request; + } + ObjectNode copy = request.deepCopy(); + ((ObjectNode) copy.path("Configuration").path(WebhookEventsConfigurations.WEBHOOK) + .path("AuthConfiguration").path(WebhookEventsConfigurations.HMAC)).put("SecretValue", secret); + return copy; + } +} diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java index b16b3ff08c..13b0115d77 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java @@ -18,6 +18,7 @@ import io.floci.aws.core.common.Resettable; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.eventbridgev2.model.EventBusV2; +import io.floci.aws.services.eventbridgev2.model.EventSourceV2; import io.floci.aws.services.eventbridgev2.model.SubscriberV2; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -41,6 +42,7 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Function; +import java.util.function.Supplier; import java.util.regex.Pattern; /** @@ -70,10 +72,10 @@ public class EventBridgeV2Service implements Resettable { "KinesisParameters", "StepFunctionsParameters", "HttpParameters", "UniversalTargetParameters", "EventBusV2Parameters"); private static final String ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"; - private static final int ID_LENGTH = 25; + static final int ID_LENGTH = 25; private static final int MAX_TAGS = 200; private static final int MAX_ENTRIES = 100; - private static final int MAX_LIST_RESULTS = 100; + static final int MAX_LIST_RESULTS = 100; private static final List UPDATABLE_SETTINGS = List.of("Description", "State", "FilterConfiguration", "BatchConfiguration", "Transformer", "RetryPolicy", "OnFailureConfiguration", "LogConfiguration"); private static final String PUT_EVENTS_CONTENT_TYPE = "application/eventbridge+json"; @@ -82,6 +84,7 @@ public class EventBridgeV2Service implements Resettable { private final AccountAwareStorageBackend subscribers; private final RegionResolver regionResolver; private final EventBridgeV2Delivery delivery; + private final EventBridgeV2EventSources eventSources; private final Clock clock; private final boolean enabled; private final SecureRandom random = new SecureRandom(); @@ -89,21 +92,24 @@ public class EventBridgeV2Service implements Resettable { @Inject public EventBridgeV2Service(StorageFactory storageFactory, RegionResolver regionResolver, - EventBridgeV2Delivery delivery, EmulatorConfig config) { + EventBridgeV2Delivery delivery, EventBridgeV2EventSources eventSources, + EmulatorConfig config) { this(storageFactory.create("eventbridgev2", "eventbridgev2-buses.json", new TypeReference>() {}), storageFactory.create("eventbridgev2", "eventbridgev2-subscribers.json", new TypeReference>() {}), - regionResolver, delivery, Clock.systemUTC(), config.services().eventbridgev2().enabled()); + regionResolver, delivery, eventSources, Clock.systemUTC(), config.services().eventbridgev2().enabled()); } EventBridgeV2Service(AccountAwareStorageBackend buses, AccountAwareStorageBackend subscribers, RegionResolver regionResolver, - EventBridgeV2Delivery delivery, Clock clock, boolean enabled) { + EventBridgeV2Delivery delivery, EventBridgeV2EventSources eventSources, Clock clock, + boolean enabled) { this.buses = buses; this.subscribers = subscribers; this.regionResolver = regionResolver; this.delivery = delivery; + this.eventSources = eventSources; this.clock = clock; this.enabled = enabled; } @@ -128,16 +134,11 @@ public class EventBridgeV2Service implements Resettable { String clientToken = optionalClientToken(request); String createRequest = withoutClientToken(request); - if (clientToken != null) { - Optional retried = buses.scan(key -> key.startsWith(region + "::")).stream() - .filter(bus -> clientToken.equals(bus.getClientToken())) - .findFirst(); - if (retried.isPresent()) { - if (!createRequest.equals(retried.get().getCreateRequest())) { - throw idempotentMismatch(clientToken); - } - return retried.get(); - } + Optional retried = retried(() -> buses.scan(key -> key.startsWith(region + "::")), clientToken, + createRequest, EventBusV2::getClientToken, EventBusV2::getCreateRequest, + () -> idempotentMismatch(clientToken)); + if (retried.isPresent()) { + return retried.get(); } String key = storageKey(region, name); if (buses.get(key).isPresent()) { @@ -206,10 +207,16 @@ public class EventBridgeV2Service implements Resettable { deleteEventBus(requireText(request, "EventBusArn"), region); } - /** Deletes a bus, which must have no subscribers left. */ + /** Deletes a bus, which must have no subscribers or event sources left. */ public synchronized void deleteEventBus(String eventBusArn, String region) { EventBusV2 bus = requireEventBus(eventBusArn, region); - if (!subscribersOf(bus, region).isEmpty()) { + boolean hasSubscribers = !subscribersOf(bus, region).isEmpty(); + if (eventSources.hasSourcesOn(bus.getArn(), region)) { + throw new AwsException("ResourceInUseException", "The event bus cannot be deleted because it has " + + (hasSubscribers ? "subscribers and event sources" : "one or more event sources") + + " that are not revoked. Delete or revoke them and retry.", 409); + } + if (hasSubscribers) { throw new AwsException("ResourceInUseException", "Event bus " + bus.getName() + " still has subscribers; delete them first.", 409); } @@ -251,16 +258,11 @@ public class EventBridgeV2Service implements Resettable { } String clientToken = optionalClientToken(request); String createRequest = withoutClientToken(request); - if (clientToken != null) { - Optional retried = subscribers.scan(key -> key.startsWith(region + "::")).stream() - .filter(subscriber -> clientToken.equals(subscriber.getClientToken())) - .findFirst(); - if (retried.isPresent()) { - if (!createRequest.equals(retried.get().getCreateRequest())) { - throw idempotentMismatch(clientToken); - } - return retried.get(); - } + Optional retried = retried(() -> subscribers.scan(key -> key.startsWith(region + "::")), + clientToken, createRequest, SubscriberV2::getClientToken, SubscriberV2::getCreateRequest, + () -> idempotentMismatch(clientToken)); + if (retried.isPresent()) { + return retried.get(); } EventBusV2 bus = requireEventBus(eventBusArn, region); String key = subscriberKey(region, bus.getName(), name); @@ -410,6 +412,36 @@ public class EventBridgeV2Service implements Resettable { .filter(bus -> bus.getArn().equals(eventBusArn)); } + // ──────────────────────────── Event sources ──────────────────────────── + + public synchronized EventSourceV2 createEventSource(JsonNode request, String region) { + return eventSources.create(request, region, name -> buses.get(storageKey(region, name))); + } + + public synchronized EventSourceV2 describeEventSource(JsonNode request, String region) { + return eventSources.describe(request, region); + } + + public synchronized EventSourceV2 updateEventSource(JsonNode request, String region) { + return eventSources.update(request, region); + } + + public synchronized void deleteEventSource(JsonNode request, String region) { + eventSources.delete(request, region); + } + + /** + * One page of the Region's event sources, or those of the bus {@code EventBusArn} names, whose name starts + * with {@code NamePrefix}, in order of the ids in their ARNs. + */ + public synchronized PaginatedResult listEventSources(JsonNode request, String region) { + return eventSources.list(request, region, name -> buses.get(storageKey(region, name))); + } + + public String webhookUrl(EventSourceV2 source) { + return eventSources.webhookUrl(source); + } + // ──────────────────────────── Events ──────────────────────────── /** A bus's deliveries waiting to be sent, in sequence order, and the lock held while sending them. */ @@ -754,6 +786,10 @@ public class EventBridgeV2Service implements Resettable { } private String newId() { + return newId(random); + } + + static String newId(SecureRandom random) { StringBuilder id = new StringBuilder(ID_LENGTH); for (int i = 0; i < ID_LENGTH; i++) { id.append(ID_ALPHABET.charAt(random.nextInt(ID_ALPHABET.length()))); @@ -761,7 +797,25 @@ public class EventBridgeV2Service implements Resettable { return id.toString(); } - private static String storageKey(String region, String name) { + /** + * The resource an earlier create made with the same {@code ClientToken}, empty when there is none. A request + * that differs from the earlier one fails with {@code mismatch}. + */ + static Optional retried(Supplier> candidates, String clientToken, String createRequest, + Function tokenOf, Function requestOf, + Supplier mismatch) { + if (clientToken == null) { + return Optional.empty(); + } + Optional found = candidates.get().stream().filter(candidate -> clientToken.equals(tokenOf.apply(candidate))) + .findFirst(); + if (found.isPresent() && !createRequest.equals(requestOf.apply(found.get()))) { + throw mismatch.get(); + } + return found; + } + + static String storageKey(String region, String name) { return region + "::" + name; } @@ -888,7 +942,7 @@ public class EventBridgeV2Service implements Resettable { * The request without its {@code ClientToken}, every object's fields in name order, so a retry that sends the same * values with its fields or tags in another order compares equal to the request it repeats. */ - private static String withoutClientToken(JsonNode request) { + static String withoutClientToken(JsonNode request) { JsonNode copy = request.deepCopy(); if (copy instanceof ObjectNode object) { object.remove("ClientToken"); @@ -935,7 +989,7 @@ public class EventBridgeV2Service implements Resettable { "ClientToken " + clientToken + " was used with a different request.", 409); } - private static AwsException invalidInput(String message) { + static AwsException invalidInput(String message) { return new AwsException("InvalidInputException", message, 400); } } diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurations.java b/src/main/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurations.java new file mode 100644 index 0000000000..94ab994f03 --- /dev/null +++ b/src/main/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurations.java @@ -0,0 +1,312 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import static io.floci.aws.services.eventbridgev2.EventBridgeV2Service.invalidInput; + +/** + * The request rules of a webhook event source that AWS checks after the constraints of its model, reported one at + * a time. It also builds the form of the configuration that {@code DescribeEventSource} returns. + */ +final class WebhookEventsConfigurations { + static final String WEBHOOK = "WebhookEventsConfiguration"; + static final String STATIC_TOKEN = "StaticTokenAuthConfiguration"; + static final String BASIC = "BasicHttpAuthConfiguration"; + static final String HMAC = "HmacAuthConfiguration"; + + private static final String AUTH = "WebhookEventsConfiguration.AuthConfiguration"; + private static final String METADATA = "WebhookEventsConfiguration.MetadataHttpHeaders"; + private static final String HMAC_INVALID = AUTH + ".HmacAuthConfiguration is invalid: "; + private static final String WHSEC = "whsec_"; + private static final int MIN_HMAC_SECRET_BYTES = 16; + private static final String ONLY_WEBHOOK = "Only WebhookEventsConfiguration event sources are supported."; + private static final List SECRET_MEMBERS = List.of("SecretValue", "Username", "Password"); + private static final List AUTH_MEMBERS = List.of(STATIC_TOKEN, BASIC, HMAC); + + private static final Set REFUSED_COMMON_HEADERS = lowerCased("Host", "X-Forwarded-For", + "X-Forwarded-Host", "X-Forwarded-Proto", "Connection", "Transfer-Encoding", "Cookie", "Via", "Upgrade", + "TE", "Keep-Alive", "Forwarded", "Proxy-Authorization", "Trailer", "Proxy-Connection", "Max-Forwards"); + private static final Set REFUSED_AUTH_HEADERS = withExtras(REFUSED_COMMON_HEADERS, + "Content-Length", "Set-Cookie"); + private static final Set REFUSED_METADATA_HEADERS = withExtras(REFUSED_COMMON_HEADERS, "Authorization"); + + private WebhookEventsConfigurations() { + } + + /** + * Checks a create request's {@code Configuration} and returns its webhook configuration. A configuration of + * another variant is refused, as Floci serves webhook event sources only. + */ + static JsonNode validateForCreate(JsonNode configuration) { + Map.Entry variant = onlyVariant(configuration); + if (!WEBHOOK.equals(variant.getKey())) { + throw invalidInput(ONLY_WEBHOOK); + } + validateWebhook(variant.getValue()); + return variant.getValue(); + } + + /** + * Checks an update request's {@code Configuration} against the authentication type the source was created + * with, and returns its webhook configuration. + */ + static JsonNode validateForUpdate(JsonNode configuration, String storedAuthType) { + Map.Entry variant = onlyVariant(configuration); + if (!WEBHOOK.equals(variant.getKey())) { + throw invalidInput("EventSource type is immutable: the configuration variant must remain " + + "WEBHOOK_EVENTS"); + } + JsonNode webhook = variant.getValue(); + JsonNode auth = webhook.path("AuthConfiguration"); + for (String member : AUTH_MEMBERS) { + for (String secret : SECRET_MEMBERS) { + if (auth.path(member).hasNonNull(secret)) { + throw invalidInput("UpdateEventSource does not accept SecretValue, Username or Password; " + + "webhook credentials change only through RotateWebhookCredentials"); + } + } + } + List present = presentAuthMembers(auth); + if (present.size() == 1 && !present.getFirst().equals(storedAuthType)) { + throw invalidInput("The webhook authentication type can't be changed after the EventSource is created"); + } + validateWebhook(webhook); + return webhook; + } + + private static List> variants(JsonNode configuration) { + List> members = new ArrayList<>(); + for (Map.Entry member : configuration.properties()) { + if (!member.getValue().isNull()) { + members.add(member); + } + } + return members; + } + + private static Map.Entry onlyVariant(JsonNode configuration) { + List> members = variants(configuration); + if (members.size() != 1) { + throw invalidInput("Exactly one Configuration sub-field must be provided"); + } + return members.getFirst(); + } + + private static List presentAuthMembers(JsonNode auth) { + List present = new ArrayList<>(); + for (String member : AUTH_MEMBERS) { + if (auth.hasNonNull(member)) { + present.add(member); + } + } + return present; + } + + private static void validateWebhook(JsonNode webhook) { + JsonNode auth = webhook.path("AuthConfiguration"); + List present = presentAuthMembers(auth); + if (present.size() != 1) { + throw invalidInput(AUTH + " must set exactly one of StaticTokenAuthConfiguration, " + + "BasicHttpAuthConfiguration or HmacAuthConfiguration"); + } + String authHeaderMember = switch (present.getFirst()) { + case BASIC -> { + validateBasic(auth.get(BASIC)); + yield null; + } + case STATIC_TOKEN -> { + refuseAuthHeader(STATIC_TOKEN, "TokenHttpHeader", + auth.get(STATIC_TOKEN).path("TokenHttpHeader").asText()); + yield "TokenHttpHeader"; + } + default -> { + validateHmac(auth.get(HMAC)); + yield "SignatureHttpHeader"; + } + }; + if (authHeaderMember == null) { + validateMetadataHeaders(webhook.get("MetadataHttpHeaders"), null, null); + return; + } + validateMetadataHeaders(webhook.get("MetadataHttpHeaders"), + auth.get(present.getFirst()).path(authHeaderMember).asText(), + present.getFirst() + "." + authHeaderMember); + } + + private static void validateBasic(JsonNode basic) { + if (basic.hasNonNull("Username") != basic.hasNonNull("Password")) { + throw invalidInput(AUTH + ".BasicHttpAuthConfiguration must set both Username and Password, or neither. " + + "Supplying only one is not valid; omit both to have EventBridge generate the credential."); + } + } + + private static void validateHmac(JsonNode hmac) { + String secret = hmacSecretValue(hmac); + boolean base64 = "BASE64".equals(hmac.path("SecretEncoding").asText(null)); + int secretBytes = 0; + if (secret != null) { + if (base64) { + try { + secretBytes = Base64.getDecoder().decode(secret).length; + } catch (IllegalArgumentException e) { + throw invalidInput(AUTH + ".HmacAuthConfiguration.SecretValue must be standard Base64 when " + + "SecretEncoding is BASE64"); + } + } else { + secretBytes = secret.getBytes(StandardCharsets.UTF_8).length; + } + } + String signature = hmac.path("SignatureHttpHeader").asText(null); + String timestamp = hmac.path("TimestampHttpHeader").asText(null); + String messageId = hmac.path("MessageIdHttpHeader").asText(null); + String composition = hmac.path("SignedMessageComposition").asText(null); + boolean signsTimestamp = "TIMESTAMP_DOT_BODY".equals(composition) + || "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY".equals(composition); + + if (secret != null && secretBytes < MIN_HMAC_SECRET_BYTES) { + throw hmacInvalid("SecretValue must be at least 16 bytes (for BASE64, after decoding)"); + } + if (hmac.hasNonNull("TimestampToleranceInSeconds") && timestamp == null) { + throw hmacInvalid("TimestampToleranceInSeconds requires TimestampHttpHeader to be set"); + } + if (timestamp != null && !signsTimestamp) { + throw hmacInvalid("TimestampHttpHeader and TimestampToleranceInSeconds require a " + + "SignedMessageComposition that signs the timestamp (TIMESTAMP_DOT_BODY or " + + "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY)"); + } + if (signsTimestamp && timestamp == null) { + throw hmacInvalid(composition + " requires TimestampHttpHeader to be set"); + } + if ("MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY".equals(composition) && messageId == null) { + throw hmacInvalid("MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY requires MessageIdHttpHeader to be set"); + } + if (timestamp != null && signature != null && signature.equalsIgnoreCase(timestamp)) { + if (!hmac.hasNonNull("Delimiter")) { + throw hmacInvalid("Delimiter is required when SignatureHttpHeader and TimestampHttpHeader are the " + + "same"); + } + if (!hmac.hasNonNull("SignaturePrefix") || !hmac.hasNonNull("TimestampPrefix")) { + throw hmacInvalid("SignaturePrefix and TimestampPrefix are both required when SignatureHttpHeader " + + "and TimestampHttpHeader are the same"); + } + } + refuseAuthHeader(HMAC, "SignatureHttpHeader", signature); + refuseAuthHeader(HMAC, "TimestampHttpHeader", timestamp); + refuseAuthHeader(HMAC, "MessageIdHttpHeader", messageId); + } + + private static void refuseAuthHeader(String configuration, String member, String header) { + if (header != null && REFUSED_AUTH_HEADERS.contains(header.toLowerCase(Locale.ROOT))) { + throw invalidInput(AUTH + "." + configuration + "." + member + " can't be the header " + header + + ": it is not allowed. Header names are case-insensitive."); + } + } + + private static void validateMetadataHeaders(JsonNode headers, String authHeader, String authHeaderMember) { + if (headers == null || !headers.isArray()) { + return; + } + Set seen = new HashSet<>(); + for (JsonNode node : headers) { + String header = node.asText(); + String key = header.toLowerCase(Locale.ROOT); + if (REFUSED_METADATA_HEADERS.contains(key)) { + throw invalidInput(METADATA + " can't include the header " + header + ": it is not allowed"); + } + if (authHeader != null && authHeader.equalsIgnoreCase(header)) { + throw invalidInput(METADATA + " can't include the header " + header + " because it is " + + authHeaderMember); + } + if (!seen.add(key)) { + throw invalidInput(METADATA + " lists the header " + header + + " more than once. Header names are case-insensitive."); + } + } + } + + private static AwsException hmacInvalid(String reason) { + return invalidInput(HMAC_INVALID + reason); + } + + // ──────────────────────────── Forms of the configuration ──────────────────────────── + + /** + * The {@code SecretValue} of an HMAC configuration as stored and checked: with {@code SecretEncoding} BASE64, + * the {@code whsec_} prefix signing tools put on a Base64 secret is removed. Null when none is given. + */ + static String hmacSecretValue(JsonNode hmac) { + JsonNode node = hmac.get("SecretValue"); + if (node == null || !node.isTextual()) { + return null; + } + String value = node.textValue(); + return "BASE64".equals(hmac.path("SecretEncoding").asText(null)) && value.startsWith(WHSEC) + ? value.substring(WHSEC.length()) : value; + } + + /** The authentication type of a webhook configuration, the name of its one authentication member. */ + static String authType(JsonNode webhook) { + List present = presentAuthMembers(webhook.path("AuthConfiguration")); + return present.isEmpty() ? null : present.getFirst(); + } + + /** + * The {@code Configuration} a describe returns for a validated request: as given, less the members the model + * does not declare and the members that hold secrets, and with no member that was sent as null. + */ + static JsonNode echo(JsonNode webhook) { + ObjectNode copy = (ObjectNode) EventBridgeV2RequestShapes.modeled("WebhookEventsSourceConfiguration", webhook); + JsonNode auth = copy.path("AuthConfiguration"); + for (String member : AUTH_MEMBERS) { + if (auth.get(member) instanceof ObjectNode configuration) { + SECRET_MEMBERS.forEach(configuration::remove); + } + } + dropNulls(copy); + ObjectNode configuration = copy.objectNode(); + configuration.set(WEBHOOK, copy); + return configuration; + } + + private static void dropNulls(JsonNode node) { + if (node instanceof ObjectNode object) { + Iterator> fields = object.properties().iterator(); + while (fields.hasNext()) { + Map.Entry field = fields.next(); + if (field.getValue().isNull()) { + fields.remove(); + } else { + dropNulls(field.getValue()); + } + } + } + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private static Set lowerCased(String... names) { + Set set = new HashSet<>(); + for (String name : names) { + set.add(name.toLowerCase(Locale.ROOT)); + } + return Set.copyOf(set); + } + + private static Set withExtras(Set common, String... extras) { + Set set = new HashSet<>(common); + set.addAll(lowerCased(extras)); + return Set.copyOf(set); + } +} diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/WebhookTokens.java b/src/main/java/io/floci/aws/services/eventbridgev2/WebhookTokens.java new file mode 100644 index 0000000000..22a2d4e21d --- /dev/null +++ b/src/main/java/io/floci/aws/services/eventbridgev2/WebhookTokens.java @@ -0,0 +1,47 @@ +package io.floci.aws.services.eventbridgev2; + +import io.floci.aws.core.common.Base64Url; +import io.floci.aws.core.common.Digests; + +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.Arrays; + +/** + * The host id and the path token of a webhook URL. The token holds 32 random bytes and the first 16 bytes of the + * SHA-256 of the host id and those bytes. + */ +final class WebhookTokens { + private static final int HOST_ID_LENGTH = 38; + private static final String TOKEN_PREFIX = "k1"; + + private static final String HOST_ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567"; + private static final int RANDOM_BYTES = 32; + private static final int CHECK_BYTES = 16; + + private WebhookTokens() { + } + + static String newHostId(SecureRandom random) { + StringBuilder id = new StringBuilder(HOST_ID_LENGTH).append('a'); + while (id.length() < HOST_ID_LENGTH) { + id.append(HOST_ID_ALPHABET.charAt(random.nextInt(HOST_ID_ALPHABET.length()))); + } + return id.toString(); + } + + static String newToken(String hostId, SecureRandom random) { + byte[] payload = new byte[RANDOM_BYTES]; + random.nextBytes(payload); + byte[] token = Arrays.copyOf(payload, RANDOM_BYTES + CHECK_BYTES); + System.arraycopy(check(hostId, payload), 0, token, RANDOM_BYTES, CHECK_BYTES); + return TOKEN_PREFIX + Base64Url.encode(token); + } + + private static byte[] check(String hostId, byte[] payload) { + byte[] hostBytes = hostId.getBytes(StandardCharsets.US_ASCII); + byte[] input = Arrays.copyOf(hostBytes, hostBytes.length + payload.length); + System.arraycopy(payload, 0, input, hostBytes.length, payload.length); + return Arrays.copyOf(Digests.sha256(input), CHECK_BYTES); + } +} diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/model/EventSourceV2.java b/src/main/java/io/floci/aws/services/eventbridgev2/model/EventSourceV2.java new file mode 100644 index 0000000000..f3e6fefafd --- /dev/null +++ b/src/main/java/io/floci/aws/services/eventbridgev2/model/EventSourceV2.java @@ -0,0 +1,147 @@ +package io.floci.aws.services.eventbridgev2.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.JsonNode; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * An EventBridge V2 webhook event source. The configuration is kept in the form the source returns it, without + * the credentials, which live in the secret. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class EventSourceV2 { + private String name; + private String arn; + private String eventBusArn; + private String description; + private JsonNode configuration; + private String state; + private Instant creationTime; + private Instant lastModifiedTime; + private Map tags = new LinkedHashMap<>(); + private String clientToken; + private String createRequestHash; + private String webhookHost; + private String webhookToken; + private String secretArn; + + public EventSourceV2() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getArn() { + return arn; + } + + public void setArn(String arn) { + this.arn = arn; + } + + public String getEventBusArn() { + return eventBusArn; + } + + public void setEventBusArn(String eventBusArn) { + this.eventBusArn = eventBusArn; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public JsonNode getConfiguration() { + return configuration; + } + + public void setConfiguration(JsonNode configuration) { + this.configuration = configuration; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public Instant getCreationTime() { + return creationTime; + } + + public void setCreationTime(Instant creationTime) { + this.creationTime = creationTime; + } + + public Instant getLastModifiedTime() { + return lastModifiedTime; + } + + public void setLastModifiedTime(Instant lastModifiedTime) { + this.lastModifiedTime = lastModifiedTime; + } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } + + public String getClientToken() { + return clientToken; + } + + public void setClientToken(String clientToken) { + this.clientToken = clientToken; + } + + public String getCreateRequestHash() { + return createRequestHash; + } + + public void setCreateRequestHash(String createRequestHash) { + this.createRequestHash = createRequestHash; + } + + public String getWebhookHostId() { + return webhookHost; + } + + public void setWebhookHostId(String webhookHost) { + this.webhookHost = webhookHost; + } + + public String getWebhookToken() { + return webhookToken; + } + + public void setWebhookToken(String webhookToken) { + this.webhookToken = webhookToken; + } + + public String getSecretArn() { + return secretArn; + } + + public void setSecretArn(String secretArn) { + this.secretArn = secretArn; + } +} diff --git a/src/main/resources/aws/eventbridgev2-request-shapes.json b/src/main/resources/aws/eventbridgev2-request-shapes.json index 39b9b157f7..997045b529 100644 --- a/src/main/resources/aws/eventbridgev2-request-shapes.json +++ b/src/main/resources/aws/eventbridgev2-request-shapes.json @@ -7,6 +7,7 @@ "CreateEventSource": "CreateEventSourceRequest", "DeleteEventSource": "DeleteEventSourceRequest", "DescribeEventSource": "DescribeEventSourceRequest", + "ListEventSources": "ListEventSourcesRequest", "UpdateEventSource": "UpdateEventSourceRequest" }, "shapes": { @@ -16,9 +17,9 @@ "AwsService" ], "members": { - "AwsService": "AwsServiceSource", "Pattern": "AwsServiceEventsSourceConfigurationPatternString", - "OnFailureConfiguration": "OnFailureConfiguration" + "OnFailureConfiguration": "OnFailureConfiguration", + "AwsService": "AwsServiceSource" } }, "AwsServiceEventsSourceConfigurationPatternString": { @@ -47,12 +48,12 @@ "Configuration" ], "members": { - "Name": "EventSourceName", - "EventBusArn": "EventBusArn", "Configuration": "EventSourceConfiguration", + "ClientToken": "ClientToken", + "Name": "EventSourceName", "Description": "Description", - "Tags": "TagMap", - "ClientToken": "ClientToken" + "EventBusArn": "EventBusArn", + "Tags": "TagMap" } }, "DeadLetterQueueArn": { @@ -101,8 +102,8 @@ "type": "structure", "members": { "AwsServiceEventsConfiguration": "AwsServiceEventsSourceConfiguration", - "PartnerEventsConfiguration": "PartnerEventsSourceConfiguration", - "WebhookEventsConfiguration": "WebhookEventsSourceConfiguration" + "WebhookEventsConfiguration": "WebhookEventsSourceConfiguration", + "PartnerEventsConfiguration": "PartnerEventsSourceConfiguration" } }, "EventSourceName": { @@ -114,8 +115,8 @@ "IncludePayload": { "type": "string", "enum": [ - "FULL", - "ON_ERROR_ONLY" + "ON_ERROR_ONLY", + "FULL" ] }, "KmsKeyIdentifier": { @@ -124,6 +125,15 @@ "max": 2048, "pattern": "[a-zA-Z0-9_\\-/:]*" }, + "ListEventSourcesRequest": { + "type": "structure", + "members": { + "MaxResults": "MaxResults", + "NextToken": "NextToken", + "NamePrefix": "EventSourceName", + "EventBusArn": "EventBusArn" + } + }, "LogConfiguration": { "type": "structure", "members": { @@ -139,6 +149,16 @@ "OFF" ] }, + "MaxResults": { + "type": "integer", + "min": 1, + "max": 100 + }, + "NextToken": { + "type": "string", + "min": 1, + "max": 4096 + }, "OnFailureConfiguration": { "type": "structure", "members": { @@ -157,9 +177,9 @@ "PartnerEventSourceArn" ], "members": { - "PartnerEventSourceArn": "PartnerEventSourceArn", - "Pattern": "PartnerEventsSourceConfigurationPatternString", "PartnerBusKmsKeyIdentifier": "KmsKeyIdentifier", + "Pattern": "PartnerEventsSourceConfigurationPatternString", + "PartnerEventSourceArn": "PartnerEventSourceArn", "OnFailureConfiguration": "OnFailureConfiguration" } }, @@ -200,8 +220,8 @@ "EventSourceArn" ], "members": { - "EventSourceArn": "EventSourceArn", "Configuration": "EventSourceConfiguration", + "EventSourceArn": "EventSourceArn", "Description": "Description" } }, @@ -209,15 +229,15 @@ "type": "structure", "members": { "StaticTokenAuthConfiguration": "WebhookStaticTokenAuthConfiguration", - "BasicHttpAuthConfiguration": "WebhookBasicHttpAuthConfiguration", - "HmacAuthConfiguration": "WebhookHmacAuthConfiguration" + "HmacAuthConfiguration": "WebhookHmacAuthConfiguration", + "BasicHttpAuthConfiguration": "WebhookBasicHttpAuthConfiguration" } }, "WebhookBasicHttpAuthConfiguration": { "type": "structure", "members": { - "Username": "WebhookUsername", - "Password": "WebhookSecretValue" + "Password": "WebhookSecretValue", + "Username": "WebhookUsername" } }, "WebhookDeduplicationConfiguration": { @@ -248,12 +268,12 @@ "RoleArn" ], "members": { - "AuthConfiguration": "WebhookAuthConfiguration", + "DeduplicationConfiguration": "WebhookDeduplicationConfiguration", "KmsKeyIdentifier": "KmsKeyIdentifier", "RoleArn": "RoleArn", + "LogConfiguration": "LogConfiguration", "MetadataHttpHeaders": "WebhookMetadataHttpHeaderList", - "DeduplicationConfiguration": "WebhookDeduplicationConfiguration", - "LogConfiguration": "LogConfiguration" + "AuthConfiguration": "WebhookAuthConfiguration" } }, "WebhookHeaderName": { @@ -278,18 +298,18 @@ "SignedMessageComposition" ], "members": { - "Algorithm": "WebhookHmacAlgorithm", - "Encoding": "WebhookHmacEncoding", - "SignatureHttpHeader": "WebhookHeaderName", + "SecretEncoding": "WebhookSecretEncoding", + "TimestampPrefix": "WebhookTimestampPrefix", + "MessageIdHttpHeader": "WebhookHeaderName", + "SecretValue": "WebhookSecretValue", "SignaturePrefix": "WebhookSignaturePrefix", "Delimiter": "WebhookDelimiter", - "TimestampHttpHeader": "WebhookHeaderName", - "TimestampPrefix": "WebhookTimestampPrefix", - "TimestampToleranceInSeconds": "WebhookTimestampToleranceInSeconds", - "MessageIdHttpHeader": "WebhookHeaderName", "SignedMessageComposition": "WebhookSignedMessageComposition", - "SecretValue": "WebhookSecretValue", - "SecretEncoding": "WebhookSecretEncoding" + "TimestampToleranceInSeconds": "WebhookTimestampToleranceInSeconds", + "SignatureHttpHeader": "WebhookHeaderName", + "Encoding": "WebhookHmacEncoding", + "TimestampHttpHeader": "WebhookHeaderName", + "Algorithm": "WebhookHmacAlgorithm" } }, "WebhookHmacEncoding": { @@ -314,8 +334,8 @@ "WebhookSecretEncoding": { "type": "string", "enum": [ - "BASE64", - "RAW" + "RAW", + "BASE64" ] }, "WebhookSecretValue": { @@ -333,9 +353,9 @@ "WebhookSignedMessageComposition": { "type": "string", "enum": [ + "TIMESTAMP_DOT_BODY", "BODY", - "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY", - "TIMESTAMP_DOT_BODY" + "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY" ] }, "WebhookStaticTokenAuthConfiguration": { @@ -344,8 +364,8 @@ "TokenHttpHeader" ], "members": { - "TokenHttpHeader": "WebhookHeaderName", - "SecretValue": "WebhookSecretValue" + "SecretValue": "WebhookSecretValue", + "TokenHttpHeader": "WebhookHeaderName" } }, "WebhookTimestampPrefix": { diff --git a/src/test/java/io/floci/aws/core/common/RequestConstraintCheckViolationsTest.java b/src/test/java/io/floci/aws/core/common/RequestConstraintCheckViolationsTest.java index a16ee95ccf..8a6e40f8a6 100644 --- a/src/test/java/io/floci/aws/core/common/RequestConstraintCheckViolationsTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestConstraintCheckViolationsTest.java @@ -48,8 +48,20 @@ class RequestConstraintCheckViolationsTest { """; private static final RequestConstraintCheck CHECK = RequestConstraintCheck.of(json(MODEL), + RequestConstraintCheck.standardMessages("InvalidInputException"), + new RequestConstraintCheck.ViolationOrder(true, true)); + + private static final RequestConstraintCheck STANDARD = RequestConstraintCheck.of(json(MODEL), RequestConstraintCheck.standardMessages("InvalidInputException")); + private static final RequestConstraintCheck PATTERN_FIRST = RequestConstraintCheck.of(json(MODEL), + RequestConstraintCheck.standardMessages("InvalidInputException"), + new RequestConstraintCheck.ViolationOrder(true, false)); + + private static final RequestConstraintCheck HASH_ORDER = RequestConstraintCheck.of(json(MODEL), + RequestConstraintCheck.standardMessages("InvalidInputException"), + new RequestConstraintCheck.ViolationOrder(false, true)); + private static final String REQUIRED_OK = "\"Name\": \"abc\", \"Inner\": {\"Leaf\": \"abc\"}"; @Test @@ -82,16 +94,60 @@ class RequestConstraintCheckViolationsTest { } @Test - void stringReportsLengthThenPatternThenEnumEachIndependently() { + void stringReportsPatternThenLengthThenEnumEachIndependently() { 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 'A' at 'name' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-z]+", + "Value 'A' at 'name' failed to satisfy constraint: Member must have length greater than or equal to 2"), 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 standardOrderReportsLengthBeforePattern() { + String request = "{\"Name\": \"A\", \"Inner\": {\"Leaf\": \"abc\"}}"; + String length = "Value 'A' at 'name' failed to satisfy constraint: " + + "Member must have length greater than or equal to 2"; + String pattern = "Value 'A' at 'name' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: [a-z]+"; + + assertEquals(List.of(length, pattern), STANDARD.violations("Put", json(request))); + assertEquals(List.of(length, pattern), HASH_ORDER.violations("Put", json(request))); + assertEquals(List.of(pattern, length), PATTERN_FIRST.violations("Put", json(request))); + assertEquals(List.of(pattern, length), CHECK.violations("Put", json(request))); + } + + @Test + void standardOrderQuotesAMapInRequestOrder() { + String request = "{" + REQUIRED_OK + ", \"Tags\": {\"b\": \"x\", \"a\": \"y\", \"c\": \"z\"}}"; + String text = "Value '%s' at 'tags' failed to satisfy constraint: Member must have length less than or equal to 2"; + + assertEquals(List.of(String.format(text, "{b=x, a=y, c=z}")), STANDARD.violations("Put", json(request))); + assertEquals(List.of(String.format(text, "{b=x, a=y, c=z}")), PATTERN_FIRST.violations("Put", json(request))); + assertEquals(List.of(String.format(text, "{a=y, b=x, c=z}")), HASH_ORDER.violations("Put", json(request))); + assertEquals(List.of(String.format(text, "{a=y, b=x, c=z}")), CHECK.violations("Put", json(request))); + } + + @Test + void modeledKeepsOnlyDeclaredMembersThroughStructuresAndListsOfStructures() { + JsonNode value = json("{\"Items\": [{\"Leaf\": \"a\", \"Extra\": 1}, {\"Other\": \"b\", \"x\": {}}]," + + " \"Unknown\": true}"); + + assertEquals(json("{\"Items\": [{\"Leaf\": \"a\"}, {\"Other\": \"b\"}]}"), + CHECK.modeled("ListyInput", value)); + } + + @Test + void modeledCopiesMapsAndScalarsAsTheyAre() { + JsonNode marks = json("{\"k\": {\"Leaf\": \"a\", \"Extra\": 1}}"); + + assertEquals(marks, CHECK.modeled("Marks", marks)); + assertEquals(json("\"text\""), CHECK.modeled("Name", json("\"text\""))); + assertEquals(json("{\"Name\": \"a\", \"Self\": {\"Name\": \"b\"}}"), + CHECK.modeled("LoopInput", json("{\"Name\": \"a\", \"Self\": {\"Name\": \"b\", \"z\": 1}, \"y\": 2}"))); + } + @Test void stringLengthCountsCodePoints() { String sixEmoji = "\\ud83d\\ude00".repeat(6); @@ -125,10 +181,16 @@ class RequestConstraintCheckViolationsTest { } @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}"))); + void integerThatDoesNotFitTheTypeIsATypeErrorBeforeAnyBound() { + AwsException tooBig = assertThrows(AwsException.class, + () -> CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Count\": 99999999999999999999}"))); + AwsException over32Bits = assertThrows(AwsException.class, + () -> CHECK.violations("Put", json("{" + REQUIRED_OK + ", \"Count\": 4294967297}"))); + + assertEquals("Invalid parameter at 'Count' failed to satisfy constraint: 'Member must be a integer'", + tooBig.getMessage()); + assertEquals("Invalid parameter at 'Count' failed to satisfy constraint: 'Member must be a integer'", + over32Bits.getMessage()); } @Test @@ -220,12 +282,25 @@ class RequestConstraintCheckViolationsTest { } @Test - void mapSizeViolationQuotesTheWholeMapInRequestOrder() { - assertEquals(List.of("Value '{b=x, a=y, c=z}' at 'tags' failed to satisfy constraint: " + void mapSizeViolationQuotesTheWholeMapInTheOrderOfAHashMapSizedForIt() { + assertEquals(List.of("Value '{a=y, b=x, 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 mapIsQuotedInTheOrderOfANewHashMapSizedForItsEntryCount() { + assertEquals(List.of("Value '{ok=v2, lead=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 '{ok=v2, lead=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\": {\" lead\": \"v\", \"ok\": \"v2\"}}"))); + } + @Test void mapKeyThenValueViolationsAreOneEachAndOnlyValuesCarryNotNull() { assertEquals(List.of( @@ -265,8 +340,8 @@ class RequestConstraintCheckViolationsTest { 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 'A' at 'name' failed to satisfy constraint: Member must have length greater than or equal to 2", "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", diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSourceIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSourceIntegrationTest.java new file mode 100644 index 0000000000..2f2157cefd --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSourceIntegrationTest.java @@ -0,0 +1,263 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client; +import software.amazon.awssdk.services.eventbridgev2.model.CreateEventSourceResponse; +import software.amazon.awssdk.services.eventbridgev2.model.DescribeEventSourceResponse; +import software.amazon.awssdk.services.eventbridgev2.model.EventSourceConfiguration; +import software.amazon.awssdk.services.eventbridgev2.model.EventSourceSummary; +import software.amazon.awssdk.services.eventbridgev2.model.InvalidInputException; +import software.amazon.awssdk.services.eventbridgev2.model.ListEventSourcesResponse; +import software.amazon.awssdk.services.eventbridgev2.model.ResourceAlreadyExistsException; +import software.amazon.awssdk.services.eventbridgev2.model.ResourceInUseException; +import software.amazon.awssdk.services.eventbridgev2.model.ResourceNotFoundException; +import software.amazon.awssdk.services.eventbridgev2.model.UpdateEventSourceResponse; +import software.amazon.awssdk.services.eventbridgev2.model.WebhookAuthConfiguration; +import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; +import software.amazon.awssdk.services.secretsmanager.model.DescribeSecretResponse; + +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Webhook event sources of EventBridge V2 and the managed secrets that hold their credentials, through the SDKs. */ +@QuarkusTest +class EventBridgeV2EventSourceIntegrationTest { + + private static final String ROLE = "arn:aws:iam::000000000000:role/WebhookRole"; + private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); + + @BeforeAll + static void configureContentTypes() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aWebhookEventSourceLivesThroughCreateDescribeUpdateAndDelete() { + String suffix = suffix(); + try (EventBridgeV2Client events = events(); SecretsManagerClient secrets = secrets()) { + String bus = events.createEventBus(request -> request.name("v2-src-" + suffix)).eventBusArn(); + + CreateEventSourceResponse created = events.createEventSource(request -> request.name("hook-" + suffix) + .eventBusArn(bus).description("orders webhook").tags(Map.of("team", "orders")) + .configuration(EventSourceConfiguration.fromWebhookEventsConfiguration(webhook -> webhook + .roleArn(ROLE).metadataHttpHeaders("X-Request-Id") + .authConfiguration(staticToken("X-Token", "s3cret-token"))))); + + assertTrue(created.eventSourceArn().matches( + "arn:aws:events:us-east-1:000000000000:event-sourcev2/webhook/hook-" + suffix + "/[a-z0-9]{25}"), + created.eventSourceArn()); + assertEquals(bus, created.eventBusArn()); + assertEquals("ACTIVE", created.stateAsString()); + assertNotNull(created.creationTime()); + String url = created.eventSourceDetails().webhookDetails().webhookUrl(); + assertTrue(url.matches("http://a[a-z2-7]{37}\\.c01\\.events-webhook\\.us-east-1\\..+/k1[A-Za-z0-9_-]{64}/"), + url); + String secretArn = created.eventSourceDetails().webhookDetails().secretArn(); + + assertEquals("s3cret-token", secrets.getSecretValue(request -> request.secretId(secretArn)) + .secretString()); + DescribeSecretResponse secret = secrets.describeSecret(request -> request.secretId(secretArn)); + assertEquals("events-webhook", secret.owningService()); + assertTrue(secret.name().startsWith("events-webhook!"), secret.name()); + + DescribeEventSourceResponse described = events.describeEventSource( + request -> request.eventSourceArn(created.eventSourceArn())); + assertEquals("orders webhook", described.description()); + assertEquals(url, described.eventSourceDetails().webhookDetails().webhookUrl()); + assertEquals(secretArn, described.eventSourceDetails().webhookDetails().secretArn()); + assertEquals(List.of("X-Request-Id"), + described.configuration().webhookEventsConfiguration().metadataHttpHeaders()); + assertNull(described.configuration().webhookEventsConfiguration().authConfiguration() + .staticTokenAuthConfiguration().secretValue()); + assertEquals("X-Token", described.configuration().webhookEventsConfiguration().authConfiguration() + .staticTokenAuthConfiguration().tokenHttpHeader()); + + ListEventSourcesResponse listed = events.listEventSources(request -> request.eventBusArn(bus)); + assertEquals(1, listed.eventSources().size()); + EventSourceSummary summary = listed.eventSources().getFirst(); + assertEquals("WEBHOOK_EVENTS", summary.typeAsString()); + assertEquals("000000000000", summary.eventSourceAccountId()); + assertEquals(0, events.listEventSources(request -> request.eventBusArn(bus).namePrefix("nope")) + .eventSources().size()); + + UpdateEventSourceResponse updated = events.updateEventSource(request -> request + .eventSourceArn(created.eventSourceArn()).description("changed") + .configuration(EventSourceConfiguration.fromWebhookEventsConfiguration(webhook -> webhook + .roleArn(ROLE).authConfiguration(auth -> auth.staticTokenAuthConfiguration( + token -> token.tokenHttpHeader("X-Changed")))))); + assertEquals(created.eventSourceArn(), updated.eventSourceArn()); + DescribeEventSourceResponse afterUpdate = events.describeEventSource( + request -> request.eventSourceArn(created.eventSourceArn())); + assertEquals("changed", afterUpdate.description()); + assertEquals(url, afterUpdate.eventSourceDetails().webhookDetails().webhookUrl()); + assertTrue(afterUpdate.configuration().webhookEventsConfiguration().metadataHttpHeaders().isEmpty()); + assertEquals("s3cret-token", secrets.getSecretValue(request -> request.secretId(secretArn)) + .secretString()); + + ResourceInUseException inUse = assertThrows(ResourceInUseException.class, + () -> events.deleteEventBus(request -> request.eventBusArn(bus))); + assertEquals("The event bus cannot be deleted because it has one or more event sources that are not " + + "revoked. Delete or revoke them and retry.", inUse.awsErrorDetails().errorMessage()); + + events.deleteEventSource(request -> request.eventSourceArn(created.eventSourceArn())); + assertNotNull(secrets.describeSecret(request -> request.secretId(secretArn)).deletedDate()); + assertThrows(ResourceNotFoundException.class, () -> events.describeEventSource( + request -> request.eventSourceArn(created.eventSourceArn()))); + events.deleteEventBus(request -> request.eventBusArn(bus)); + } + } + + @Test + void basicAndHmacSourcesKeepTheirCredentialsInTheSecret() { + String suffix = suffix(); + try (EventBridgeV2Client events = events(); SecretsManagerClient secrets = secrets()) { + String bus = events.createEventBus(request -> request.name("v2-auth-" + suffix)).eventBusArn(); + CreateEventSourceResponse basic = events.createEventSource(request -> request.name("basic-" + suffix) + .eventBusArn(bus).configuration(EventSourceConfiguration.fromWebhookEventsConfiguration( + webhook -> webhook.roleArn(ROLE).authConfiguration(auth -> auth + .basicHttpAuthConfiguration(credential -> credential.username("alice") + .password("p4ssword")))))); + assertEquals("{\"username\":\"alice\",\"password\":\"p4ssword\"}", secrets.getSecretValue( + request -> request.secretId(basic.eventSourceDetails().webhookDetails().secretArn())) + .secretString()); + DescribeEventSourceResponse described = events.describeEventSource( + request -> request.eventSourceArn(basic.eventSourceArn())); + assertNull(described.configuration().webhookEventsConfiguration().authConfiguration() + .basicHttpAuthConfiguration().username()); + + CreateEventSourceResponse hmac = events.createEventSource(request -> request.name("hmac-" + suffix) + .eventBusArn(bus).configuration(EventSourceConfiguration.fromWebhookEventsConfiguration( + webhook -> webhook.roleArn(ROLE).authConfiguration(auth -> auth + .hmacAuthConfiguration(signing -> signing.algorithm("SHA256").encoding("HEX") + .signatureHttpHeader("X-Signature").signedMessageComposition("BODY")))))); + String generated = secrets.getSecretValue( + request -> request.secretId(hmac.eventSourceDetails().webhookDetails().secretArn())) + .secretString(); + assertEquals(44, generated.length()); + + events.deleteEventSource(request -> request.eventSourceArn(basic.eventSourceArn())); + events.deleteEventSource(request -> request.eventSourceArn(hmac.eventSourceArn())); + events.deleteEventBus(request -> request.eventBusArn(bus)); + } + } + + @Test + void errorsCarryTheCodesAndMessagesAwsAnswers() { + String suffix = suffix(); + try (EventBridgeV2Client events = events()) { + String bus = events.createEventBus(request -> request.name("v2-err-" + suffix)).eventBusArn(); + EventSourceConfiguration configuration = EventSourceConfiguration.fromWebhookEventsConfiguration( + webhook -> webhook.roleArn(ROLE).authConfiguration(staticToken("Host", null))); + + InvalidInputException reserved = assertThrows(InvalidInputException.class, () -> events + .createEventSource(request -> request.name("bad-" + suffix).eventBusArn(bus) + .configuration(configuration))); + assertEquals("WebhookEventsConfiguration.AuthConfiguration.StaticTokenAuthConfiguration.TokenHttpHeader " + + "can't be the header Host: it is not allowed. Header names are case-insensitive.", + reserved.awsErrorDetails().errorMessage()); + + InvalidInputException constraint = assertThrows(InvalidInputException.class, () -> events + .createEventSource(request -> request.name("-x").eventBusArn(bus).configuration(configuration))); + assertEquals("1 validation error detected: Value '-x' at 'name' failed to satisfy constraint: Member " + + "must satisfy regular expression pattern: (?!aws\\.)[A-Za-z0-9][\\.\\-_A-Za-z0-9]*", + constraint.awsErrorDetails().errorMessage()); + + String missingBus = bus.replace("v2-err-" + suffix, "v2-none-" + suffix); + ResourceNotFoundException noBus = assertThrows(ResourceNotFoundException.class, + () -> events.listEventSources(request -> request.eventBusArn(missingBus))); + assertEquals("Resource does not exist", noBus.awsErrorDetails().errorMessage()); + + EventSourceConfiguration valid = EventSourceConfiguration.fromWebhookEventsConfiguration( + webhook -> webhook.roleArn(ROLE).authConfiguration(staticToken("X-Token", null))); + String created = events.createEventSource(request -> request.name("dup-" + suffix).eventBusArn(bus) + .configuration(valid)).eventSourceArn(); + ResourceAlreadyExistsException exists = assertThrows(ResourceAlreadyExistsException.class, () -> events + .createEventSource(request -> request.name("dup-" + suffix).eventBusArn(bus) + .configuration(valid))); + assertEquals("Resource already exists", exists.awsErrorDetails().errorMessage()); + + String missing = created.replace("dup-" + suffix, "none-" + suffix); + ResourceNotFoundException notFound = assertThrows(ResourceNotFoundException.class, + () -> events.describeEventSource(request -> request.eventSourceArn(missing))); + assertEquals("EventSource not found: " + missing, notFound.awsErrorDetails().errorMessage()); + + events.deleteEventSource(request -> request.eventSourceArn(created)); + events.deleteEventBus(request -> request.eventBusArn(bus)); + } + } + + @Test + void aSourceWhoseSecretIsAlreadyScheduledForDeletionCanBeDeleted() { + String suffix = suffix(); + try (EventBridgeV2Client events = events(); SecretsManagerClient secrets = secrets()) { + String bus = events.createEventBus(request -> request.name("v2-sched-" + suffix)).eventBusArn(); + CreateEventSourceResponse created = events.createEventSource(request -> request.name("sched-" + suffix) + .eventBusArn(bus).configuration(EventSourceConfiguration.fromWebhookEventsConfiguration( + webhook -> webhook.roleArn(ROLE).authConfiguration(staticToken("X-Token", null))))); + String secretArn = created.eventSourceDetails().webhookDetails().secretArn(); + + secrets.deleteSecret(request -> request.secretId(secretArn)); + events.deleteEventSource(request -> request.eventSourceArn(created.eventSourceArn())); + + assertNotNull(secrets.describeSecret(request -> request.secretId(secretArn)).deletedDate()); + assertThrows(ResourceNotFoundException.class, () -> events.describeEventSource( + request -> request.eventSourceArn(created.eventSourceArn()))); + events.deleteEventBus(request -> request.eventBusArn(bus)); + } + } + + @Test + void aMemberOfTheWrongTypeIsASerializationExceptionWithNoMessage() throws Exception { + ObjectNode body = CBOR_MAPPER.createObjectNode().put("Name", 5); + + byte[] answer = given() + .contentType("application/cbor") + .accept("application/cbor") + .header("smithy-protocol", "rpc-v2-cbor") + .body(CBOR_MAPPER.writeValueAsBytes(body)) + .when() + .post("/service/AWSEventsV2/operation/CreateEventSource") + .then() + .statusCode(400) + .header("smithy-protocol", equalTo("rpc-v2-cbor")) + .extract().asByteArray(); + + JsonNode error = CBOR_MAPPER.readTree(answer); + assertEquals("SerializationException", error.path("__type").asText()); + assertNull(error.path("message").textValue()); + } + + private static WebhookAuthConfiguration staticToken(String header, String secretValue) { + return WebhookAuthConfiguration.builder().staticTokenAuthConfiguration( + token -> token.tokenHttpHeader(header).secretValue(secretValue)).build(); + } + + private static EventBridgeV2Client events() { + return AwsTestClients.create(EventBridgeV2Client.builder(), "000000000000", Region.US_EAST_1); + } + + private static SecretsManagerClient secrets() { + return AwsTestClients.create(SecretsManagerClient.builder(), "000000000000", Region.US_EAST_1); + } + + private static String suffix() { + return Long.toString(System.nanoTime(), 36); + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSourcesTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSourcesTest.java new file mode 100644 index 0000000000..b7dde24649 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSourcesTest.java @@ -0,0 +1,853 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.PaginatedResult; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.eventbridgev2.model.EventBusV2; +import io.floci.aws.services.eventbridgev2.model.EventSourceV2; +import io.floci.aws.services.secretsmanager.SecretsManagerService; +import io.floci.aws.services.secretsmanager.model.Secret; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class EventBridgeV2EventSourcesTest { + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final Instant NOW = Instant.parse("2026-11-20T12:00:00Z"); + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String ROLE = "arn:aws:iam::000000000000:role/Hook"; + private static final String STATIC_AUTH = "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Token\"}}"; + private static final String BASIC_AUTH = "{\"BasicHttpAuthConfiguration\":{}}"; + + private SecretsManagerService secrets; + private EventBridgeV2Service service; + private TestClock clock; + private String bus; + + @BeforeEach + void setUp() { + secrets = mock(SecretsManagerService.class); + when(secrets.createSecret(any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(call -> { + Secret secret = new Secret(); + secret.setArn("arn:aws:secretsmanager:us-east-1:000000000000:secret:" + call.getArgument(0) + "-AbCdEf"); + return secret; + }); + when(secrets.describeSecret(any(), any())).thenReturn(new Secret()); + clock = new TestClock(NOW); + RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); + EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources( + AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, "http://floci.test:4566"); + service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT), + AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, mock(EventBridgeV2Delivery.class), + eventSources, clock, true); + bus = bus("orders"); + } + + // ──────────────────────────── Create ──────────────────────────── + + @Test + void createMintsAnActiveSourceWithAnArnAndAWebhookUrl() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + + assertTrue(source.getArn().matches( + "arn:aws:events:us-east-1:000000000000:event-sourcev2/webhook/hook/[a-z0-9]{25}"), source.getArn()); + assertEquals(bus, source.getEventBusArn()); + assertEquals("ACTIVE", source.getState()); + assertEquals(NOW, source.getCreationTime()); + assertEquals(NOW, source.getLastModifiedTime()); + String url = service.webhookUrl(source); + String host = "[a-z][a-z2-7]{37}\\.c01\\.events-webhook\\.us-east-1\\.floci\\.test:4566"; + assertTrue(url.matches("http://" + host + "/k1[A-Za-z0-9_-]{64}/"), url); + assertTrue(source.getWebhookHostId().startsWith("a")); + } + + @Test + void createKeepsTheSecretOutOfTheStoredConfiguration() { + EventSourceV2 source = service.createEventSource(create("hook", bus, + "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Token\",\"SecretValue\":\"s3cret!!\"}}"), + REGION); + assertEquals(json("{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + STATIC_AUTH + + ",\"RoleArn\":\"" + ROLE + "\"}}"), source.getConfiguration()); + } + + @Test + void createStoresTheGivenStaticTokenInAManagedSecret() { + EventSourceV2 source = service.createEventSource(create("hook", bus, + "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Token\",\"SecretValue\":\"s3cret!!\"}}"), + REGION); + + ArgumentCaptor name = ArgumentCaptor.forClass(String.class); + ArgumentCaptor secretString = ArgumentCaptor.forClass(String.class); + ArgumentCaptor> tags = ArgumentCaptor.captor(); + verify(secrets).createSecret(name.capture(), secretString.capture(), isNull(), isNull(), isNull(), + tags.capture(), eq("events-webhook"), eq(REGION)); + assertTrue(name.getValue().matches("events-webhook![0-9a-f-]{36}"), name.getValue()); + assertEquals("s3cret!!", secretString.getValue()); + assertEquals(List.of(new Secret.Tag("aws:secretsmanager:owningService", "events-webhook")), tags.getValue()); + assertTrue(source.getSecretArn().contains(name.getValue())); + } + + @Test + void createGeneratesA44CharacterStaticToken() { + service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + String generated = capturedSecretString(); + assertEquals(44, generated.length()); + assertEquals(32, Base64.getDecoder().decode(generated).length); + } + + @Test + void createStoresBasicCredentialsAsACompactJsonObject() { + service.createEventSource(create("hook", bus, "{\"BasicHttpAuthConfiguration\":{\"Username\":\"user\"," + + "\"Password\":\"p4ssword\"}}"), REGION); + assertEquals("{\"username\":\"user\",\"password\":\"p4ssword\"}", capturedSecretString()); + } + + @Test + void createGeneratesBothBasicCredentialsWhenNeitherIsGiven() throws Exception { + service.createEventSource(create("hook", bus, BASIC_AUTH), REGION); + String secretString = capturedSecretString(); + assertTrue(secretString.matches("\\{\"username\":\"[A-Za-z0-9+/]{43}=\",\"password\":\"[A-Za-z0-9+/]{43}=\"}"), + secretString); + assertEquals(List.of("username", "password"), MAPPER.readTree(secretString).properties().stream().map(Map.Entry::getKey).toList()); + } + + @Test + void createStripsTheWhsecPrefixOnlyForABase64HmacSecret() { + String hmac = "\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"SignatureHttpHeader\":\"X-Sig\"," + + "\"SignedMessageComposition\":\"BODY\","; + service.createEventSource(create("base64", bus, "{\"HmacAuthConfiguration\":{" + hmac + + "\"SecretEncoding\":\"BASE64\",\"SecretValue\":\"whsec_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"}}"), + REGION); + service.createEventSource(create("raw", bus, "{\"HmacAuthConfiguration\":{" + hmac + + "\"SecretEncoding\":\"RAW\",\"SecretValue\":\"whsec_0123456789abcdef\"}}"), REGION); + service.createEventSource(create("none", bus, "{\"HmacAuthConfiguration\":{" + hmac + + "\"SecretValue\":\"whsec_0123456789abcdef\"}}"), REGION); + service.createEventSource(create("generated", bus, "{\"HmacAuthConfiguration\":{" + hmac.substring(0, + hmac.length() - 1) + "}}"), REGION); + + ArgumentCaptor secretString = ArgumentCaptor.forClass(String.class); + verify(secrets, times(4)).createSecret(any(), secretString.capture(), any(), any(), any(), any(), any(), + any()); + List values = secretString.getAllValues(); + assertEquals("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", values.get(0)); + assertEquals("whsec_0123456789abcdef", values.get(1)); + assertEquals("whsec_0123456789abcdef", values.get(2)); + assertEquals(44, values.get(3).length()); + } + + @Test + void createChecksConstraintsFirstAndReportsThemTogether() { + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(json( + "{\"Name\":\"-x\",\"EventBusArn\":\"nope\",\"Configuration\":{}}"), REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + assertTrue(e.getMessage().startsWith("2 validation errors detected: Value '-x' at 'name'"), e.getMessage()); + } + + @Test + void createRefusesABusOfAnotherRegionBeforeAnotherAccount() { + String otherRegion = "arn:aws:events:eu-west-1:111111111111:event-busv2/orders/abcdefghijklmnopqrstuvwxy"; + AwsException e = assertThrows(AwsException.class, + () -> service.createEventSource(create("hook", otherRegion, STATIC_AUTH), REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals("The region or partition in EventBusArn does not match this endpoint", e.getMessage()); + } + + @Test + void createRefusesABusOrARoleOfAnotherAccount() { + String otherAccount = "arn:aws:events:us-east-1:111111111111:event-busv2/orders/abcdefghijklmnopqrstuvwxy"; + AwsException bus = assertThrows(AwsException.class, + () -> service.createEventSource(create("hook", otherAccount, STATIC_AUTH), REGION)); + assertEquals("AccessDeniedException", bus.getErrorCode()); + assertEquals(403, bus.getHttpStatus()); + assertEquals("Access denied.", bus.getMessage()); + + JsonNode foreignRole = json(create("hook", this.bus, STATIC_AUTH).toString().replace(ROLE, + "arn:aws:iam::111111111111:role/Hook")); + AwsException role = assertThrows(AwsException.class, () -> service.createEventSource(foreignRole, REGION)); + assertEquals("AccessDeniedException", role.getErrorCode()); + } + + @Test + void createAcceptsARoleThatDoesNotExist() { + service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + } + + @Test + void createChecksTheRulesBeforeLookingForTheBus() { + String missing = "arn:aws:events:us-east-1:000000000000:event-busv2/missing/abcdefghijklmnopqrstuvwxy"; + AwsException e = assertThrows(AwsException.class, + () -> service.createEventSource(create("hook", missing, "{}"), REGION)); + assertTrue(e.getMessage().startsWith("WebhookEventsConfiguration.AuthConfiguration must set exactly one"), + e.getMessage()); + AwsException notFound = assertThrows(AwsException.class, + () -> service.createEventSource(create("hook", missing, STATIC_AUTH), REGION)); + assertEquals("ResourceNotFoundException", notFound.getErrorCode()); + assertEquals(404, notFound.getHttpStatus()); + assertEquals("Resource does not exist", notFound.getMessage()); + } + + @Test + void createNamesTheBusWhenOnlyTheIdInItsArnDiffers() { + String otherId = bus.substring(0, bus.lastIndexOf('/') + 1) + "zzzzzzzzzzzzzzzzzzzzzzzzz"; + AwsException e = assertThrows(AwsException.class, + () -> service.createEventSource(create("hook", otherId, STATIC_AUTH), REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + assertEquals(404, e.getHttpStatus()); + assertEquals("Event bus not found: orders", e.getMessage()); + } + + @Test + void createRefusesAnotherVariantWithFlociOwnWording() { + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(json( + "{\"Name\":\"hook\",\"ClientToken\":\"t\",\"EventBusArn\":\"" + bus + "\",\"Configuration\":" + + "{\"AwsServiceEventsConfiguration\":{\"AwsService\":\"aws.s3\"}}}"), REGION)); + assertEquals("Only WebhookEventsConfiguration event sources are supported.", e.getMessage()); + } + + @Test + void createWithoutAClientTokenIsRefusedBeforeTheSemanticRules() { + ObjectNode request = create("hook", bus, "{\"BasicHttpAuthConfiguration\":{\"Username\":\"u\"}}"); + request.remove("ClientToken"); + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(request, REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + assertEquals("ClientToken is required", e.getMessage()); + } + + @Test + void createChecksTheAccountBeforeTheClientToken() { + String otherAccount = "arn:aws:events:us-east-1:111111111111:event-busv2/orders/abcdefghijklmnopqrstuvwxy"; + ObjectNode request = create("hook", otherAccount, STATIC_AUTH); + request.remove("ClientToken"); + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(request, REGION)); + assertEquals("AccessDeniedException", e.getErrorCode()); + assertEquals(403, e.getHttpStatus()); + } + + @Test + void createChecksTheRegionAndTheConstraintsBeforeTheClientToken() { + String otherRegion = "arn:aws:events:eu-west-1:000000000000:event-busv2/orders/abcdefghijklmnopqrstuvwxy"; + ObjectNode regionRequest = create("hook", otherRegion, STATIC_AUTH); + regionRequest.remove("ClientToken"); + assertEquals("The region or partition in EventBusArn does not match this endpoint", + assertThrows(AwsException.class, () -> service.createEventSource(regionRequest, REGION)).getMessage()); + + ObjectNode constraintRequest = create("bad name", bus, STATIC_AUTH); + constraintRequest.remove("ClientToken"); + assertEquals("1 validation error detected: Value 'bad name' at 'name' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: (?!aws\\.)[A-Za-z0-9][\\.\\-_A-Za-z0-9]*", + assertThrows(AwsException.class, () -> service.createEventSource(constraintRequest, REGION)) + .getMessage()); + } + + @Test + void createWithNoVariantAndNoClientTokenNamesTheClientToken() { + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(json( + "{\"Name\":\"hook\",\"EventBusArn\":\"" + bus + "\",\"Configuration\":{}}"), REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals("ClientToken is required", e.getMessage()); + } + + @Test + void createWithTwoVariantsAndNoClientTokenNamesTheClientToken() { + ObjectNode request = (ObjectNode) twoVariants(bus); + request.remove("ClientToken"); + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(request, REGION)); + assertEquals("ClientToken is required", e.getMessage()); + } + + @Test + void createWithTwoVariantsAndAClientTokenNamesTheSubField() { + assertExactlyOne(twoVariants(bus)); + } + + @Test + void createWithNoVariantAndAClientTokenNamesTheSubField() { + assertExactlyOne(json("{\"Name\":\"hook\",\"ClientToken\":\"t\",\"EventBusArn\":\"" + bus + + "\",\"Configuration\":{}}")); + } + + @Test + void createWithAnyVariantCountOnABusOfAnotherAccountIsAccessDenied() { + String otherAccount = "arn:aws:events:us-east-1:111111111111:event-busv2/orders/abcdefghijklmnopqrstuvwxy"; + JsonNode none = json("{\"Name\":\"hook\",\"ClientToken\":\"t\",\"EventBusArn\":\"" + otherAccount + + "\",\"Configuration\":{}}"); + for (JsonNode request : List.of(twoVariants(otherAccount), none)) { + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(request, REGION)); + assertEquals("AccessDeniedException", e.getErrorCode()); + assertEquals(403, e.getHttpStatus()); + assertEquals("Access denied.", e.getMessage()); + } + } + + private void assertExactlyOne(JsonNode request) { + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(request, REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + assertEquals("Exactly one Configuration sub-field must be provided", e.getMessage()); + } + + @Test + void createWithAUsedNameFailsInEveryBusOfTheRegionOnly() { + service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + String other = bus("payments"); + AwsException e = assertThrows(AwsException.class, + () -> service.createEventSource(create("hook", other, STATIC_AUTH), REGION)); + assertEquals("ResourceAlreadyExistsException", e.getErrorCode()); + assertEquals(409, e.getHttpStatus()); + assertEquals("Resource already exists", e.getMessage()); + verify(secrets, times(1)).createSecret(any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void createRetriedWithItsClientTokenReturnsTheSameSource() { + JsonNode request = create("hook", bus, STATIC_AUTH, "\"ClientToken\":\"t-1\""); + EventSourceV2 first = service.createEventSource(request, REGION); + EventSourceV2 retried = service.createEventSource(request, REGION); + assertEquals(first.getArn(), retried.getArn()); + verify(secrets, times(1)).createSecret(any(), any(), any(), any(), any(), any(), any(), any()); + assertEquals(first.getCreateRequestHash(), retried.getCreateRequestHash()); + } + + @Test + void createRetriedWithAnotherRequestIsAnIdempotentParameterMismatch() { + service.createEventSource(create("hook", bus, STATIC_AUTH, "\"ClientToken\":\"t-1\""), REGION); + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource( + create("hook", bus, STATIC_AUTH, "\"ClientToken\":\"t-1\",\"Description\":\"changed\""), REGION)); + assertEquals("IdempotentParameterMismatchException", e.getErrorCode()); + assertEquals(409, e.getHttpStatus()); + assertEquals("ClientToken was used by a previous request with different parameters", e.getMessage()); + } + + @Test + void createKeepsOnlyAHashOfTheRequestThatCarriesSecrets() { + EventSourceV2 source = service.createEventSource(create("hook", bus, + "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Token\",\"SecretValue\":\"s3cret!!\"}}", + "\"ClientToken\":\"t-1\""), REGION); + assertFalse(source.getCreateRequestHash().contains("s3cret")); + } + + @Test + void createDeletesItsSecretWhenTheSourceCannotBeStored() { + AccountAwareStorageBackend failing = spy( + AccountAwareStorageBackend.inMemory(ACCOUNT)); + IllegalStateException failure = new IllegalStateException("disk full"); + doThrow(failure).when(failing).put(any(), any()); + EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources(failing, secrets, + new RegionResolver(REGION, ACCOUNT), clock, "http://floci.test:4566"); + + EventBusV2 existing = new EventBusV2(); + existing.setArn(bus); + IllegalStateException e = assertThrows(IllegalStateException.class, () -> eventSources.create( + create("hook", bus, STATIC_AUTH), REGION, name -> Optional.of(existing))); + + assertSame(failure, e); + ArgumentCaptor secretName = ArgumentCaptor.forClass(String.class); + verify(secrets).createSecret(secretName.capture(), any(), any(), any(), any(), any(), any(), any()); + verify(secrets).deleteSecret( + eq("arn:aws:secretsmanager:us-east-1:000000000000:secret:" + secretName.getValue() + "-AbCdEf"), + isNull(), eq(true), eq(REGION)); + } + + // ──────────────────────────── Describe ──────────────────────────── + + @Test + void describeFindsASourceByItsArnAndChecksTheArn() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + assertEquals(source.getArn(), service.describeEventSource(arn(source.getArn()), REGION).getArn()); + + String missing = source.getArn().replace("/hook/", "/gone/"); + AwsException notFound = assertThrows(AwsException.class, + () -> service.describeEventSource(arn(missing), REGION)); + assertEquals("ResourceNotFoundException", notFound.getErrorCode()); + assertEquals("EventSource not found: " + missing, notFound.getMessage()); + + String otherRegion = source.getArn().replace("us-east-1", "eu-west-1"); + assertEquals("The region or partition in EventSourceArn does not match this endpoint", assertThrows( + AwsException.class, () -> service.describeEventSource(arn(otherRegion), REGION)).getMessage()); + + String otherAccount = source.getArn().replace(ACCOUNT, "111111111111"); + AwsException denied = assertThrows(AwsException.class, + () -> service.describeEventSource(arn(otherAccount), REGION)); + assertEquals("AccessDeniedException", denied.getErrorCode()); + assertEquals(403, denied.getHttpStatus()); + + AwsException invalid = assertThrows(AwsException.class, + () -> service.describeEventSource(arn("nope"), REGION)); + assertTrue(invalid.getMessage().startsWith("1 validation error detected: Value 'nope' at 'eventSourceArn'"), + invalid.getMessage()); + } + + // ──────────────────────────── List ──────────────────────────── + + @Test + void listIsOrderedByTheIdInTheArnAndFiltersByBusAndNamePrefix() { + String other = bus("payments"); + for (String name : List.of("a-one", "b-two", "a-three")) { + service.createEventSource(create(name, bus, STATIC_AUTH), REGION); + } + service.createEventSource(create("a-four", other, STATIC_AUTH), REGION); + + List all = service.listEventSources(json("{}"), REGION).items(); + assertEquals(4, all.size()); + List ids = all.stream().map(EventBridgeV2EventSources::id).toList(); + assertEquals(ids.stream().sorted().toList(), ids); + + assertEquals(Set.of("a-one", "b-two", "a-three"), names(service.listEventSources( + json("{\"EventBusArn\":\"" + bus + "\"}"), REGION))); + assertEquals(Set.of("a-one", "a-three", "a-four"), names(service.listEventSources( + json("{\"NamePrefix\":\"a-\"}"), REGION))); + assertEquals(Set.of("a-one", "a-three"), names(service.listEventSources( + json("{\"NamePrefix\":\"a-\",\"EventBusArn\":\"" + bus + "\"}"), REGION))); + assertEquals(Set.of(), names(service.listEventSources(json("{}"), "eu-west-1"))); + } + + @Test + void listPagesWithMaxResultsAndNextToken() { + for (String name : List.of("one", "two", "three")) { + service.createEventSource(create(name, bus, STATIC_AUTH), REGION); + } + PaginatedResult first = service.listEventSources(json("{\"MaxResults\":2}"), REGION); + assertEquals(2, first.items().size()); + PaginatedResult second = service.listEventSources( + json("{\"MaxResults\":2,\"NextToken\":\"" + first.nextToken() + "\"}"), REGION); + assertEquals(1, second.items().size()); + assertNull(second.nextToken()); + } + + @Test + void listForABusThatDoesNotExistFails() { + AwsException e = assertThrows(AwsException.class, () -> service.listEventSources(json( + "{\"EventBusArn\":\"arn:aws:events:us-east-1:000000000000:event-busv2/none/abcdefghijklmnopqrstuvwxy\"}"), + REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + assertEquals(404, e.getHttpStatus()); + assertEquals("Resource does not exist", e.getMessage()); + } + + @Test + void listForABusOfAnotherAccountDoesNotExistEvenWhenTheNameIsOurs() { + AwsException e = assertThrows(AwsException.class, () -> service.listEventSources(json( + "{\"EventBusArn\":\"arn:aws:events:us-east-1:111111111111:event-busv2/orders/abcdefghijklmnopqrstuvwxy\"}"), + REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + assertEquals(404, e.getHttpStatus()); + assertEquals("Resource does not exist", e.getMessage()); + } + + @Test + void listNamesTheBusWhenOnlyTheIdInItsArnDiffers() { + String otherId = bus.substring(0, bus.lastIndexOf('/') + 1) + "zzzzzzzzzzzzzzzzzzzzzzzzz"; + AwsException e = assertThrows(AwsException.class, + () -> service.listEventSources(json("{\"EventBusArn\":\"" + otherId + "\"}"), REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + assertEquals(404, e.getHttpStatus()); + assertEquals("Event bus not found: orders", e.getMessage()); + } + + @Test + void listChecksConstraintsThenTheRegionThenTheTokenThenTheBus() { + String missing = "arn:aws:events:us-east-1:000000000000:event-busv2/none/abcdefghijklmnopqrstuvwxy"; + String otherRegion = "arn:aws:events:eu-west-1:000000000000:event-busv2/none/abcdefghijklmnopqrstuvwxy"; + + AwsException constraint = assertThrows(AwsException.class, () -> service.listEventSources(json( + "{\"MaxResults\":0,\"NextToken\":\"garbage\",\"EventBusArn\":\"" + otherRegion + "\"}"), REGION)); + assertEquals("1 validation error detected: Value '0' at 'maxResults' failed to satisfy constraint: " + + "Member must have value greater than or equal to 1", constraint.getMessage()); + + AwsException region = assertThrows(AwsException.class, () -> service.listEventSources(json( + "{\"NextToken\":\"garbage\",\"EventBusArn\":\"" + otherRegion + "\"}"), REGION)); + assertEquals("InvalidInputException", region.getErrorCode()); + assertEquals("The region or partition in EventBusArn does not match this endpoint", region.getMessage()); + + AwsException token = assertThrows(AwsException.class, () -> service.listEventSources(json( + "{\"NextToken\":\"garbage\",\"EventBusArn\":\"" + missing + "\"}"), REGION)); + assertEquals("InvalidInputException", token.getErrorCode()); + assertEquals(400, token.getHttpStatus()); + assertEquals("Invalid nextToken", token.getMessage()); + } + + @Test + void listRefusesATokenOfAnotherListing() { + service.createEventBus(json("{\"Name\":\"extra\"}"), REGION); + String busToken = service.listEventBuses(json("{\"MaxResults\":1}"), REGION).nextToken(); + AwsException e = assertThrows(AwsException.class, () -> service.listEventSources( + json("{\"NextToken\":\"" + busToken + "\"}"), REGION)); + assertEquals("Invalid nextToken", e.getMessage()); + } + + @Test + void listTokenKeepsWorkingWithTheSameFilters() { + for (String name : List.of("a-one", "a-two", "a-three")) { + service.createEventSource(create(name, bus, STATIC_AUTH), REGION); + } + String filters = "\"EventBusArn\":\"" + bus + "\",\"NamePrefix\":\"a-\",\"MaxResults\":2"; + PaginatedResult first = service.listEventSources(json("{" + filters + "}"), REGION); + + PaginatedResult second = service.listEventSources( + json("{" + filters + ",\"NextToken\":\"" + first.nextToken() + "\"}"), REGION); + + assertEquals(1, second.items().size()); + } + + @Test + void listRefusesATokenOfAListingWithOtherFilters() { + for (String name : List.of("a-one", "a-two", "a-three")) { + service.createEventSource(create(name, bus, STATIC_AUTH), REGION); + } + String token = service.listEventSources(json("{\"NamePrefix\":\"a-\",\"MaxResults\":1}"), REGION) + .nextToken(); + String withBusToken = service.listEventSources(json("{\"EventBusArn\":\"" + bus + "\",\"MaxResults\":1}"), + REGION).nextToken(); + String unfilteredToken = service.listEventSources(json("{\"MaxResults\":1}"), REGION).nextToken(); + + for (String request : List.of( + "{\"NamePrefix\":\"b-\",\"NextToken\":\"" + token + "\"}", + "{\"NamePrefix\":\"a-\",\"EventBusArn\":\"" + bus + "\",\"NextToken\":\"" + token + "\"}", + "{\"EventBusArn\":\"" + bus + "\",\"NamePrefix\":\"a-\",\"NextToken\":\"" + withBusToken + "\"}", + "{\"NamePrefix\":\"a-\",\"NextToken\":\"" + unfilteredToken + "\"}")) { + AwsException e = assertThrows(AwsException.class, () -> service.listEventSources(json(request), REGION), + request); + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals("Invalid nextToken", e.getMessage()); + } + } + + @Test + void listRefusesATokenOfAnotherRegion() { + for (String name : List.of("a-one", "a-two")) { + service.createEventSource(create(name, bus, STATIC_AUTH), REGION); + } + String token = service.listEventSources(json("{\"MaxResults\":1}"), REGION).nextToken(); + + AwsException e = assertThrows(AwsException.class, () -> service.listEventSources( + json("{\"NextToken\":\"" + token + "\"}"), "eu-west-1")); + + assertEquals("Invalid nextToken", e.getMessage()); + } + + @Test + void createDoesNotKeepMembersTheModelDoesNotDeclare() { + EventSourceV2 source = service.createEventSource(create("hook", bus, + "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Token\",\"secretValue\":\"s3cret!!\"," + + "\"password\":\"p\"},\"Extra\":1}").deepCopy(), REGION); + ObjectNode withExtra = create("hook2", bus, STATIC_AUTH); + ((ObjectNode) withExtra.path("Configuration").path("WebhookEventsConfiguration")).put("Unknown", "x"); + + EventSourceV2 other = service.createEventSource(withExtra, REGION); + + assertEquals(json("{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + STATIC_AUTH + + ",\"RoleArn\":\"" + ROLE + "\"}}"), source.getConfiguration()); + assertEquals(source.getConfiguration(), other.getConfiguration()); + } + + @Test + void updateDoesNotKeepMembersTheModelDoesNotDeclare() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + + EventSourceV2 updated = service.updateEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + + "\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + + "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Token\",\"secretValue\":\"s\"," + + "\"password\":\"p\"}},\"RoleArn\":\"" + ROLE + "\",\"Unknown\":true}}}"), REGION); + + assertEquals(json("{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + STATIC_AUTH + + ",\"RoleArn\":\"" + ROLE + "\"}}"), updated.getConfiguration()); + } + + // ──────────────────────────── Update ──────────────────────────── + + @Test + void updateWithNothingStillMovesTheModifiedTime() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + clock.advance(Duration.ofMinutes(5)); + EventSourceV2 updated = service.updateEventSource(arn(source.getArn()), REGION); + assertEquals(NOW, updated.getCreationTime()); + assertEquals(NOW.plus(Duration.ofMinutes(5)), updated.getLastModifiedTime()); + } + + @Test + void updateStoresANewSourceAndLeavesTheOneAReaderHeldUnchanged() { + EventSourceV2 held = service.createEventSource(create("hook", bus, STATIC_AUTH, + "\"Description\":\"first\""), REGION); + clock.advance(Duration.ofMinutes(5)); + + EventSourceV2 updated = service.updateEventSource(json("{\"EventSourceArn\":\"" + held.getArn() + + "\",\"Description\":\"second\"}"), REGION); + + assertEquals("first", held.getDescription()); + assertEquals(NOW, held.getLastModifiedTime()); + assertEquals("second", updated.getDescription()); + assertEquals(held.getSecretArn(), updated.getSecretArn()); + assertEquals(service.webhookUrl(held), service.webhookUrl(updated)); + } + + @Test + void updateReplacesTheDescriptionAndKeepsItWhenLeftOut() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH, + "\"Description\":\"first\""), REGION); + service.updateEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\",\"Description\":\"second\"}"), + REGION); + assertEquals("second", service.describeEventSource(arn(source.getArn()), REGION).getDescription()); + service.updateEventSource(arn(source.getArn()), REGION); + assertEquals("second", service.describeEventSource(arn(source.getArn()), REGION).getDescription()); + } + + @Test + void updateReplacesTheWholeConfigurationAndKeepsTheSecretAndUrl() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH, + "\"Tags\":{\"a\":\"b\"}").deepCopy().put("Description", "d"), REGION); + String url = service.webhookUrl(source); + String secretArn = source.getSecretArn(); + JsonNode request = json("{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":" + + "{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":" + + "{\"TokenHttpHeader\":\"X-Other\"}},\"RoleArn\":\"" + ROLE + "2\",\"MetadataHttpHeaders\":[\"X-A\"]}}}"); + + EventSourceV2 updated = service.updateEventSource(request, REGION); + + assertEquals(json("{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":" + + "{\"TokenHttpHeader\":\"X-Other\"}},\"RoleArn\":\"" + ROLE + "2\",\"MetadataHttpHeaders\":[\"X-A\"]}}"), + updated.getConfiguration()); + assertEquals(url, service.webhookUrl(updated)); + assertEquals(secretArn, updated.getSecretArn()); + assertEquals("d", updated.getDescription()); + verify(secrets, times(1)).createSecret(any(), any(), any(), any(), any(), any(), any(), any()); + + service.updateEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":" + + "{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":" + + "{\"TokenHttpHeader\":\"X-Other\"}},\"RoleArn\":\"" + ROLE + "\"}}}"), REGION); + assertNull(service.describeEventSource(arn(source.getArn()), REGION).getConfiguration() + .path("WebhookEventsConfiguration").get("MetadataHttpHeaders")); + } + + @Test + void aRefusedUpdateChangesNothing() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + clock.advance(Duration.ofMinutes(1)); + JsonNode before = source.getConfiguration().deepCopy(); + AwsException e = assertThrows(AwsException.class, () -> service.updateEventSource(json( + "{\"EventSourceArn\":\"" + source.getArn() + "\",\"Description\":\"changed\",\"Configuration\":" + + "{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + BASIC_AUTH + ",\"RoleArn\":\"" + + ROLE + "\"}}}"), REGION)); + assertEquals("The webhook authentication type can't be changed after the EventSource is created", + e.getMessage()); + EventSourceV2 stored = service.describeEventSource(arn(source.getArn()), REGION); + assertEquals(before, stored.getConfiguration()); + assertNull(stored.getDescription()); + assertEquals(NOW, stored.getLastModifiedTime()); + } + + @Test + void updateRefusesCredentialsAndRequiresTheRequiredMembers() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + AwsException secret = assertThrows(AwsException.class, () -> service.updateEventSource(json( + "{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":{\"WebhookEventsConfiguration\":" + + "{\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Token\"," + + "\"SecretValue\":\"another-secret\"}},\"RoleArn\":\"" + ROLE + "\"}}}"), REGION)); + assertTrue(secret.getMessage().startsWith("UpdateEventSource does not accept SecretValue")); + AwsException missing = assertThrows(AwsException.class, () -> service.updateEventSource(json( + "{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":{\"WebhookEventsConfiguration\":" + + "{}}}"), REGION)); + assertTrue(missing.getMessage().startsWith("2 validation errors detected: Value null at "), missing.getMessage()); + } + + // ──────────────────────────── Delete ──────────────────────────── + + @Test + void deleteSchedulesTheSecretForDeletionAndRemovesTheSource() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + service.deleteEventSource(arn(source.getArn()), REGION); + + verify(secrets).deleteSecret(source.getSecretArn(), null, false, REGION); + assertThrows(AwsException.class, () -> service.describeEventSource(arn(source.getArn()), REGION)); + assertEquals(Set.of(), names(service.listEventSources(json("{}"), REGION))); + service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + } + + @Test + void deleteToleratesASecretThatIsAlreadyGone() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + doThrow(new AwsException("ResourceNotFoundException", "gone", 400)).when(secrets) + .deleteSecret(any(), any(), eq(false), any()); + service.deleteEventSource(arn(source.getArn()), REGION); + assertEquals(Set.of(), names(service.listEventSources(json("{}"), REGION))); + } + + @Test + void deleteToleratesASecretThatDescribeCannotFind() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + when(secrets.describeSecret(any(), any())) + .thenThrow(new AwsException("ResourceNotFoundException", "gone", 400)); + service.deleteEventSource(arn(source.getArn()), REGION); + assertEquals(Set.of(), names(service.listEventSources(json("{}"), REGION))); + verify(secrets, never()).deleteSecret(any(), any(), eq(false), any()); + } + + @Test + void deleteKeepsTheSourceWhenTheSecretFailsToDeleteForAnotherReason() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + AwsException failure = new AwsException("InternalServiceError", "boom", 500); + doThrow(failure).when(secrets).deleteSecret(any(), any(), eq(false), any()); + AwsException e = assertThrows(AwsException.class, + () -> service.deleteEventSource(arn(source.getArn()), REGION)); + assertSame(failure, e); + assertEquals(Set.of("hook"), names(service.listEventSources(json("{}"), REGION))); + assertEquals(source.getArn(), service.describeEventSource(arn(source.getArn()), REGION).getArn()); + } + + @Test + void deleteDoesNotScheduleASecretThatIsAlreadyScheduledForDeletion() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + Secret scheduled = new Secret(); + scheduled.setDeletedDate(NOW.plus(Duration.ofDays(7))); + when(secrets.describeSecret(any(), any())).thenReturn(scheduled); + service.deleteEventSource(arn(source.getArn()), REGION); + assertEquals(Set.of(), names(service.listEventSources(json("{}"), REGION))); + verify(secrets, never()).deleteSecret(any(), any(), eq(false), any()); + } + + @Test + void deleteOfAMissingSourceDeletesNoSecret() { + String missing = "arn:aws:events:us-east-1:000000000000:event-sourcev2/webhook/x/abcdefghijklmnopqrstuvwxy"; + assertThrows(AwsException.class, () -> service.deleteEventSource(arn(missing), REGION)); + verify(secrets, never()).deleteSecret(any(), any(), eq(false), any()); + } + + // ──────────────────────────── DeleteEventBus ──────────────────────────── + + @Test + void aBusWithEventSourcesCannotBeDeleted() { + EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + AwsException e = assertThrows(AwsException.class, () -> service.deleteEventBus(bus, REGION)); + assertEquals("ResourceInUseException", e.getErrorCode()); + assertEquals(409, e.getHttpStatus()); + assertEquals("The event bus cannot be deleted because it has one or more event sources that are not " + + "revoked. Delete or revoke them and retry.", e.getMessage()); + + service.deleteEventSource(arn(source.getArn()), REGION); + service.deleteEventBus(bus, REGION); + } + + @Test + void aBusWithSubscribersAndEventSourcesNamesBoth() { + service.createSubscriber(json("{\"Name\":\"s\",\"EventBusArn\":\"" + bus + "\",\"InvokeConfiguration\":" + + "{\"TargetArn\":\"arn:aws:sqs:us-east-1:000000000000:q\",\"RoleArn\":\"" + ROLE + "\"}}"), REGION); + service.createEventSource(create("hook", bus, STATIC_AUTH), REGION); + AwsException e = assertThrows(AwsException.class, () -> service.deleteEventBus(bus, REGION)); + assertEquals("The event bus cannot be deleted because it has subscribers and event sources that are not " + + "revoked. Delete or revoke them and retry.", e.getMessage()); + } + + @Test + void aBusWithOnlySubscribersKeepsTheExistingMessage() { + service.createSubscriber(json("{\"Name\":\"s\",\"EventBusArn\":\"" + bus + "\",\"InvokeConfiguration\":" + + "{\"TargetArn\":\"arn:aws:sqs:us-east-1:000000000000:q\",\"RoleArn\":\"" + ROLE + "\"}}"), REGION); + AwsException e = assertThrows(AwsException.class, () -> service.deleteEventBus(bus, REGION)); + assertEquals("Event bus orders still has subscribers; delete them first.", e.getMessage()); + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private String bus(String name) { + EventBusV2 created = service.createEventBus(json("{\"Name\":\"" + name + "\"}"), REGION); + return created.getArn(); + } + + private String capturedSecretString() { + ArgumentCaptor secretString = ArgumentCaptor.forClass(String.class); + verify(secrets).createSecret(any(), secretString.capture(), any(), any(), any(), any(), any(), any()); + return secretString.getValue(); + } + + private static Set names(PaginatedResult page) { + return page.items().stream().map(EventSourceV2::getName).collect(Collectors.toSet()); + } + + private static ObjectNode create(String name, String bus, String auth, String... extra) { + String more = extra.length == 0 ? "" : "," + String.join(",", extra); + String token = "t" + Integer.toHexString((name + bus + auth + more).hashCode()); + return (ObjectNode) json("{\"ClientToken\":\"" + token + "\",\"Name\":\"" + name + + "\",\"EventBusArn\":\"" + bus + "\",\"Configuration\":{\"WebhookEventsConfiguration\":" + + "{\"AuthConfiguration\":" + auth + ",\"RoleArn\":\"" + ROLE + "\"}}" + more + "}"); + } + + private static JsonNode twoVariants(String busArn) { + ObjectNode request = create("hook", busArn, STATIC_AUTH); + ((ObjectNode) request.get("Configuration")).putObject("AwsServiceEventsConfiguration") + .put("AwsService", "aws.s3"); + return request; + } + + private static JsonNode arn(String arn) { + return json("{\"EventSourceArn\":\"" + arn + "\"}"); + } + + private static JsonNode json(String json) { + try { + return MAPPER.readTree(json); + } catch (Exception e) { + throw new IllegalArgumentException(json, e); + } + } + + private static final class TestClock extends Clock { + private Instant now; + + TestClock(Instant now) { + this.now = now; + } + + void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapesTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapesTest.java index ff300e604e..9018897595 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapesTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapesTest.java @@ -1,192 +1,593 @@ 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 io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.SmithyValidationErrors; import org.junit.jupiter.api.Test; +import java.util.Arrays; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -/** The measured AWS answers for CreateEventSource, read through the vendored request shapes. */ +/** + * What AWS answered to each request below, as measured, read through the vendored request shapes. Orders, + * wording and the cut at ten violations are the measured ones. + */ 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"; + private static final String REQUEST = "{\"Name\":\"n\",\"EventBusArn\":" + + "\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnopqrstuvwxy\"," + + "\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":" + + "\"arn:aws:iam::123456789012:role/probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}}}"; @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())); + void validRequestsHaveNoViolations() { + assertDoesNotThrow(() -> EventBridgeV2RequestShapes.check("CreateEventSource", json(REQUEST))); + assertDoesNotThrow(() -> EventBridgeV2RequestShapes.check("ListEventSources", json("{}"))); } @Test - void descriptionWithAControlCharacterBreaksItsPattern() { - ObjectNode request = validRequest(); - request.put("Description", "a\u0001b"); + void unknownMembersAreIgnoredAndNullMembersAreAbsent() { + ObjectNode request = json(REQUEST); + request.put("Bogus", "x"); + request.putNull("Description"); - 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)); + assertDoesNotThrow(() -> EventBridgeV2RequestShapes.check("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)); + void otherConfigurationVariantsPassTheShapes() { + assertDoesNotThrow(() -> EventBridgeV2RequestShapes.check("CreateEventSource", json( + "{\"Name\":\"n\",\"EventBusArn\":" + + "\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnopqrstuvwxy\"," + + "\"Configuration\":{\"AwsServiceEventsConfiguration\":{\"AwsService\":\"aws.s3\"}}}"))); } @Test - void moreThanTwoHundredTagsIsOneSizeViolation() { - ObjectNode request = validRequest(); + void twoHundredAndOneTagsQuoteTheWholeMapInHashMapOrder() { + ObjectNode request = json("{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}}}"); ObjectNode tags = request.putObject("Tags"); for (int i = 0; i < 201; i++) { tags.put("k" + i, "v"); } - List found = CHECK.violations("CreateEventSource", request); + assertAnswers("CreateEventSource", request, + "Value '{k31=v, k30=v, k33=v, k32=v, k35=v, k34=v, k37=v, k36=v, k39=v, k38=v, k141=v, k140" + + "=v, k143=v, k142=v, k145=v, k144=v, k147=v, k146=v, k149=v, k148=v, k40=v, k42=v, k41=v, k" + + "44=v, k43=v, k46=v, k45=v, k48=v, k47=v, k49=v, k130=v, k132=v, k131=v, k134=v, k133=v, k1" + + "36=v, k135=v, k138=v, k137=v, k139=v, k51=v, k50=v, k53=v, k52=v, k55=v, k54=v, k57=v, k56" + + "=v, k59=v, k170=v, k58=v, k161=v, k160=v, k163=v, k162=v, k165=v, k164=v, k167=v, k166=v, " + + "k169=v, k168=v, k60=v, k62=v, k61=v, k64=v, k63=v, k66=v, k65=v, k68=v, k67=v, k69=v, k150" + + "=v, k152=v, k151=v, k154=v, k153=v, k156=v, k155=v, k158=v, k157=v, k159=v, k71=v, k70=v, " + + "k73=v, k72=v, k75=v, k74=v, k77=v, k76=v, k79=v, k190=v, k78=v, k192=v, k191=v, k183=v, k1" + + "82=v, k185=v, k184=v, k187=v, k186=v, k189=v, k188=v, k80=v, k82=v, k81=v, k84=v, k83=v, k" + + "86=v, k85=v, k88=v, k87=v, k89=v, k181=v, k180=v, k172=v, k171=v, k174=v, k173=v, k176=v, " + + "k175=v, k178=v, k177=v, k179=v, k91=v, k90=v, k93=v, k92=v, k95=v, k94=v, k97=v, k96=v, k9" + + "9=v, k98=v, k194=v, k193=v, k196=v, k195=v, k198=v, k197=v, k199=v, k0=v, k1=v, k2=v, k3=v" + + ", k4=v, k5=v, k6=v, k7=v, k8=v, k9=v, k200=v, k101=v, k100=v, k103=v, k102=v, k105=v, k104" + + "=v, k107=v, k106=v, k109=v, k108=v, k11=v, k10=v, k13=v, k12=v, k15=v, k14=v, k17=v, k16=v" + + ", k19=v, k18=v, k121=v, k120=v, k123=v, k122=v, k125=v, k124=v, k127=v, k126=v, k129=v, k1" + + "28=v, k20=v, k22=v, k21=v, k24=v, k23=v, k26=v, k25=v, k28=v, k27=v, k29=v, k110=v, k112=v" + + ", k111=v, k114=v, k113=v, k116=v, k115=v, k118=v, k117=v, k119=v}' at 'tags' failed to sat" + + "isfy constraint: Member must have length less than or equal to 200"); + } - assertEquals(1, found.size()); + @Test + void tagKeyWithALeadingSpaceQuotesTheMapInHashMapOrder() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"Tags\":{\" lead\":\"v\",\"ok\":\"v2\"}}", + "Value '{ok=v2, lead=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]).*]"); + } + + @Test + void tagKeyOverTheLengthLimitIsAKeyViolation() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"Tags\":{\"kkkkkkkkkkkkkkkkkkkkkkkkkkkk" + + "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + + "k\":\"v\"}}", + "Value '{kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk=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]).*]"); + } + + @Test + void tagValueWithALeadingSpaceIsAValueViolation() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"Tags\":{\"k\":\" lead\",\"ok\":\"v2\"}}", + "Value '{ok=v2, k= lead}' 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]"); + } + + @Test + void tagValueOverTheLengthLimitIsAValueViolation() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"Tags\":{\"k\":\"vvvvvvvvvvvvvvvvvvvvvvvv" + + "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv" + + "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv" + + "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\"}}", + "Value '{k=vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv}' 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]"); + } + + @Test + void tagKeyAndValueBothBrokenAreTwoViolationsKeysFirst() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"Tags\":{\" k\":\" v\"}}", + "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]"); + } + + @Test + void descriptionComesBeforeTags() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"Tags\":{\" k\":\" v\"},\"Description\":\"a\\u" + + "0001b\"}", + "Value 'a\u0001b' at 'description' failed to satisfy constraint: Member must satisfy regular expression pattern: [^\\u0000-\\u001F\\u007F-\\u009F\\u2028\\u2029]*(?![\\s\\S]).*", + "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]"); + } + + @Test + void everythingBrokenAnswersTheFirstTenOfTheWalk() { + assertAnswers("CreateEventSource", "{\"Name\":\"bad name\",\"EventBusArn\":\"x\",\"Description\":\"a\\u0001b\",\"ClientToken\":\"a b\",\"Tags\":{\" k\":\" v\"}" + + ",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"r\",\"KmsKeyIdentifier\":\"a b\",\"MetadataHttp" + + "Headers\":[\"bad header\"],\"DeduplicationConfiguration\":{\"DeduplicationType\":\"X\"},\"LogConfiguration\":{\"" + + "Level\":\"X\",\"IncludePayload\":\"X\"},\"AuthConfiguration\":{\"HmacAuthConfiguration\":{\"Algorithm\":\"X\",\"Enco" + + "ding\":\"X\",\"SignatureHttpHeader\":\"bad header\",\"SignaturePrefix\":\"\",\"Delimiter\":\"\",\"TimestampHttpHeade" + + "r\":\"bad header\",\"TimestampPrefix\":\"\",\"TimestampToleranceInSeconds\":0,\"MessageIdHttpHeader\":\"bad head" + + "er\",\"SignedMessageComposition\":\"X\",\"SecretValue\":\"abc\",\"SecretEncoding\":\"X\"}}}}}", + "Value 'X' at 'configuration.webhookEventsConfiguration.deduplicationConfiguration.deduplicationType' failed to satisfy constraint: Member must satisfy enum value set: [CONTENT_BASED]", + "Value 'a b' at 'configuration.webhookEventsConfiguration.kmsKeyIdentifier' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_\\-/:]*", + "Value 'r' at 'configuration.webhookEventsConfiguration.roleArn' failed to satisfy constraint: Member must satisfy regular expression pattern: arn:aws(-[a-z0-9]+)*:iam::\\d{12}:role\\/[\\w+=,.@/-]+", + "Value 'X' at 'configuration.webhookEventsConfiguration.logConfiguration.level' failed to satisfy constraint: Member must satisfy enum value set: [ERROR, INFO, OFF]", + "Value 'X' at 'configuration.webhookEventsConfiguration.logConfiguration.includePayload' failed to satisfy constraint: Member must satisfy enum value set: [ON_ERROR_ONLY, FULL]", + "Value '[bad header]' at 'configuration.webhookEventsConfiguration.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]", + "Value 'X' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.secretEncoding' failed to satisfy constraint: Member must satisfy enum value set: [RAW, BASE64]", + "Value '' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.timestampPrefix' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\u0020-\\u007E]+", + "Value '' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.timestampPrefix' failed to satisfy constraint: Member must have length greater than or equal to 1", + "Value 'bad header' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.messageIdHttpHeader' failed to satisfy constraint: Member must satisfy regular expression pattern: [!#$%&'*+\\-.^_`|~0-9A-Za-z]+"); + } + + @Test + void emptyRequestNamesTheThreeRequiredMembersInWalkOrder() { + assertAnswers("CreateEventSource", "{}", + "Value null at 'configuration' failed to satisfy constraint: Member must not be null", + "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"); + } + + @Test + void emptyWebhookNamesRoleArnThenAuthConfiguration() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{}}}", + "Value null at 'configuration.webhookEventsConfiguration.roleArn' failed to satisfy constraint: Member must not be null", + "Value null at 'configuration.webhookEventsConfiguration.authConfiguration' failed to satisfy constraint: Member must not be null"); + } + + @Test + void emptyHmacNamesItsFourRequiredMembersInWalkOrder() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"HmacAuthConfiguration\":{}}}}}", + "Value null at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.signedMessageComposition' failed to satisfy constraint: Member must not be null", + "Value null at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.signatureHttpHeader' failed to satisfy constraint: Member must not be null", + "Value null at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.encoding' failed to satisfy constraint: Member must not be null", + "Value null at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.algorithm' failed to satisfy constraint: Member must not be null"); + } + + @Test + void staticTokenAndBasicBrokenAreWalkedInThatOrder() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"bad header\",\"SecretVa" + + "lue\":\"abc\"},\"BasicHttpAuthConfiguration\":{\"Username\":\"a:b\",\"Password\":\"abc\"}}}}}", + "Value at 'configuration.webhookEventsConfiguration.authConfiguration.staticTokenAuthConfiguration.secretValue' failed to satisfy constraint: Member must have length greater than or equal to 6", + "Value 'bad header' at 'configuration.webhookEventsConfiguration.authConfiguration.staticTokenAuthConfiguration.tokenHttpHeader' failed to satisfy constraint: Member must satisfy regular expression pattern: [!#$%&'*+\\-.^_`|~0-9A-Za-z]+", + "Value at 'configuration.webhookEventsConfiguration.authConfiguration.basicHttpAuthConfiguration.password' failed to satisfy constraint: Member must have length greater than or equal to 6", + "Value 'a:b' at 'configuration.webhookEventsConfiguration.authConfiguration.basicHttpAuthConfiguration.username' failed to satisfy constraint: Member must satisfy regular expression pattern: [^:\\s]+"); + } + + @Test + void updateEverythingBrokenIsWalkedConfigurationFirst() { + assertAnswers("UpdateEventSource", "{\"EventSourceArn\":\"x\",\"Description\":\"a\\u0001b\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleA" + + "rn\":\"r\"}}}", + "Value 'r' at 'configuration.webhookEventsConfiguration.roleArn' failed to satisfy constraint: Member must satisfy regular expression pattern: arn:aws(-[a-z0-9]+)*:iam::\\d{12}:role\\/[\\w+=,.@/-]+", + "Value null at 'configuration.webhookEventsConfiguration.authConfiguration' failed to satisfy constraint: Member must not be null", + "Value 'x' at 'eventSourceArn' failed to satisfy constraint: Member must satisfy regular expression 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}", + "Value 'a\u0001b' at 'description' failed to satisfy constraint: Member must satisfy regular expression pattern: [^\\u0000-\\u001F\\u007F-\\u009F\\u2028\\u2029]*(?![\\s\\S]).*"); + } + + @Test + void tagsOfSixEntriesQuoteTheMapInHashMapOrder() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"Tags\":{\" zeta\":\"v\",\"alpha\":\" v\",\"Mid" + + "\":\"v\",\"b\":\"v\",\"aa\":\"v\",\"BB\":\"v\"}}", + "Value '{aa=v, BB=v, Mid=v, b=v, zeta=v, alpha= 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 '{aa=v, BB=v, Mid=v, b=v, zeta=v, alpha= 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]"); + } + + @Test + void listNamePrefixBreakingItsPatternIsOneViolation() { + assertAnswers("ListEventSources", "{\"NamePrefix\":\"bad name\"}", + "Value 'bad name' at 'namePrefix' failed to satisfy constraint: Member must satisfy regular expression pattern: (?!aws\\.)[A-Za-z0-9][\\.\\-_A-Za-z0-9]*"); + } + + @Test + void listEmptyNamePrefixBreaksPatternThenLength() { + assertAnswers("ListEventSources", "{\"NamePrefix\":\"\"}", + "Value '' at 'namePrefix' failed to satisfy constraint: Member must satisfy regular expression pattern: (?!aws\\.)[A-Za-z0-9][\\.\\-_A-Za-z0-9]*", + "Value '' at 'namePrefix' failed to satisfy constraint: Member must have length greater than or equal to 1"); + } + + @Test + void listMaxResultsBelowOne() { + assertAnswers("ListEventSources", "{\"MaxResults\":0}", + "Value '0' at 'maxResults' failed to satisfy constraint: Member must have value greater than or equal to 1"); + } + + @Test + void listMaxResultsAboveOneHundred() { + assertAnswers("ListEventSources", "{\"MaxResults\":101}", + "Value '101' at 'maxResults' failed to satisfy constraint: Member must have value less than or equal to 100"); + } + + @Test + void listEmptyNextTokenIsTooShort() { + assertAnswers("ListEventSources", "{\"NextToken\":\"\"}", + "Value '' at 'nextToken' failed to satisfy constraint: Member must have length greater than or equal to 1"); + } + + @Test + void listEventBusArnBreakingItsPattern() { + assertAnswers("ListEventSources", "{\"EventBusArn\":\"x\"}", + "Value 'x' at 'eventBusArn' failed to satisfy constraint: Member must satisfy regular expression 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}"); + } + + @Test + void listEverythingBrokenIsWalkedInTheOrderAwsMeasured() { + assertAnswers("ListEventSources", "{\"EventBusArn\":\"x\",\"NamePrefix\":\"bad name\",\"MaxResults\":0,\"NextToken\":\"\"}", + "Value '0' at 'maxResults' failed to satisfy constraint: Member must have value greater than or equal to 1", + "Value '' at 'nextToken' failed to satisfy constraint: Member must have length greater than or equal to 1", + "Value 'bad name' at 'namePrefix' failed to satisfy constraint: Member must satisfy regular expression pattern: (?!aws\\.)[A-Za-z0-9][\\.\\-_A-Za-z0-9]*", + "Value 'x' at 'eventBusArn' failed to satisfy constraint: Member must satisfy regular expression 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}"); + } + + @Test + void describeArnBreakingItsPattern() { + assertAnswers("DescribeEventSource", "{\"EventSourceArn\":\"x\"}", + "Value 'x' at 'eventSourceArn' failed to satisfy constraint: Member must satisfy regular expression 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}"); + } + + @Test + void deleteWithoutAnArnNamesTheMissingMember() { + assertAnswers("DeleteEventSource", "{}", + "Value null at 'eventSourceArn' failed to satisfy constraint: Member must not be null"); + } + + @Test + void nullTagValueIsQuotedAsNull() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"Tags\":{\"k\":null}}", + "Value '{k=null}' 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]"); + } + + @Test + void nullMetadataHeaderIsQuotedAsNull() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}},\"MetadataHttpHeaders\":[\"ok\",null]}}}", + "Value '[ok, null]' at 'configuration.webhookEventsConfiguration.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]"); + } + + @Test + void nullNameIsAnAbsentMember() { + assertAnswers("CreateEventSource", "{\"Name\":null,\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmno" + + "pqrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role" + + "/probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}}}", + "Value null at 'name' failed to satisfy constraint: Member must not be null"); + } + + @Test + void emptyBodyAnswersTheSameAsAnEmptyRequest() { + assertAnswers("CreateEventSource", "{}", + "Value null at 'configuration' failed to satisfy constraint: Member must not be null", + "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"); + } + + @Test + void tagsWithALeadingSpaceKeyAndAnOkKey() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"Tags\":{\" lead\":\"v\",\"ok\":\"v2\"}}", + "Value '{ok=v2, lead=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]).*]"); + } + + @Test + void badCompositionListsItsValuesInTheMeasuredOrder() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"Signatur" + + "eHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"X\"}}}}}", + "Value 'X' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.signedMessageComposition' failed to satisfy constraint: Member must satisfy enum value set: [TIMESTAMP_DOT_BODY, BODY, MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY]"); + } + + @Test + void elevenViolationsAreCutToTheFirstTen() { + assertAnswers("CreateEventSource", "{\"Name\":\"bad name\",\"EventBusArn\":\"x\",\"Description\":\"a\\u0001b\",\"ClientToken\":\"a b\",\"Tags\":{\" k\":\" v\"}" + + ",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"r\",\"AuthConfiguration\":{\"BasicHttpAuthCon" + + "figuration\":{}},\"KmsKeyIdentifier\":\"a b\",\"MetadataHttpHeaders\":[\"bad header\"],\"DeduplicationConfigur" + + "ation\":{\"DeduplicationType\":\"X\"},\"LogConfiguration\":{\"Level\":\"X\",\"IncludePayload\":\"X\"}}}}", + "Value 'X' at 'configuration.webhookEventsConfiguration.deduplicationConfiguration.deduplicationType' failed to satisfy constraint: Member must satisfy enum value set: [CONTENT_BASED]", + "Value 'a b' at 'configuration.webhookEventsConfiguration.kmsKeyIdentifier' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_\\-/:]*", + "Value 'r' at 'configuration.webhookEventsConfiguration.roleArn' failed to satisfy constraint: Member must satisfy regular expression pattern: arn:aws(-[a-z0-9]+)*:iam::\\d{12}:role\\/[\\w+=,.@/-]+", + "Value 'X' at 'configuration.webhookEventsConfiguration.logConfiguration.level' failed to satisfy constraint: Member must satisfy enum value set: [ERROR, INFO, OFF]", + "Value 'X' at 'configuration.webhookEventsConfiguration.logConfiguration.includePayload' failed to satisfy constraint: Member must satisfy enum value set: [ON_ERROR_ONLY, FULL]", + "Value '[bad header]' at 'configuration.webhookEventsConfiguration.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]", + "Value 'a b' at 'clientToken' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\u0021-\\u007E]+", + "Value 'bad name' at 'name' failed to satisfy constraint: Member must satisfy regular expression pattern: (?!aws\\.)[A-Za-z0-9][\\.\\-_A-Za-z0-9]*", + "Value 'a\u0001b' at 'description' failed to satisfy constraint: Member must satisfy regular expression pattern: [^\\u0000-\\u001F\\u007F-\\u009F\\u2028\\u2029]*(?![\\s\\S]).*", + "Value 'x' at 'eventBusArn' failed to satisfy constraint: Member must satisfy regular expression 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}"); + } + + @Test + void nameAsANumberIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":5,\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnopqr" + + "stuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/pr" + + "obe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}}}"); + } + + @Test + void nameAsABooleanIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":true,\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmno" + + "pqrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role" + + "/probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}}}"); + } + + @Test + void nameAsAListIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":[\"a\"],\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmn" + + "opqrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:rol" + + "e/probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}}}"); + } + + @Test + void configurationAsAStringIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":\"x\"}"); + } + + @Test + void webhookConfigurationAsAStringIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":\"x\"}}"); + } + + @Test + void tagsAsAListIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"Tags\":[\"a\"]}"); + } + + @Test + void tagValueAsANumberIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"Tags\":{\"k\":5}}"); + } + + @Test + void metadataHeadersAsAStringIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}},\"MetadataHttpHeaders\":\"x\"}}}"); + } + + @Test + void metadataHeaderAsANumberIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}},\"MetadataHttpHeaders\":[5]}}}"); + } + + @Test + void toleranceAsAStringIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"Signatur" + + "eHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\",\"TimestampToleranceInSeconds\":\"5\"}}}}}"); + } + + @Test + void toleranceAsAFloatIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"Signatur" + + "eHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\",\"TimestampToleranceInSeconds\":5.5}}}}}"); + } + + @Test + void toleranceBeyond32BitsIsASerializationExceptionWithNoMessage() { + assertSerializationException("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"Signatur" + + "eHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\",\"TimestampToleranceInSeconds\":999999999999999" + + "99999}}}}}"); + } + + @Test + void listMaxResultsAsAStringIsASerializationExceptionWithNoMessage() { + assertSerializationException("ListEventSources", "{\"MaxResults\":\"5\"}"); + } + + @Test + void hmacEnumsListTheirValuesInTheMeasuredOrder() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"HmacAuthConfiguration\":{\"Algorithm\":\"X\",\"Encoding\":\"X\",\"SignatureHttpHe" + + "ader\":\"X-Sig\",\"SignedMessageComposition\":\"X\",\"SecretEncoding\":\"X\"}}}}}", + "Value 'X' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.secretEncoding' failed to satisfy constraint: Member must satisfy enum value set: [RAW, BASE64]", + "Value 'X' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.signedMessageComposition' failed to satisfy constraint: Member must satisfy enum value set: [TIMESTAMP_DOT_BODY, BODY, MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY]", + "Value 'X' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.encoding' failed to satisfy constraint: Member must satisfy enum value set: [BASE64, HEX]", + "Value 'X' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.algorithm' failed to satisfy constraint: Member must satisfy enum value set: [SHA1, SHA256]"); + } + + @Test + void hmacMembersBrokenInTheFirstHalfAreWalkedInHashOrder() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"Signatur" + + "eHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\",\"SignaturePrefix\":\"\\u00e9\",\"Delimiter\":\"\\u00e" + + "9\",\"TimestampHttpHeader\":\"bad header\",\"TimestampPrefix\":\"\\u00e9\",\"TimestampToleranceInSeconds\":0,\"Me" + + "ssageIdHttpHeader\":\"bad header\",\"SecretValue\":\"abc\"}}}}}", + "Value '\u00e9' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.timestampPrefix' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\u0020-\\u007E]+", + "Value 'bad header' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.messageIdHttpHeader' failed to satisfy constraint: Member must satisfy regular expression pattern: [!#$%&'*+\\-.^_`|~0-9A-Za-z]+", + "Value at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.secretValue' failed to satisfy constraint: Member must have length greater than or equal to 6", + "Value '\u00e9' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.signaturePrefix' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\u0020-\\u007E]+", + "Value '\u00e9' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.delimiter' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\u0020-\\u007E]+", + "Value '0' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.timestampToleranceInSeconds' failed to satisfy constraint: Member must have value greater than or equal to 1", + "Value 'bad header' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.timestampHttpHeader' failed to satisfy constraint: Member must satisfy regular expression pattern: [!#$%&'*+\\-.^_`|~0-9A-Za-z]+"); + } + + @Test + void hmacMembersBrokenInTheSecondHalfAreWalkedInHashOrder() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"HmacAuthConfiguration\":{\"Algorithm\":\"X\",\"Encoding\":\"X\",\"SignatureHttpHe" + + "ader\":\"bad header\",\"SignedMessageComposition\":\"X\",\"SecretEncoding\":\"X\",\"SecretValue\":\"abc\",\"Timestam" + + "pToleranceInSeconds\":901}}}}}", + "Value 'X' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.secretEncoding' failed to satisfy constraint: Member must satisfy enum value set: [RAW, BASE64]", + "Value at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.secretValue' failed to satisfy constraint: Member must have length greater than or equal to 6", + "Value 'X' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.signedMessageComposition' failed to satisfy constraint: Member must satisfy enum value set: [TIMESTAMP_DOT_BODY, BODY, MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY]", + "Value '901' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.timestampToleranceInSeconds' failed to satisfy constraint: Member must have value less than or equal to 900", + "Value 'bad header' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.signatureHttpHeader' failed to satisfy constraint: Member must satisfy regular expression pattern: [!#$%&'*+\\-.^_`|~0-9A-Za-z]+", + "Value 'X' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.encoding' failed to satisfy constraint: Member must satisfy enum value set: [BASE64, HEX]", + "Value 'X' at 'configuration.webhookEventsConfiguration.authConfiguration.hmacAuthConfiguration.algorithm' failed to satisfy constraint: Member must satisfy enum value set: [SHA1, SHA256]"); + } + + @Test + void sixTopLevelMembersBrokenAreWalkedInHashOrder() { + assertAnswers("CreateEventSource", "{\"Name\":\"bad name\",\"EventBusArn\":\"x\",\"Description\":\"a\\u0001b\",\"ClientToken\":\"a b\",\"Tags\":{\" k\":\"v\"}}", + "Value null at 'configuration' failed to satisfy constraint: Member must not be null", + "Value 'a b' at 'clientToken' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\u0021-\\u007E]+", + "Value 'bad name' at 'name' failed to satisfy constraint: Member must satisfy regular expression pattern: (?!aws\\.)[A-Za-z0-9][\\.\\-_A-Za-z0-9]*", + "Value 'a\u0001b' at 'description' failed to satisfy constraint: Member must satisfy regular expression pattern: [^\\u0000-\\u001F\\u007F-\\u009F\\u2028\\u2029]*(?![\\s\\S]).*", + "Value 'x' at 'eventBusArn' failed to satisfy constraint: Member must satisfy regular expression 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}", + "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]).*]"); + } + + @Test + void nameBreakingPatternAndLengthAnswersThePatternFirst() { + assertAnswers("CreateEventSource", "{\"Name\":\" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"EventBusArn\":\"arn:aws:events:u" + + "s-east-1:123456789012:event-busv2/orders/abcdefghijklmnopqrstuvwxy\",\"Configuration\":{\"WebhookEventsC" + + "onfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/probe\",\"AuthConfiguration\":{\"BasicHttpAuthC" + + "onfiguration\":{}}}}}", + "Value ' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' at 'name' failed to satisfy constraint: Member must satisfy regular expression pattern: (?!aws\\.)[A-Za-z0-9][\\.\\-_A-Za-z0-9]*", + "Value ' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' at 'name' failed to satisfy constraint: Member must have length less than or equal to 256"); + } + + @Test + void clientTokenBreakingPatternAndLengthAnswersThePatternFirst() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}},\"ClientToken\":\" " + + " \"}", + "Value ' ' at 'clientToken' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\u0021-\\u007E]+", + "Value ' ' at 'clientToken' failed to satisfy constraint: Member must have length less than or equal to 64"); + } + + @Test + void tokenHeaderBreakingPatternAndLengthAnswersThePatternFirst() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\" " + + " " + + " " + + " " + + " " + + " \"}}}}}", + "Value ' ' at 'configuration.webhookEventsConfiguration.authConfiguration.staticTokenAuthConfiguration.tokenHttpHeader' failed to satisfy constraint: Member must satisfy regular expression pattern: [!#$%&'*+\\-.^_`|~0-9A-Za-z]+", + "Value ' ' at 'configuration.webhookEventsConfiguration.authConfiguration.staticTokenAuthConfiguration.tokenHttpHeader' failed to satisfy constraint: Member must have length less than or equal to 512"); + } + + @Test + void metadataListBreakingItsSizeAndAMemberAnswersTheSizeFirst() { + assertAnswers("CreateEventSource", "{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}},\"MetadataHttpHeaders\":[\"bad header\",\"h0" + + "\",\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\",\"h7\",\"h8\",\"h9\",\"h10\",\"h11\",\"h12\",\"h13\",\"h14\",\"h15\",\"h16\",\"h17\",\"h18\"" + + ",\"h19\"]}}}", + "Value '[bad header, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13, h14, h15, h16, h17, h18, h19]' at 'configuration.webhookEventsConfiguration.metadataHttpHeaders' failed to satisfy constraint: Member must have length less than or equal to 20", + "Value '[bad header, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13, h14, h15, h16, h17, h18, h19]' at 'configuration.webhookEventsConfiguration.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]"); + } + + @Test + void tagsBreakingSizeKeysAndValuesAreThreeViolationsInThatOrder() { + ObjectNode request = json("{\"Name\":\"n\",\"EventBusArn\":\"arn:aws:events:us-east-1:123456789012:event-busv2/orders/abcdefghijklmnop" + + "qrstuvwxy\",\"Configuration\":{\"WebhookEventsConfiguration\":{\"RoleArn\":\"arn:aws:iam::123456789012:role/" + + "probe\",\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}}}}"); + ObjectNode tags = request.putObject("Tags"); + for (int i = 0; i < 199; i++) { + tags.put("k" + i, "v"); + } + tags.put(" a", "v"); + tags.put("b", " v"); + + List found = violationsOf("CreateEventSource", request); + + assertEquals(3, 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)); + assertTrue(found.get(1).endsWith("' 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]).*]"), found.get(1)); + assertTrue(found.get(2).endsWith("' 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]"), found.get(2)); } - @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)); + private static void assertAnswers(String operation, String request, String... violations) { + assertAnswers(operation, json(request), violations); } - @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)); + private static void assertAnswers(String operation, ObjectNode request, String... violations) { + AwsException e = assertThrows(AwsException.class, () -> EventBridgeV2RequestShapes.check(operation, request)); + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + assertEquals(SmithyValidationErrors.message(Arrays.asList(violations)), e.getMessage()); } - @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)); + private static List violationsOf(String operation, ObjectNode request) { + AwsException e = assertThrows(AwsException.class, () -> EventBridgeV2RequestShapes.check(operation, request)); + return List.of(e.getMessage().replaceFirst("^\\d+ validation errors? detected: ", "").split("; (?=Value )")); } - @Test - void twentyOneMetadataHeadersAreOneSizeViolation() { - ObjectNode request = validRequest(); - String[] names = new String[21]; - for (int i = 0; i < names.length; i++) { - names[i] = "h" + (i + 1); + private static void assertSerializationException(String operation, String request) { + AwsException e = assertThrows(AwsException.class, + () -> EventBridgeV2RequestShapes.check(operation, json(request))); + assertEquals("SerializationException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + assertNull(e.getMessage()); + } + + private static ObjectNode json(String json) { + try { + return (ObjectNode) MAPPER.readTree(json); + } catch (Exception e) { + throw new IllegalArgumentException(json, e); } - 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/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ServiceTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ServiceTest.java index c8d91b0c00..6cb324559f 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ServiceTest.java @@ -10,6 +10,7 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.services.eventbridgev2.model.EventBusV2; import io.floci.aws.services.eventbridgev2.model.SubscriberV2; +import io.floci.aws.services.secretsmanager.SecretsManagerService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -59,9 +60,13 @@ class EventBridgeV2ServiceTest { @BeforeEach void setUp() { delivery = mock(EventBridgeV2Delivery.class); + RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); + Clock clock = Clock.fixed(NOW, ZoneOffset.UTC); + EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources( + AccountAwareStorageBackend.inMemory(ACCOUNT), mock(SecretsManagerService.class), regionResolver, clock, + "http://floci.test:4566"); service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT), - AccountAwareStorageBackend.inMemory(ACCOUNT), new RegionResolver(REGION, ACCOUNT), delivery, - Clock.fixed(NOW, ZoneOffset.UTC), true); + AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, eventSources, clock, true); } @Test diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurationsTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurationsTest.java new file mode 100644 index 0000000000..54d2cd78e1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurationsTest.java @@ -0,0 +1,492 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class WebhookEventsConfigurationsTest { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String BUS = "arn:aws:events:us-east-1:000000000000:event-busv2/orders/abcdefghijklmnopqrstuvwxy"; + private static final String ROLE = "arn:aws:iam::000000000000:role/Hook"; + private static final String PATH = "configuration.webhookEventsConfiguration"; + private static final String HMAC_PATH = PATH + ".authConfiguration.hmacAuthConfiguration"; + private static final String STATIC_AUTH = "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Token\"}}"; + private static final String HMAC_BASE = "\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\"," + + "\"SignatureHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\""; + private static final String SIGNED_MESSAGE_ID_ERROR = "WebhookEventsConfiguration.AuthConfiguration" + + ".HmacAuthConfiguration is invalid: "; + + // ──────────────────────────── Constraints, through the generated shapes ──────────────────────────── + + @Test + void validRequestHasNoViolations() { + assertEquals(List.of(), violations("CreateEventSource", create("{\"Name\":\"hook\"," + + "\"EventBusArn\":\"" + BUS + "\",\"Description\":\"d\",\"ClientToken\":\"t\"," + + "\"Tags\":{\"a\":\"b\"},\"Configuration\":{\"WebhookEventsConfiguration\":{" + + "\"AuthConfiguration\":" + STATIC_AUTH + ",\"RoleArn\":\"" + ROLE + "\"}}}"))); + } + + @Test + void missingRequiredMembersAreReportedAsNull() { + assertEquals(List.of( + "Value null at 'configuration' failed to satisfy constraint: Member must not be null", + "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"), + violations("CreateEventSource", MAPPER.createObjectNode())); + assertEquals(List.of( + "Value null at '" + PATH + ".roleArn' failed to satisfy constraint: Member must not be null", + "Value null at '" + PATH + ".authConfiguration' failed to satisfy constraint: Member must not be null"), + webhookViolations("{}")); + } + + @Test + void nameBreakingItsPatternIsReportedWithTheModelsPattern() { + List violations = violations("CreateEventSource", create("{\"Name\":\"-x\"," + + "\"EventBusArn\":\"" + BUS + "\",\"Configuration\":{}}")); + assertEquals(List.of("Value '-x' at 'name' failed to satisfy constraint: Member must satisfy regular " + + "expression pattern: (?!aws\\.)[A-Za-z0-9][\\.\\-_A-Za-z0-9]*"), violations); + } + + @Test + void reservedAwsNamePrefixIsRefused() { + List violations = violations("CreateEventSource", create("{\"Name\":\"aws.x\"," + + "\"EventBusArn\":\"" + BUS + "\",\"Configuration\":{}}")); + assertEquals(1, violations.size()); + assertTrue(violations.getFirst().startsWith("Value 'aws.x' at 'name'"), violations.toString()); + } + + @Test + void severalViolationsAreCountedInOneMessageInMemberOrder() { + List violations = violations("CreateEventSource", create("{\"Name\":\"-x\"," + + "\"EventBusArn\":\"nope\",\"ClientToken\":\"\",\"Configuration\":{}}")); + assertEquals(4, violations.size()); + assertTrue(violations.get(0).contains("at 'clientToken' failed to satisfy constraint: Member must satisfy " + + "regular expression pattern: [\\u0021-\\u007E]+")); + assertEquals("Value '' at 'clientToken' failed to satisfy constraint: Member must have length greater than " + + "or equal to 1", violations.get(1)); + assertTrue(violations.get(2).contains("at 'name'")); + assertTrue(violations.get(3).contains("at 'eventBusArn' failed to satisfy constraint: Member must satisfy " + + "regular expression pattern: arn:aws(-[a-z0-9]+)*:events:"), violations.get(3)); + } + + @Test + void timestampToleranceIsHeldTo1Through900() { + assertEquals(List.of("Value '0' at '" + HMAC_PATH + ".timestampToleranceInSeconds' failed to satisfy " + + "constraint: Member must have value greater than or equal to 1"), + hmacViolations("\"TimestampToleranceInSeconds\":0")); + assertEquals(List.of("Value '901' at '" + HMAC_PATH + ".timestampToleranceInSeconds' failed to satisfy " + + "constraint: Member must have value less than or equal to 900"), + hmacViolations("\"TimestampToleranceInSeconds\":901")); + assertEquals(List.of(), hmacViolations("\"TimestampToleranceInSeconds\":900")); + } + + @Test + void enumValuesAreListedInTheMeasuredOrder() { + assertEquals(List.of("Value 'DEBUG' at '" + PATH + ".logConfiguration.level' failed to satisfy constraint: " + + "Member must satisfy enum value set: [ERROR, INFO, OFF]"), + webhookViolations("{\"AuthConfiguration\":" + STATIC_AUTH + ",\"RoleArn\":\"" + ROLE + "\"," + + "\"LogConfiguration\":{\"Level\":\"DEBUG\"}}")); + assertEquals(List.of("Value 'MD5' at '" + HMAC_PATH + ".algorithm' failed to satisfy constraint: Member " + + "must satisfy enum value set: [SHA1, SHA256]"), + hmacViolations("\"Algorithm\":\"MD5\"")); + assertEquals(List.of("Value 'X' at '" + PATH + ".deduplicationConfiguration.deduplicationType' failed to " + + "satisfy constraint: Member must satisfy enum value set: [CONTENT_BASED]"), + webhookViolations("{\"AuthConfiguration\":" + STATIC_AUTH + ",\"RoleArn\":\"" + ROLE + "\"," + + "\"DeduplicationConfiguration\":{\"DeduplicationType\":\"X\"}}")); + } + + @Test + void sensitiveMembersLeaveTheirValueOutOfTheMessage() { + assertEquals(List.of("Value at '" + PATH + ".authConfiguration.staticTokenAuthConfiguration.secretValue' " + + "failed to satisfy constraint: Member must have length greater than or equal to 6"), + webhookViolations("{\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":" + + "\"X-Token\",\"SecretValue\":\"abc\"}},\"RoleArn\":\"" + ROLE + "\"}")); + assertEquals(List.of("Value at '" + PATH + ".authConfiguration.basicHttpAuthConfiguration.password' " + + "failed to satisfy constraint: Member must have length greater than or equal to 6"), + webhookViolations("{\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{\"Password\":\"abc\"}}," + + "\"RoleArn\":\"" + ROLE + "\"}")); + } + + @Test + void headerNameWithABadCharacterIsReportedWithItsPattern() { + List violations = webhookViolations("{\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":" + + "{\"TokenHttpHeader\":\"X Token\"}},\"RoleArn\":\"" + ROLE + "\"}"); + assertEquals(List.of("Value 'X Token' at '" + PATH + ".authConfiguration.staticTokenAuthConfiguration" + + ".tokenHttpHeader' failed to satisfy constraint: Member must satisfy regular expression pattern: " + + "[!#$%&'*+\\-.^_`|~0-9A-Za-z]+"), violations); + } + + @Test + void metadataHeaderBreakingItsMemberShapeReportsTheWholeList() { + List violations = webhookViolations("{\"AuthConfiguration\":" + STATIC_AUTH + ",\"RoleArn\":\"" + + ROLE + "\",\"MetadataHttpHeaders\":[\"X Y\"]}"); + assertEquals(List.of("Value '[X Y]' at '" + PATH + ".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]"), violations); + } + + @Test + void metadataHeaderListHoldsAtMost20() { + StringBuilder headers = new StringBuilder(); + StringBuilder rendered = new StringBuilder(); + for (int i = 0; i < 21; i++) { + headers.append(i == 0 ? "" : ",").append("\"X-H").append(i).append('"'); + rendered.append(i == 0 ? "" : ", ").append("X-H").append(i); + } + assertEquals(List.of("Value '[" + rendered + "]' at '" + PATH + ".metadataHttpHeaders' failed to satisfy " + + "constraint: Member must have length less than or equal to 20"), + webhookViolations("{\"AuthConfiguration\":" + STATIC_AUTH + ",\"RoleArn\":\"" + ROLE + "\"," + + "\"MetadataHttpHeaders\":[" + headers + "]}")); + } + + @Test + void tagsAreHeldToTheirShape() { + Map rendered = new HashMap<>(201); + for (int i = 0; i < 201; i++) { + rendered.put("k" + i, "v"); + } + assertEquals(List.of("Value '" + rendered + "' at 'tags' failed to satisfy constraint: Member must have " + + "length less than or equal to 200"), + violations("CreateEventSource", create(withTags(201)))); + List violations = violations("CreateEventSource", create("{\"Name\":\"hook\"," + + "\"EventBusArn\":\"" + BUS + "\",\"Configuration\":{\"WebhookEventsConfiguration\":{" + + "\"AuthConfiguration\":" + STATIC_AUTH + ",\"RoleArn\":\"" + ROLE + "\"}},\"Tags\":{\" a\":\"b \"}}")); + assertEquals(List.of( + "Value '{ a=b }' 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 '{ a=b }' 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]"), violations); + } + + @Test + void aValueOfTheWrongTypeIsASerializationExceptionWithNoMessage() { + AwsException e = assertThrows(AwsException.class, () -> EventBridgeV2RequestShapes.check( + "CreateEventSource", create("{\"Name\":5}"))); + assertEquals("SerializationException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + assertNull(e.getMessage()); + } + + @Test + void hmacSecretLengthIsCheckedAfterTheWhsecPrefixIsRemoved() { + assertEquals(List.of(), hmacViolations("\"SecretEncoding\":\"BASE64\",\"SecretValue\":\"whsec_abcdef\"")); + assertEquals(1, hmacViolations("\"SecretEncoding\":\"BASE64\",\"SecretValue\":\"whsec_abc\"").size()); + assertEquals(List.of(), hmacViolations("\"SecretValue\":\"whsec_abc\"")); + JsonNode request = json("{\"Name\":\"hook\",\"EventBusArn\":\"" + BUS + "\",\"Configuration\":" + + "{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":{\"HmacAuthConfiguration\":{" + HMAC_BASE + + ",\"SecretEncoding\":\"BASE64\",\"SecretValue\":\"whsec_abcdef\"}},\"RoleArn\":\"" + ROLE + "\"}}}"); + EventBridgeV2RequestShapes.check("CreateEventSource", request); + assertEquals("whsec_abcdef", request.at("/Configuration/WebhookEventsConfiguration/AuthConfiguration" + + "/HmacAuthConfiguration/SecretValue").asText()); + } + + @Test + void updateViolationsCoverTheArnConfigurationAndDescription() { + List violations = violations("UpdateEventSource", MAPPER.createObjectNode() + .put("EventSourceArn", "x").put("Description", "a\nb")); + assertEquals(2, violations.size()); + assertTrue(violations.get(0).startsWith("Value 'x' at 'eventSourceArn'"), violations.get(0)); + assertTrue(violations.get(1).contains("at 'description'"), violations.get(1)); + } + + // ──────────────────────────── Rules after the constraints ──────────────────────────── + + @Test + void configurationMustHoldExactlyOneMember() { + assertEquals("Exactly one Configuration sub-field must be provided", createRefusal("{}")); + assertEquals("Exactly one Configuration sub-field must be provided", + createRefusal("{\"WebhookEventsConfiguration\":{},\"PartnerEventsConfiguration\":{}}")); + } + + @ParameterizedTest + @ValueSource(strings = {"AwsServiceEventsConfiguration", "PartnerEventsConfiguration"}) + void otherVariantsAreNotSupported(String variant) { + assertEquals("Only WebhookEventsConfiguration event sources are supported.", + createRefusal("{\"" + variant + "\":{}}")); + } + + @Test + void authConfigurationMustSetExactlyOneMember() { + String message = "WebhookEventsConfiguration.AuthConfiguration must set exactly one of " + + "StaticTokenAuthConfiguration, BasicHttpAuthConfiguration or HmacAuthConfiguration"; + assertEquals(message, webhookRefusal("{}")); + assertEquals(message, webhookRefusal("{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-T\"}," + + "\"BasicHttpAuthConfiguration\":{}}")); + } + + @Test + void basicAuthNeedsBothCredentialsOrNeither() { + String message = "WebhookEventsConfiguration.AuthConfiguration.BasicHttpAuthConfiguration must set both " + + "Username and Password, or neither. Supplying only one is not valid; omit both to have " + + "EventBridge generate the credential."; + assertEquals(message, webhookRefusal("{\"BasicHttpAuthConfiguration\":{\"Username\":\"u\"}}")); + assertEquals(message, webhookRefusal("{\"BasicHttpAuthConfiguration\":{\"Password\":\"secret1\"}}")); + WebhookEventsConfigurations.validateForCreate(wrapped("{\"AuthConfiguration\":" + + "{\"BasicHttpAuthConfiguration\":{}},\"RoleArn\":\"" + ROLE + "\"}")); + } + + @ParameterizedTest + @ValueSource(strings = {"Host", "host", "X-Forwarded-For", "Content-Length", "Set-Cookie", "TE", "Trailer"}) + void staticTokenHeaderCannotBeAReservedName(String header) { + assertEquals("WebhookEventsConfiguration.AuthConfiguration.StaticTokenAuthConfiguration.TokenHttpHeader " + + "can't be the header " + header + ": it is not allowed. Header names are case-insensitive.", + webhookRefusal("{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"" + header + "\"}}")); + } + + @ParameterizedTest + @ValueSource(strings = {"Authorization", "X-Forwarded-Port", "Content-Type", "Expect", "X-Custom"}) + void staticTokenHeaderMayBeAnyOtherName(String header) { + WebhookEventsConfigurations.validateForCreate(wrapped("{\"AuthConfiguration\":" + + "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"" + header + "\"}},\"RoleArn\":\"" + + ROLE + "\"}")); + } + + @Test + void hmacRulesAreCheckedInOrder() { + assertEquals(SIGNED_MESSAGE_ID_ERROR + "SecretValue must be at least 16 bytes (for BASE64, after decoding)", + hmacRefusal("\"SecretValue\":\"short-secret\"")); + assertEquals(SIGNED_MESSAGE_ID_ERROR + "SecretValue must be at least 16 bytes (for BASE64, after decoding)", + hmacRefusal("\"SecretEncoding\":\"BASE64\",\"SecretValue\":\"c2hvcnQ=\",\"TimestampToleranceInSeconds\":5")); + assertEquals(SIGNED_MESSAGE_ID_ERROR + "TimestampToleranceInSeconds requires TimestampHttpHeader to be set", + hmacRefusal("\"TimestampToleranceInSeconds\":5")); + assertEquals(SIGNED_MESSAGE_ID_ERROR + "TimestampHttpHeader and TimestampToleranceInSeconds require a " + + "SignedMessageComposition that signs the timestamp (TIMESTAMP_DOT_BODY or " + + "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY)", hmacRefusal("\"TimestampHttpHeader\":\"X-Ts\"")); + assertEquals(SIGNED_MESSAGE_ID_ERROR + "TIMESTAMP_DOT_BODY requires TimestampHttpHeader to be set", + hmacRefusal("\"SignedMessageComposition\":\"TIMESTAMP_DOT_BODY\"")); + assertEquals(SIGNED_MESSAGE_ID_ERROR + "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY requires TimestampHttpHeader to " + + "be set", hmacRefusal("\"SignedMessageComposition\":\"MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY\"")); + assertEquals(SIGNED_MESSAGE_ID_ERROR + "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY requires MessageIdHttpHeader to " + + "be set", hmacRefusal("\"SignedMessageComposition\":\"MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY\"," + + "\"TimestampHttpHeader\":\"X-Ts\"")); + assertEquals(SIGNED_MESSAGE_ID_ERROR + "Delimiter is required when SignatureHttpHeader and " + + "TimestampHttpHeader are the same", hmacRefusal("\"SignedMessageComposition\":" + + "\"TIMESTAMP_DOT_BODY\",\"TimestampHttpHeader\":\"x-sig\"")); + assertEquals(SIGNED_MESSAGE_ID_ERROR + "SignaturePrefix and TimestampPrefix are both required when " + + "SignatureHttpHeader and TimestampHttpHeader are the same", hmacRefusal( + "\"SignedMessageComposition\":\"TIMESTAMP_DOT_BODY\",\"TimestampHttpHeader\":\"X-SIG\"," + + "\"Delimiter\":\",\",\"SignaturePrefix\":\"v1=\"")); + } + + @Test + void hmacAcceptsTheCombinationsAwsAccepts() { + for (String extra : List.of( + "\"MessageIdHttpHeader\":\"X-Id\",\"Delimiter\":\",\",\"TimestampPrefix\":\"t=\"", + "\"SignedMessageComposition\":\"TIMESTAMP_DOT_BODY\",\"TimestampHttpHeader\":\"X-SIG\"," + + "\"Delimiter\":\",\",\"SignaturePrefix\":\"p=\",\"TimestampPrefix\":\"p=\"", + "\"SignedMessageComposition\":\"MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY\",\"TimestampHttpHeader\":" + + "\"X-Ts\",\"MessageIdHttpHeader\":\"X-Sig\"")) { + WebhookEventsConfigurations.validateForCreate(wrapped("{\"AuthConfiguration\":{\"HmacAuthConfiguration\":" + + "{" + withReplaced(extra) + "}},\"RoleArn\":\"" + ROLE + "\"}")); + } + } + + @Test + void hmacBase64SecretMustBeStandardBase64() { + assertEquals("WebhookEventsConfiguration.AuthConfiguration.HmacAuthConfiguration.SecretValue must be " + + "standard Base64 when SecretEncoding is BASE64", + hmacRefusal("\"SecretEncoding\":\"BASE64\",\"SecretValue\":\"abc-_abc-_abc-_abc-_abc-_\"")); + WebhookEventsConfigurations.validateForCreate(wrapped("{\"AuthConfiguration\":{\"HmacAuthConfiguration\":" + + "{" + HMAC_BASE + ",\"SecretEncoding\":\"BASE64\",\"SecretValue\":\"whsec_" + + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"}},\"RoleArn\":\"" + ROLE + "\"}")); + } + + @Test + void hmacReservedHeadersAreCheckedAfterTheOtherRulesInOrder() { + assertEquals("WebhookEventsConfiguration.AuthConfiguration.HmacAuthConfiguration.SignatureHttpHeader can't " + + "be the header Cookie: it is not allowed. Header names are case-insensitive.", + webhookRefusal("{\"HmacAuthConfiguration\":{" + HMAC_BASE.replace("X-Sig", "Cookie") + "}}")); + assertEquals("WebhookEventsConfiguration.AuthConfiguration.HmacAuthConfiguration.TimestampHttpHeader can't " + + "be the header Via: it is not allowed. Header names are case-insensitive.", + hmacRefusal("\"SignedMessageComposition\":\"TIMESTAMP_DOT_BODY\",\"TimestampHttpHeader\":\"Via\"")); + assertEquals("WebhookEventsConfiguration.AuthConfiguration.HmacAuthConfiguration.MessageIdHttpHeader can't " + + "be the header Host: it is not allowed. Header names are case-insensitive.", + hmacRefusal("\"MessageIdHttpHeader\":\"Host\"")); + } + + @Test + void metadataHeadersAreCheckedOneByOneInListOrder() { + String prefix = "WebhookEventsConfiguration.MetadataHttpHeaders "; + assertEquals(prefix + "can't include the header Authorization: it is not allowed", + metadataRefusal("[\"X-Ok\",\"Authorization\"]")); + assertEquals(prefix + "can't include the header x-token because it is StaticTokenAuthConfiguration" + + ".TokenHttpHeader", metadataRefusal("[\"x-token\"]")); + assertEquals(prefix + "lists the header x-A more than once. Header names are case-insensitive.", + metadataRefusal("[\"X-A\",\"x-A\"]")); + assertEquals(prefix + "lists the header X-A more than once. Header names are case-insensitive.", + metadataRefusal("[\"X-A\",\"X-A\",\"Cookie\"]")); + } + + @Test + void metadataHeadersMayRepeatNamesAwsAllows() { + WebhookEventsConfigurations.validateForCreate(wrapped("{\"AuthConfiguration\":" + STATIC_AUTH + + ",\"RoleArn\":\"" + ROLE + "\",\"MetadataHttpHeaders\":[\"Content-Length\",\"Set-Cookie\"," + + "\"Content-Type\"]}")); + } + + @Test + void metadataHeaderCannotBeTheHmacSignatureHeader() { + AwsException e = assertThrows(AwsException.class, () -> WebhookEventsConfigurations.validateForCreate( + wrapped("{\"AuthConfiguration\":{\"HmacAuthConfiguration\":{" + HMAC_BASE + "}},\"RoleArn\":\"" + ROLE + + "\",\"MetadataHttpHeaders\":[\"x-SIG\"]}"))); + assertEquals("WebhookEventsConfiguration.MetadataHttpHeaders can't include the header x-SIG because it is " + + "HmacAuthConfiguration.SignatureHttpHeader", e.getMessage()); + } + + @Test + void updateRefusesAnotherVariantAnyCredentialAndAnotherAuthType() { + assertEquals("EventSource type is immutable: the configuration variant must remain WEBHOOK_EVENTS", + updateRefusal("{\"PartnerEventsConfiguration\":{}}", "StaticTokenAuthConfiguration")); + assertEquals("UpdateEventSource does not accept SecretValue, Username or Password; webhook credentials " + + "change only through RotateWebhookCredentials", updateRefusal("{\"WebhookEventsConfiguration\":" + + "{\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{\"Username\":\"u\"}}}}", + "BasicHttpAuthConfiguration")); + assertEquals("The webhook authentication type can't be changed after the EventSource is created", + updateRefusal("{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + + "{\"BasicHttpAuthConfiguration\":{}}}}", "StaticTokenAuthConfiguration")); + assertEquals("Exactly one Configuration sub-field must be provided", + updateRefusal("{}", "StaticTokenAuthConfiguration")); + } + + @Test + void updateKeepsApplyingTheRulesOfCreate() { + assertEquals("WebhookEventsConfiguration.AuthConfiguration.StaticTokenAuthConfiguration.TokenHttpHeader " + + "can't be the header Host: it is not allowed. Header names are case-insensitive.", + updateRefusal("{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + + "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"Host\"}}}}", + "StaticTokenAuthConfiguration")); + } + + // ──────────────────────────── Forms ──────────────────────────── + + @Test + void echoLeavesOutSecretsAndKeepsWhatTheRequestGave() { + JsonNode webhook = config("{\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{\"Username\":\"u\"," + + "\"Password\":\"secret1\"}},\"RoleArn\":\"" + ROLE + "\",\"MetadataHttpHeaders\":[]}"); + assertEquals(MAPPER.createObjectNode().set("WebhookEventsConfiguration", config("{\"AuthConfiguration\":" + + "{\"BasicHttpAuthConfiguration\":{}},\"RoleArn\":\"" + ROLE + "\",\"MetadataHttpHeaders\":[]}")), + WebhookEventsConfigurations.echo(webhook)); + + JsonNode hmac = config("{\"AuthConfiguration\":{\"HmacAuthConfiguration\":{" + HMAC_BASE + + ",\"SecretValue\":\"0123456789abcdef\",\"SecretEncoding\":\"RAW\"}},\"RoleArn\":\"" + ROLE + "\"}"); + JsonNode echoed = WebhookEventsConfigurations.echo(hmac).path("WebhookEventsConfiguration") + .path("AuthConfiguration").path("HmacAuthConfiguration"); + assertFalse(echoed.has("SecretValue")); + assertEquals("RAW", echoed.path("SecretEncoding").asText()); + assertNull(WebhookEventsConfigurations.echo(hmac).path("WebhookEventsConfiguration").get("Description")); + } + + @Test + void authTypeNamesTheOneAuthenticationMember() { + assertEquals("HmacAuthConfiguration", WebhookEventsConfigurations.authType(config( + "{\"AuthConfiguration\":{\"HmacAuthConfiguration\":{}}}"))); + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private static String withReplaced(String extra) { + String base = HMAC_BASE; + for (String member : List.of("SignedMessageComposition")) { + if (extra.contains("\"" + member + "\"")) { + base = base.replace(",\"SignedMessageComposition\":\"BODY\"", ""); + } + } + return base + "," + extra; + } + + private static List violations(String operation, JsonNode request) { + try { + EventBridgeV2RequestShapes.check(operation, request); + return List.of(); + } catch (AwsException e) { + return List.of(e.getMessage().replaceFirst("^\\d+ validation errors? detected: ", "").split("; ")); + } + } + + private static JsonNode create(String json) { + return json(json); + } + + private static JsonNode json(String json) { + try { + return MAPPER.readTree(json); + } catch (Exception e) { + throw new IllegalArgumentException(json, e); + } + } + + private static JsonNode wrapped(String webhookJson) { + return json("{\"WebhookEventsConfiguration\":" + webhookJson + "}"); + } + + private static JsonNode config(String webhookJson) { + return json(webhookJson); + } + + private static String withTags(int count) { + StringBuilder tags = new StringBuilder(); + for (int i = 0; i < count; i++) { + tags.append(i == 0 ? "" : ",").append("\"k").append(i).append("\":\"v\""); + } + return "{\"Name\":\"hook\",\"EventBusArn\":\"" + BUS + "\",\"Configuration\":{\"WebhookEventsConfiguration\":" + + "{\"AuthConfiguration\":" + STATIC_AUTH + ",\"RoleArn\":\"" + ROLE + "\"}},\"Tags\":{" + tags + "}}"; + } + + private static List webhookViolations(String webhookJson) { + return violations("CreateEventSource", json("{\"Name\":\"hook\",\"EventBusArn\":\"" + BUS + + "\",\"Configuration\":{\"WebhookEventsConfiguration\":" + webhookJson + "}}")); + } + + private static List hmacViolations(String extra) { + String members = HMAC_BASE; + if (extra.contains("\"Algorithm\"")) { + members = members.replace("\"Algorithm\":\"SHA256\",", ""); + } + return webhookViolations("{\"AuthConfiguration\":{\"HmacAuthConfiguration\":{" + members + "," + extra + + "}},\"RoleArn\":\"" + ROLE + "\"}"); + } + + private static String createRefusal(String configurationJson) { + return assertThrows(AwsException.class, + () -> WebhookEventsConfigurations.validateForCreate(json(configurationJson))).getMessage(); + } + + private static String webhookRefusal(String authJson) { + return createRefusal("{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + authJson + ",\"RoleArn\":\"" + + ROLE + "\"}}"); + } + + private static String hmacRefusal(String extra) { + return webhookRefusal("{\"HmacAuthConfiguration\":{" + withReplaced(extra) + "}}"); + } + + private static String metadataRefusal(String headers) { + return createRefusal("{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + STATIC_AUTH + .replace("X-Token", "x-token") + ",\"RoleArn\":\"" + ROLE + "\",\"MetadataHttpHeaders\":" + headers + + "}}"); + } + + private static String updateRefusal(String configurationJson, String storedAuthType) { + return assertThrows(AwsException.class, () -> WebhookEventsConfigurations.validateForUpdate( + json(configurationJson), storedAuthType)).getMessage(); + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/WebhookTokensTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/WebhookTokensTest.java new file mode 100644 index 0000000000..3a836afdf4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/WebhookTokensTest.java @@ -0,0 +1,25 @@ +package io.floci.aws.services.eventbridgev2; + +import org.junit.jupiter.api.Test; + +import java.security.SecureRandom; +import java.util.Base64; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class WebhookTokensTest { + private final SecureRandom random = new SecureRandom(); + + @Test + void hostIdIsAnAFollowedBy37LowercaseBase32Characters() { + assertTrue(WebhookTokens.newHostId(random).matches("a[a-z2-7]{37}")); + } + + @Test + void tokenIsK1AndFortyEightBytesOfUnpaddedBase64Url() { + String token = WebhookTokens.newToken(WebhookTokens.newHostId(random), random); + assertTrue(token.matches("k1[A-Za-z0-9_-]{64}"), token); + assertEquals(48, Base64.getUrlDecoder().decode(token.substring(2)).length); + } +} diff --git a/tools/aws/regen_eventbridgev2_shapes.py b/tools/aws/regen_eventbridgev2_shapes.py index b78c37acc6..ae01a9ae10 100644 --- a/tools/aws/regen_eventbridgev2_shapes.py +++ b/tools/aws/regen_eventbridgev2_shapes.py @@ -2,6 +2,8 @@ """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. +The order of every enum's values and of every structure's members is the order AWS answers in, +which the model does not give. """ from __future__ import annotations @@ -12,25 +14,101 @@ 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") +OPERATIONS = ("CreateEventSource", "DeleteEventSource", "DescribeEventSource", "ListEventSources", + "UpdateEventSource") + +# The order AWS lists the values of a violated enum in. It follows no rule, so each is measured. +ENUM_ORDER = { + "WebhookHmacAlgorithm": ["SHA1", "SHA256"], + "WebhookHmacEncoding": ["BASE64", "HEX"], + "WebhookSignedMessageComposition": ["TIMESTAMP_DOT_BODY", "BODY", "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY"], + "WebhookSecretEncoding": ["RAW", "BASE64"], + "WebhookDeduplicationType": ["CONTENT_BASED"], + "LogLevel": ["ERROR", "INFO", "OFF"], + "IncludePayload": ["ON_ERROR_ONLY", "FULL"], +} + +# The one structure AWS walks out of hash order, as measured. +MEMBER_ORDER = { + "ListEventSourcesRequest": ["MaxResults", "NextToken", "NamePrefix", "EventBusArn"], +} -def sort_enums(model: dict) -> dict: - """The model, with every enum's values sorted. +def java_hash(text: str) -> int: + """`String.hashCode` of `text`, as an unsigned 32-bit integer.""" + value = 0 + data = text.encode("utf-16-be") + for index in range(0, len(data), 2): + value = (value * 31 + int.from_bytes(data[index:index + 2], "big")) & 0xFFFFFFFF + return value - 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(): + +def table_size(count: int) -> int: + """The bucket count of a default `java.util.HashMap` holding `count` entries.""" + size = 16 + while count > size * 3 // 4: + size *= 2 + return size + + +def hash_order(members: list[str]) -> list[str]: + """`members` in the iteration order of a `java.util.HashMap` keyed by each name with a lower-case + first letter. Names that share a bucket come in alphabetical order.""" + size = table_size(len(members)) + + def bucket(member: str) -> int: + code = java_hash(member[0].lower() + member[1:]) + return (code ^ (code >> 16)) & (size - 1) + + return sorted(members, key=lambda member: (bucket(member), member[0].lower() + member[1:])) + + +def reachable(model: dict, operations: tuple[str, ...]) -> set[str]: + """The names of the shapes the input of `operations` reaches.""" + seen: set[str] = set() + pending = [model["operations"][name]["input"]["shape"] for name in operations] + while pending: + name = pending.pop() + if name in seen: + continue + seen.add(name) + shape = model["shapes"][name] + if shape["type"] == "structure": + pending.extend(spec["shape"] for spec in shape.get("members", {}).values()) + elif shape["type"] == "list": + pending.append(shape["member"]["shape"]) + elif shape["type"] == "map": + pending.append(shape["key"]["shape"]) + pending.append(shape["value"]["shape"]) + return seen + + +def prepare(model: dict) -> dict: + """The model with each vendored enum's values and each structure's members in the order AWS answers in.""" + for name in sorted(reachable(model, OPERATIONS)): + shape = model["shapes"][name] if "enum" in shape: - shape["enum"] = sorted(shape["enum"]) + if name not in ENUM_ORDER: + raise SystemExit(f"error: no measured order for the values of {name}: {shape['enum']}") + if sorted(ENUM_ORDER[name]) != sorted(shape["enum"]): + raise SystemExit(f"error: the model's values of {name} are {shape['enum']}, " + f"not the measured {ENUM_ORDER[name]}") + shape["enum"] = list(ENUM_ORDER[name]) + for name, shape in model["shapes"].items(): + if shape["type"] != "structure" or not shape.get("members"): + continue + members = shape["members"] + order = MEMBER_ORDER.get(name) or hash_order(list(members)) + if sorted(order) != sorted(members): + raise SystemExit(f"error: the measured members of {name} are {order}, the model's are {list(members)}") + shape["members"] = {member: members[member] for member in order} 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) + prepare=prepare) if __name__ == "__main__": diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py index dd9845268f..1f4b63a62e 100644 --- a/tools/aws/test_request_shapes.py +++ b/tools/aws/test_request_shapes.py @@ -591,16 +591,67 @@ 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(): +def test_eventbridgev2_shapes_keep_the_measured_orders_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"] + "ListEventSources", "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 + assert {name: shape["enum"] for name, shape in shapes.items() if "enum" in shape} == { + "WebhookHmacAlgorithm": ["SHA1", "SHA256"], + "WebhookHmacEncoding": ["BASE64", "HEX"], + "WebhookSignedMessageComposition": ["TIMESTAMP_DOT_BODY", "BODY", "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY"], + "WebhookSecretEncoding": ["RAW", "BASE64"], + "WebhookDeduplicationType": ["CONTENT_BASED"], + "LogLevel": ["ERROR", "INFO", "OFF"], + "IncludePayload": ["ON_ERROR_ONLY", "FULL"], + } + + +def test_eventbridgev2_shapes_list_members_in_the_order_aws_walks_them(): + shapes = json.loads(regen_eventbridgev2_shapes.OUTPUT.read_text(encoding="utf-8"))["shapes"] + + assert list(shapes["CreateEventSourceRequest"]["members"]) == [ + "Configuration", "ClientToken", "Name", "Description", "EventBusArn", "Tags"] + assert list(shapes["UpdateEventSourceRequest"]["members"]) == ["Configuration", "EventSourceArn", "Description"] + assert list(shapes["ListEventSourcesRequest"]["members"]) == [ + "MaxResults", "NextToken", "NamePrefix", "EventBusArn"] + assert list(shapes["WebhookEventsSourceConfiguration"]["members"]) == [ + "DeduplicationConfiguration", "KmsKeyIdentifier", "RoleArn", "LogConfiguration", "MetadataHttpHeaders", + "AuthConfiguration"] + assert list(shapes["WebhookHmacAuthConfiguration"]["members"])[:5] == [ + "SecretEncoding", "TimestampPrefix", "MessageIdHttpHeader", "SecretValue", "SignaturePrefix"] + assert list(shapes["WebhookStaticTokenAuthConfiguration"]["members"]) == ["SecretValue", "TokenHttpHeader"] + assert list(shapes["WebhookBasicHttpAuthConfiguration"]["members"]) == ["Password", "Username"] + + +def test_eventbridgev2_hash_order_follows_java_hash_map(): + assert regen_eventbridgev2_shapes.java_hash("name") == 3373707 + assert regen_eventbridgev2_shapes.table_size(12) == 16 + assert regen_eventbridgev2_shapes.table_size(13) == 32 + assert regen_eventbridgev2_shapes.hash_order(["Name", "ClientToken", "Configuration"]) == [ + "Configuration", "ClientToken", "Name"] + + +def test_eventbridgev2_prepare_refuses_an_enum_it_has_no_measured_order_for(): + model = {"operations": {name: {"input": {"shape": "Request"}} for name in regen_eventbridgev2_shapes.OPERATIONS}, + "shapes": {"Request": {"type": "structure", "members": {"Mode": {"shape": "Mode"}}}, + "Mode": {"type": "string", "enum": ["A", "B"]}}} + + with pytest.raises(SystemExit, match="no measured order for the values of Mode"): + regen_eventbridgev2_shapes.prepare(model) + + +def test_eventbridgev2_prepare_refuses_an_enum_whose_values_changed(): + model = {"operations": {name: {"input": {"shape": "Request"}} for name in regen_eventbridgev2_shapes.OPERATIONS}, + "shapes": {"Request": {"type": "structure", "members": {"Level": {"shape": "LogLevel"}}}, + "LogLevel": {"type": "string", "enum": ["OFF", "ERROR", "INFO", "DEBUG"]}}} + + with pytest.raises(SystemExit, match="LogLevel"): + regen_eventbridgev2_shapes.prepare(model) def test_config_shapes_keep_arn_bounds_and_leave_timestamps_to_handlers():