feat(eventbridgev2): manage webhook event sources (#9321)

Adds CreateEventSource, DescribeEventSource, ListEventSources,
UpdateEventSource and DeleteEventSource for EventBridge V2 webhook event
sources. Each source gets a webhook URL and a Secrets Manager secret owned by
events-webhook; DeleteEventSource schedules it for deletion, and
DeleteEventBus refuses a bus that still has event sources. UpdateEventSource
replaces the whole webhook configuration and stores a new source.

Requests are checked against the generated eventbridgev2 request shapes, with
the violation wording and order AWS answers in us-east-1. A ListEventSources
token belongs to its Region, EventBusArn and NamePrefix, and the stored
configuration keeps only the members the model declares. The webhook URL does
not accept requests yet.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-24 20:35:04 -04:00
1 parent f380fac5e6
commit c1fdd98a6d
22 files changed
+3726 -257

No files matched your search

@@ -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",
@@ -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);
}
}
@@ -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<String> name = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> secretString = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<List<Secret.Tag>> 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<String> secretString = ArgumentCaptor.forClass(String.class);
verify(secrets, times(4)).createSecret(any(), secretString.capture(), any(), any(), any(), any(), any(),
any());
List<String> 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<EventSourceV2> failing = spy(
AccountAwareStorageBackend.<EventSourceV2>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<String> 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<EventSourceV2> all = service.listEventSources(json("{}"), REGION).items();
assertEquals(4, all.size());
List<String> 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<EventSourceV2> first = service.listEventSources(json("{\"MaxResults\":2}"), REGION);
assertEquals(2, first.items().size());
PaginatedResult<EventSourceV2> 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<EventSourceV2> first = service.listEventSources(json("{" + filters + "}"), REGION);
PaginatedResult<EventSourceV2> 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<String> secretString = ArgumentCaptor.forClass(String.class);
verify(secrets).createSecret(any(), secretString.capture(), any(), any(), any(), any(), any(), any());
return secretString.getValue();
}
private static Set<String> names(PaginatedResult<EventSourceV2> 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;
}
}
}
@@ -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<String> 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<String> 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<String> 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;
}
}
@@ -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
@@ -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<String> 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<String> 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<String> 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<String> 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<String> 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<String, String> 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<String> 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<String> 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<String> 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<String> webhookViolations(String webhookJson) {
return violations("CreateEventSource", json("{\"Name\":\"hook\",\"EventBusArn\":\"" + BUS
+ "\",\"Configuration\":{\"WebhookEventsConfiguration\":" + webhookJson + "}}"));
}
private static List<String> 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();
}
}
@@ -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);
}
}