feat(eventbridgev2): encrypt the webhook secret with KmsKeyIdentifier (#9661)

#9321 stored a webhook event source's KmsKeyIdentifier without using it. The source's secret is now created with that key, an UpdateEventSource that changes it re-encrypts the secret, and one that leaves it out or sets "" returns the secret to the AWS managed key aws/secretsmanager. A key that does not exist answers AccessDeniedException with KMS_KEY_NOT_FOUND, and an AWS managed key, or a key ARN of another Region or account, answers InvalidInputException, each at the point AWS checks it.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-28 10:20:52 -04:00
1 parent 927ff3a001
commit 31d2222c93
11 files changed
+470 -19

No files matched your search

+4 -1
View File
@@ -145,7 +145,10 @@ section covers the webhook kind. A `PartnerEventsConfiguration` always fails, as
Basic keeps its username. A repeat of a `ClientToken` of the source with the same request changes nothing.
Floci forgets a token 8 hours after its rotation. A rotation answers `InvalidStateException` (409) when the
secret is scheduled for deletion or deleted.
- `KmsKeyIdentifier` is stored and returned. It is not used for the secret.
- `KmsKeyIdentifier` is returned as given, and the secret is encrypted with that key. An update that changes the key
re-encrypts the secret, and one that leaves it out or sets `""` returns the secret to the default key. A key that
does not exist answers `AccessDeniedException` (403), and an AWS managed key such as `alias/aws/secretsmanager`
answers `InvalidInputException` (400), and so does a key ARN of another Region or account.
- `DeleteEventSource` schedules the secret for deletion at once.
- `DescribeEventSource` and `ListEventSources` return `Revoked` once the source is revoked, and leave it out before.
@@ -23,6 +23,8 @@ import io.floci.aws.services.eventbridge.model.Target;
import io.floci.aws.services.eventbridgev2.model.EventBusV2;
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
import io.floci.aws.services.eventbridgev2.model.RotationRequest;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.kms.model.KmsKey;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.Secret;
import jakarta.enterprise.context.ApplicationScoped;
@@ -38,6 +40,7 @@ import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
@@ -74,20 +77,23 @@ public class EventBridgeV2EventSources implements Resettable {
private final WebhookDeduplication deduplication;
private final TlsCertificateManager certificateManager;
private final EventBridgeService eventBridge;
private final KmsService kms;
@Inject
public EventBridgeV2EventSources(StorageFactory storageFactory, SecretsManagerService secrets,
RegionResolver regionResolver, EmulatorConfig config,
TlsCertificateManager certificateManager, EventBridgeService eventBridge) {
TlsCertificateManager certificateManager, EventBridgeService eventBridge,
KmsService kms) {
this(storageFactory.create("eventbridgev2", "eventbridgev2-event-sources.json",
new TypeReference<Map<String, EventSourceV2>>() {}),
secrets, regionResolver, Clock.systemUTC(), config.effectiveBaseUrl(), certificateManager,
eventBridge);
eventBridge, kms);
}
EventBridgeV2EventSources(AccountAwareStorageBackend<EventSourceV2> sources, SecretsManagerService secrets,
RegionResolver regionResolver, Clock clock, String baseUrl,
TlsCertificateManager certificateManager, EventBridgeService eventBridge) {
TlsCertificateManager certificateManager, EventBridgeService eventBridge,
KmsService kms) {
this.sources = sources;
this.secrets = secrets;
this.regionResolver = regionResolver;
@@ -95,6 +101,7 @@ public class EventBridgeV2EventSources implements Resettable {
this.baseUrl = URI.create(baseUrl);
this.certificateManager = certificateManager;
this.eventBridge = eventBridge;
this.kms = kms;
this.deduplication = new WebhookDeduplication(clock);
}
@@ -115,6 +122,9 @@ public class EventBridgeV2EventSources implements Resettable {
if (roleArn != null) {
requireOwnAccount(roleArn);
}
String keyIdentifier = WebhookEventsConfigurations.keyIdentifier(
configuration.path(WebhookEventsConfigurations.WEBHOOK));
WebhookEventsConfigurations.requireKeyArnOfCaller(keyIdentifier, region, regionResolver.getAccountId());
String clientToken = request.path("ClientToken").textValue();
if (clientToken == null) {
throw EventBridgeV2Service.invalidInput("ClientToken is required");
@@ -132,15 +142,19 @@ public class EventBridgeV2EventSources implements Resettable {
// The request carries credentials, so only its hash is kept.
String requestHash = Digests.sha256Hex(EventBridgeV2Service.withoutClientToken(request));
requireBus(eventBusArn, findBusByName);
KmsKey kmsKey = keyIdentifier == null ? null : requireKey(keyIdentifier, region);
Optional<EventSourceV2> retried = retriedSource(region, clientToken, requestHash);
if (retried.isPresent()) {
return retried.get();
}
requireBus(eventBusArn, findBusByName);
String key = EventBridgeV2Service.storageKey(region, name);
if (sources.get(key).isPresent()) {
throw new AwsException("ResourceAlreadyExistsException", "Resource already exists", 409);
}
if (kmsKey != null) {
refuseAwsManagedKey(keyIdentifier, kmsKey, region);
}
String hostId = WebhookTokens.newHostId(random);
Instant now = clock.instant();
@@ -149,7 +163,13 @@ public class EventBridgeV2EventSources implements Resettable {
source.setArn(sourceArn(region, "webhook", name));
source.setEventBusArn(eventBusArn);
source.setDescription(request.path("Description").textValue());
source.setConfiguration(WebhookEventsConfigurations.echo(webhook));
JsonNode echoed = WebhookEventsConfigurations.echo(webhook);
if (keyIdentifier == null) {
// Create's Describe leaves out an empty KmsKeyIdentifier, update's echoes it.
((ObjectNode) echoed.get(WebhookEventsConfigurations.WEBHOOK)).remove(
WebhookEventsConfigurations.KMS_KEY_IDENTIFIER);
}
source.setConfiguration(echoed);
source.setState(EventBridgeV2Service.ACTIVE);
source.setCreationTime(now);
source.setLastModifiedTime(now);
@@ -158,7 +178,7 @@ public class EventBridgeV2EventSources implements Resettable {
source.setCreateRequestHash(requestHash);
source.setWebhookHostId(hostId);
source.setWebhookToken(WebhookTokens.newToken(hostId, random));
source.setSecretArn(createSecret(webhook, region));
source.setSecretArn(createSecret(webhook, keyIdentifier, region));
try {
sources.put(key, source);
} catch (RuntimeException e) {
@@ -298,10 +318,20 @@ public class EventBridgeV2EventSources implements Resettable {
}
JsonNode webhook = configuration == null ? null : WebhookEventsConfigurations.validateForUpdate(
configuration, WebhookEventsConfigurations.authType(
source.getConfiguration().get(WebhookEventsConfigurations.WEBHOOK)));
source.getConfiguration().get(WebhookEventsConfigurations.WEBHOOK)),
region, regionResolver.getAccountId());
requireNotRevoked(source, "EventSource is revoked and cannot be updated");
String newKey = webhook == null ? null : WebhookEventsConfigurations.keyIdentifier(webhook);
if (newKey != null) {
refuseAwsManagedKey(newKey, requireKey(newKey, region), region);
}
if (webhook != null && !Objects.equals(newKey, WebhookEventsConfigurations.keyIdentifier(
source.getConfiguration().get(WebhookEventsConfigurations.WEBHOOK)))) {
secrets.updateSecret(source.getSecretArn(), null, newKey == null ? "" : newKey, region);
}
EventSourceV2 changed = copyOf(source);
changed.setDescription(request.hasNonNull("Description") ? request.get("Description").textValue()
: source.getDescription());
@@ -616,7 +646,33 @@ public class EventBridgeV2EventSources implements Resettable {
deduplication.clear();
}
private String createSecret(JsonNode webhook, String region) {
private KmsKey requireKey(String keyIdentifier, String region) {
try {
return kms.describeKey(keyIdentifier, region);
} catch (AwsException e) {
if (!"NotFoundException".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("The KMS key of an event source was not found: {0}", e.getMessage());
throw new AwsException("AccessDeniedException",
"KMS_KEY_NOT_FOUND: The event bus's KMS key does not exist.", 403);
}
}
private void refuseAwsManagedKey(String keyIdentifier, KmsKey key, String region) {
if (!kms.isAwsManagedKey(key.getArn())) {
return;
}
boolean alias = keyIdentifier.startsWith("alias/") || keyIdentifier.contains(":alias/");
String shown = !alias ? key.getArn()
: AwsArnUtils.looksLikeArn(keyIdentifier) ? keyIdentifier
: regionResolver.buildArn("kms", region, keyIdentifier);
throw EventBridgeV2Service.invalidInput("The KMS key " + shown + " can't be used for a webhook EventSource "
+ "because it is an AWS managed key. Supply a customer managed key, or omit KmsKeyIdentifier to use "
+ "the AWS managed key aws/secretsmanager");
}
private String createSecret(JsonNode webhook, String keyIdentifier, String region) {
JsonNode auth = webhook.get("AuthConfiguration");
String authType = WebhookEventsConfigurations.authType(webhook);
String secretString;
@@ -632,7 +688,7 @@ public class EventBridgeV2EventSources implements Resettable {
secretString = staticToken.hasNonNull("SecretValue") ? staticToken.get("SecretValue").textValue()
: generated();
}
return secrets.createSecret("events-webhook!" + UUID.randomUUID(), secretString, null, null, null,
return secrets.createSecret("events-webhook!" + UUID.randomUUID(), secretString, null, null, keyIdentifier,
List.of(new Secret.Tag("aws:secretsmanager:owningService", OWNING_SERVICE)), OWNING_SERVICE,
region).getArn();
}
@@ -2,6 +2,7 @@ package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import java.nio.charset.StandardCharsets;
@@ -25,6 +26,7 @@ final class WebhookEventsConfigurations {
static final String STATIC_TOKEN = "StaticTokenAuthConfiguration";
static final String BASIC = "BasicHttpAuthConfiguration";
static final String HMAC = "HmacAuthConfiguration";
static final String KMS_KEY_IDENTIFIER = "KmsKeyIdentifier";
private static final String AUTH = "WebhookEventsConfiguration.AuthConfiguration";
private static final String METADATA = "WebhookEventsConfiguration.MetadataHttpHeaders";
@@ -56,7 +58,8 @@ final class WebhookEventsConfigurations {
* Checks an update request's {@code Configuration} against the authentication type the source was created
* with, and returns its webhook configuration.
*/
static JsonNode validateForUpdate(JsonNode configuration, String storedAuthType) {
static JsonNode validateForUpdate(JsonNode configuration, String storedAuthType, String region,
String accountId) {
Map.Entry<String, JsonNode> variant = onlyVariant(configuration);
if (!WEBHOOK.equals(variant.getKey())) {
throw variantImmutable(ServiceEventsConfigurations.WEBHOOK_TYPE);
@@ -75,10 +78,39 @@ final class WebhookEventsConfigurations {
if (present.size() == 1 && !present.getFirst().equals(storedAuthType)) {
throw invalidInput("The webhook authentication type can't be changed after the EventSource is created");
}
requireKeyArnOfCaller(keyIdentifier(webhook), region, accountId);
validateWebhook(webhook);
return webhook;
}
/** The {@code KmsKeyIdentifier} of a webhook configuration, or null when it is absent or empty. */
static String keyIdentifier(JsonNode webhook) {
String identifier = webhook.path(KMS_KEY_IDENTIFIER).textValue();
return identifier == null || identifier.isEmpty() ? null : identifier;
}
/** Refuses a key ARN of another Region, then of another account. Any other identifier passes. */
static void requireKeyArnOfCaller(String keyIdentifier, String region, String accountId) {
if (!AwsArnUtils.looksLikeArn(keyIdentifier)) {
return;
}
AwsArnUtils.Arn arn;
try {
arn = AwsArnUtils.parse(keyIdentifier);
} catch (IllegalArgumentException ignored) {
// Too few fields to hold a Region, so the key lookup refuses it.
return;
}
if (!arn.region().equals(region)) {
throw invalidInput(WEBHOOK + "." + KMS_KEY_IDENTIFIER + " region '" + arn.region()
+ "' must match the caller's region '" + region + "'");
}
if (!arn.accountId().equals(accountId)) {
throw invalidInput(WEBHOOK + "." + KMS_KEY_IDENTIFIER + " account '" + arn.accountId()
+ "' must match the caller's account '" + accountId + "'");
}
}
private static List<Map.Entry<String, JsonNode>> variants(JsonNode configuration) {
List<Map.Entry<String, JsonNode>> members = new ArrayList<>();
for (Map.Entry<String, JsonNode> member : configuration.properties()) {
@@ -10,6 +10,7 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.eventbridge.model.Target;
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.Secret;
import io.floci.aws.testing.ManualClock;
@@ -72,7 +73,7 @@ class AwsServiceEventSourcesTest {
when(secrets.createSecret(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(secret);
EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources(
AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock,
"http://floci.test:4566", certificateManager, eventBridge);
"http://floci.test:4566", certificateManager, eventBridge, mock(KmsService.class));
service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT),
AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, eventSources, clock, true);
bus = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn();
@@ -13,6 +13,7 @@ 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.AccessDeniedException;
import software.amazon.awssdk.services.eventbridgev2.model.CreateEventSourceResponse;
import software.amazon.awssdk.services.eventbridgev2.model.DescribeEventSourceResponse;
import software.amazon.awssdk.services.eventbridgev2.model.EventSourceConfiguration;
@@ -24,6 +25,8 @@ import software.amazon.awssdk.services.eventbridgev2.model.ResourceInUseExceptio
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.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.CreateKeyRequest;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.DescribeSecretResponse;
@@ -235,6 +238,62 @@ class EventBridgeV2EventSourceIntegrationTest {
}
}
@Test
void aWebhookSecretIsEncryptedWithTheKmsKeyOfTheSource() {
String suffix = suffix();
try (EventBridgeV2Client events = events(); SecretsManagerClient secrets = secrets();
KmsClient kms = kms()) {
String bus = events.createEventBus(request -> request.name("v2-kms-" + suffix)).eventBusArn();
String first = "alias/hook-one-" + suffix;
String second = "alias/hook-two-" + suffix;
kms.createAlias(request -> request.aliasName(first)
.targetKeyId(kms.createKey(CreateKeyRequest.builder().build()).keyMetadata().keyId()));
kms.createAlias(request -> request.aliasName(second)
.targetKeyId(kms.createKey(CreateKeyRequest.builder().build()).keyMetadata().keyId()));
CreateEventSourceResponse created = events.createEventSource(request -> request.name("hook-" + suffix)
.eventBusArn(bus).configuration(EventSourceConfiguration.fromWebhookEventsConfiguration(
webhook -> webhook.roleArn(ROLE).kmsKeyIdentifier(first)
.authConfiguration(staticToken("X-Token", "s3cret-token")))));
String secretArn = created.eventSourceDetails().webhookDetails().secretArn();
assertEquals(first, secrets.describeSecret(request -> request.secretId(secretArn)).kmsKeyId());
assertEquals(first, events.describeEventSource(request -> request
.eventSourceArn(created.eventSourceArn())).configuration().webhookEventsConfiguration()
.kmsKeyIdentifier());
events.updateEventSource(request -> request.eventSourceArn(created.eventSourceArn())
.configuration(EventSourceConfiguration.fromWebhookEventsConfiguration(
webhook -> webhook.roleArn(ROLE).kmsKeyIdentifier(second)
.authConfiguration(staticToken("X-Token", null)))));
assertEquals(second, secrets.describeSecret(request -> request.secretId(secretArn)).kmsKeyId());
assertEquals("s3cret-token", secrets.getSecretValue(request -> request.secretId(secretArn))
.secretString());
EventSourceConfiguration managed = EventSourceConfiguration.fromWebhookEventsConfiguration(
webhook -> webhook.roleArn(ROLE).kmsKeyIdentifier("alias/aws/secretsmanager")
.authConfiguration(staticToken("X-Token", null)));
InvalidInputException awsManaged = assertThrows(InvalidInputException.class, () -> events
.createEventSource(request -> request.name("managed-" + suffix).eventBusArn(bus)
.configuration(managed)));
assertEquals("The KMS key arn:aws:kms:us-east-1:000000000000:alias/aws/secretsmanager can't be used "
+ "for a webhook EventSource because it is an AWS managed key. Supply a customer managed key, or "
+ "omit KmsKeyIdentifier to use the AWS managed key aws/secretsmanager",
awsManaged.awsErrorDetails().errorMessage());
EventSourceConfiguration missing = EventSourceConfiguration.fromWebhookEventsConfiguration(
webhook -> webhook.roleArn(ROLE).kmsKeyIdentifier("alias/none-" + suffix)
.authConfiguration(staticToken("X-Token", null)));
AccessDeniedException noKey = assertThrows(AccessDeniedException.class, () -> events
.createEventSource(request -> request.name("nokey-" + suffix).eventBusArn(bus)
.configuration(missing)));
assertEquals("KMS_KEY_NOT_FOUND: The event bus's KMS key does not exist.",
noKey.awsErrorDetails().errorMessage());
events.deleteEventSource(request -> request.eventSourceArn(created.eventSourceArn()));
events.deleteEventBus(request -> request.eventBusArn(bus));
}
}
@Test
void aSourceWhoseSecretIsAlreadyScheduledForDeletionCanBeDeleted() {
String suffix = suffix();
@@ -289,6 +348,10 @@ class EventBridgeV2EventSourceIntegrationTest {
return AwsTestClients.create(SecretsManagerClient.builder(), "000000000000", Region.US_EAST_1);
}
private static KmsClient kms() {
return AwsTestClients.create(KmsClient.builder(), "000000000000", Region.US_EAST_1);
}
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
@@ -11,6 +11,8 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.eventbridgev2.model.EventBusV2;
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.kms.model.KmsKey;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.Secret;
import io.floci.aws.testing.ManualClock;
@@ -58,6 +60,7 @@ class EventBridgeV2EventSourcesTest {
private EventBridgeV2Service service;
private ManualClock clock;
private EventBridgeService eventBridge;
private KmsService kms;
private String bus;
@BeforeEach
@@ -73,9 +76,10 @@ class EventBridgeV2EventSourcesTest {
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
certificateManager = mock(TlsCertificateManager.class);
eventBridge = mock(EventBridgeService.class);
kms = mock(KmsService.class);
EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources(
AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, "http://floci.test:4566",
certificateManager, eventBridge);
certificateManager, eventBridge, kms);
service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT),
AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, mock(EventBridgeV2Delivery.class),
eventSources, clock, true);
@@ -394,7 +398,7 @@ class EventBridgeV2EventSourcesTest {
doThrow(failure).when(failing).put(any(), any());
EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources(failing, secrets,
new RegionResolver(REGION, ACCOUNT), clock, "http://floci.test:4566",
certificateManager, eventBridge);
certificateManager, eventBridge, kms);
EventBusV2 existing = new EventBusV2();
existing.setArn(bus);
@@ -710,6 +714,292 @@ class EventBridgeV2EventSourcesTest {
assertTrue(missing.getMessage().startsWith("2 validation errors detected: Value null at "), missing.getMessage());
}
// ──────────────────────────── KmsKeyIdentifier ────────────────────────────
private static final String KEY_ARN =
"arn:aws:kms:us-east-1:000000000000:key/1234abcd-12ab-34cd-56ef-1234567890ab";
private void customerKey(String identifier) {
stubKey(identifier, KEY_ARN, false);
}
private void stubKey(String identifier, String keyArn, boolean awsManaged) {
KmsKey key = new KmsKey();
key.setArn(keyArn);
when(kms.describeKey(identifier, REGION)).thenReturn(key);
when(kms.isAwsManagedKey(keyArn)).thenReturn(awsManaged);
}
private void missingKey(String identifier) {
when(kms.describeKey(identifier, REGION)).thenThrow(
new AwsException("NotFoundException", "Alias is not found.", 400));
}
private static ObjectNode withKey(ObjectNode request, String identifier) {
((ObjectNode) request.get("Configuration").get("WebhookEventsConfiguration"))
.put("KmsKeyIdentifier", identifier);
return request;
}
private JsonNode updateWithKey(EventSourceV2 source, String identifier) {
String key = identifier == null ? "" : ",\"KmsKeyIdentifier\":\"" + identifier + "\"";
return json("{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":"
+ "{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + STATIC_AUTH + ",\"RoleArn\":\"" + ROLE
+ "\"" + key + "}}}");
}
private void assertCreateFails(ObjectNode request, String code, int status, String message) {
AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(request, REGION));
assertEquals(code, e.getErrorCode());
assertEquals(status, e.getHttpStatus());
assertEquals(message, e.getMessage());
}
private static final String KEY_MISSING = "KMS_KEY_NOT_FOUND: The event bus's KMS key does not exist.";
@Test
void createRefusesAKeyArnOfAnotherRegionBeforeAnotherAccountAndBeforeTheClientToken() {
ObjectNode request = withKey(create("hook", bus, STATIC_AUTH),
"arn:aws:kms:eu-west-1:111111111111:key/1234abcd-12ab-34cd-56ef-1234567890ab");
request.remove("ClientToken");
assertCreateFails(request, "InvalidInputException", 400,
"WebhookEventsConfiguration.KmsKeyIdentifier region 'eu-west-1' must match the caller's region "
+ "'us-east-1'");
}
@Test
void createRefusesAKeyOrAliasArnOfAnotherAccountBeforeTheBusLookup() {
String missingBus = "arn:aws:events:us-east-1:000000000000:event-busv2/missing/abcdefghijklmnopqrstuvwxy";
String message = "WebhookEventsConfiguration.KmsKeyIdentifier account '111111111111' must match the "
+ "caller's account '000000000000'";
assertCreateFails(withKey(create("hook", missingBus, STATIC_AUTH),
"arn:aws:kms:us-east-1:111111111111:key/1234abcd-12ab-34cd-56ef-1234567890ab"),
"InvalidInputException", 400, message);
assertCreateFails(withKey(create("hook", missingBus, STATIC_AUTH),
"arn:aws:kms:us-east-1:111111111111:alias/mine"), "InvalidInputException", 400, message);
}
@Test
void createRefusesAKeyArnOfAnotherRegionBeforeAuthChecks() {
ObjectNode request = withKey(create("hook", bus, "{\"StaticTokenAuthConfiguration\":"
+ "{\"TokenHttpHeader\":\"Host\"}}"), "arn:aws:kms:eu-west-1:000000000000:alias/mine");
assertCreateFails(request, "InvalidInputException", 400,
"WebhookEventsConfiguration.KmsKeyIdentifier region 'eu-west-1' must match the caller's region "
+ "'us-east-1'");
}
@Test
void createAnswersAMissingKeyAfterTheBusLookup() {
missingKey("alias/gone");
String missingBus = "arn:aws:events:us-east-1:000000000000:event-busv2/missing/abcdefghijklmnopqrstuvwxy";
assertCreateFails(withKey(create("hook", missingBus, STATIC_AUTH), "alias/gone"),
"ResourceNotFoundException", 404, "Resource does not exist");
assertCreateFails(withKey(create("hook", bus, STATIC_AUTH), "alias/gone"),
"AccessDeniedException", 403, KEY_MISSING);
verify(secrets, never()).createSecret(any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
void createAnswersAMissingKeyForAReplayBeforeTheIdempotencyConflict() {
service.createEventSource(create("hook", bus, STATIC_AUTH, "\"ClientToken\":\"t-1\""), REGION);
missingKey("alias/gone");
assertCreateFails(withKey(create("hook", bus, STATIC_AUTH, "\"ClientToken\":\"t-1\""), "alias/gone"),
"AccessDeniedException", 403, KEY_MISSING);
}
@Test
void createAnswersAMissingKeyBeforeTheNameClash() {
service.createEventSource(create("hook", bus, STATIC_AUTH), REGION);
missingKey("alias/gone");
assertCreateFails(withKey(create("hook", bus, STATIC_AUTH, "\"ClientToken\":\"other\""), "alias/gone"),
"AccessDeniedException", 403, KEY_MISSING);
}
@Test
void createStillReplaysWhenTheKeyExists() {
customerKey("alias/mine");
ObjectNode request = withKey(create("hook", bus, STATIC_AUTH, "\"ClientToken\":\"t-1\""), "alias/mine");
EventSourceV2 first = service.createEventSource(request, REGION);
assertEquals(first.getArn(), service.createEventSource(request, REGION).getArn());
}
@Test
void createRefusesAnAwsManagedKeyAfterTheNameClash() {
stubKey("alias/aws/secretsmanager", "arn:aws:kms:us-east-1:000000000000:key/aws-key", true);
service.createEventSource(create("hook", bus, STATIC_AUTH), REGION);
assertCreateFails(withKey(create("hook", bus, STATIC_AUTH, "\"ClientToken\":\"other\""),
"alias/aws/secretsmanager"), "ResourceAlreadyExistsException", 409, "Resource already exists");
assertCreateFails(withKey(create("second", bus, STATIC_AUTH), "alias/aws/secretsmanager"),
"InvalidInputException", 400, "The KMS key "
+ "arn:aws:kms:us-east-1:000000000000:alias/aws/secretsmanager can't be used for a webhook "
+ "EventSource because it is an AWS managed key. Supply a customer managed key, or omit "
+ "KmsKeyIdentifier to use the AWS managed key aws/secretsmanager");
verify(secrets, times(1)).createSecret(any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
void createNamesTheKeyArnOrTheAliasArnOfAnAwsManagedKey() {
String keyArn = "arn:aws:kms:us-east-1:000000000000:key/aws-key";
String aliasArn = "arn:aws:kms:us-east-1:000000000000:alias/aws/secretsmanager";
stubKey("aws-key", keyArn, true);
stubKey(keyArn, keyArn, true);
stubKey(aliasArn, keyArn, true);
String tail = " can't be used for a webhook EventSource because it is an AWS managed key. Supply a "
+ "customer managed key, or omit KmsKeyIdentifier to use the AWS managed key aws/secretsmanager";
assertCreateFails(withKey(create("a", bus, STATIC_AUTH), "aws-key"), "InvalidInputException", 400,
"The KMS key " + keyArn + tail);
assertCreateFails(withKey(create("b", bus, STATIC_AUTH), keyArn), "InvalidInputException", 400,
"The KMS key " + keyArn + tail);
assertCreateFails(withKey(create("c", bus, STATIC_AUTH), aliasArn), "InvalidInputException", 400,
"The KMS key " + aliasArn + tail);
}
@Test
void createEncryptsTheSecretWithTheKeyAndEchoesTheIdentifierAsGiven() {
customerKey("alias/mine");
EventSourceV2 source = service.createEventSource(withKey(create("hook", bus, STATIC_AUTH), "alias/mine"),
REGION);
ArgumentCaptor<String> kmsKeyId = ArgumentCaptor.forClass(String.class);
verify(secrets).createSecret(any(), any(), any(), any(), kmsKeyId.capture(), any(), any(), any());
assertEquals("alias/mine", kmsKeyId.getValue());
assertEquals("alias/mine", source.getConfiguration().get("WebhookEventsConfiguration")
.get("KmsKeyIdentifier").textValue());
}
@Test
void createAcceptsAnEmptyKeyIdentifierWithNoKeyAndLeavesItOutOfTheEcho() {
EventSourceV2 source = service.createEventSource(withKey(create("hook", bus, STATIC_AUTH), ""), REGION);
ArgumentCaptor<String> kmsKeyId = ArgumentCaptor.forClass(String.class);
verify(secrets).createSecret(any(), any(), any(), any(), kmsKeyId.capture(), any(), any(), any());
assertNull(kmsKeyId.getValue());
assertFalse(source.getConfiguration().get("WebhookEventsConfiguration").has("KmsKeyIdentifier"));
verify(kms, never()).describeKey(any(), any());
}
@Test
void createFailsBeforeStoringAnythingWhenTheSecretRefusesTheKey() {
customerKey("alias/disabled");
AwsException refused = new AwsException("EncryptionFailure", "Secrets Manager can't encrypt", 400);
when(secrets.createSecret(any(), any(), any(), any(), eq("alias/disabled"), any(), any(), any()))
.thenThrow(refused);
assertCreateFails(withKey(create("hook", bus, STATIC_AUTH), "alias/disabled"), "EncryptionFailure", 400,
"Secrets Manager can't encrypt");
assertTrue(names(service.listEventSources(json("{}"), REGION)).isEmpty());
}
@Test
void updateChecksTheKeyArnAfterTheSecretRefusalAndTheAuthTypeAndBeforeTheAuthHeaders() {
EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION);
String foreign = "arn:aws:kms:eu-west-1:000000000000:key/1234abcd-12ab-34cd-56ef-1234567890ab";
String message = "WebhookEventsConfiguration.KmsKeyIdentifier region 'eu-west-1' must match the caller's "
+ "region 'us-east-1'";
AwsException secret = assertThrows(AwsException.class, () -> service.updateEventSource(json(
"{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":{\"WebhookEventsConfiguration\":"
+ "{\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Token\","
+ "\"SecretValue\":\"secret-value\"}},\"RoleArn\":\"" + ROLE + "\",\"KmsKeyIdentifier\":\"" + foreign
+ "\"}}}"), REGION));
assertTrue(secret.getMessage().startsWith("UpdateEventSource does not accept SecretValue"));
AwsException type = assertThrows(AwsException.class, () -> service.updateEventSource(json(
"{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":{\"WebhookEventsConfiguration\":"
+ "{\"AuthConfiguration\":" + BASIC_AUTH + ",\"RoleArn\":\"" + ROLE
+ "\",\"KmsKeyIdentifier\":\"" + foreign + "\"}}}"), REGION));
assertTrue(type.getMessage().startsWith("The webhook authentication type can't be changed"));
AwsException header = assertThrows(AwsException.class, () -> service.updateEventSource(json(
"{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":{\"WebhookEventsConfiguration\":"
+ "{\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"Host\"}},"
+ "\"RoleArn\":\"" + ROLE + "\",\"KmsKeyIdentifier\":\"" + foreign + "\"}}}"), REGION));
assertEquals(message, header.getMessage());
AwsException account = assertThrows(AwsException.class, () -> service.updateEventSource(
updateWithKey(source, "arn:aws:kms:us-east-1:111111111111:alias/mine"), REGION));
assertEquals("WebhookEventsConfiguration.KmsKeyIdentifier account '111111111111' must match the caller's "
+ "account '000000000000'", account.getMessage());
}
@Test
void updateAnswersARevokedSourceBeforeTheKeyLookup() {
EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION);
service.revokeResource(json("{\"Arn\":\"" + source.getArn() + "\"}"), REGION);
missingKey("alias/gone");
AwsException e = assertThrows(AwsException.class,
() -> service.updateEventSource(updateWithKey(source, "alias/gone"), REGION));
assertEquals("EventSource is revoked and cannot be updated", e.getMessage());
}
@Test
void updateAnswersAMissingKeyThenAnAwsManagedKey() {
EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION);
missingKey("alias/gone");
AwsException missing = assertThrows(AwsException.class,
() -> service.updateEventSource(updateWithKey(source, "alias/gone"), REGION));
assertEquals("AccessDeniedException", missing.getErrorCode());
assertEquals(KEY_MISSING, missing.getMessage());
stubKey("alias/aws/secretsmanager", "arn:aws:kms:us-east-1:000000000000:key/aws-key", true);
AwsException managed = assertThrows(AwsException.class,
() -> service.updateEventSource(updateWithKey(source, "alias/aws/secretsmanager"), REGION));
assertEquals("InvalidInputException", managed.getErrorCode());
assertTrue(managed.getMessage().startsWith(
"The KMS key arn:aws:kms:us-east-1:000000000000:alias/aws/secretsmanager can't be used"));
verify(secrets, never()).updateSecret(any(), any(), any(), any());
}
@Test
void updateReEncryptsTheSecretWhenTheKeyChanges() {
customerKey("alias/one");
customerKey("alias/two");
EventSourceV2 source = service.createEventSource(create("hook", bus, STATIC_AUTH), REGION);
service.updateEventSource(updateWithKey(source, "alias/one"), REGION);
verify(secrets).updateSecret(source.getSecretArn(), null, "alias/one", REGION);
service.updateEventSource(updateWithKey(source, "alias/one"), REGION);
verify(secrets, times(1)).updateSecret(any(), any(), any(), any());
service.updateEventSource(updateWithKey(source, "alias/two"), REGION);
verify(secrets).updateSecret(source.getSecretArn(), null, "alias/two", REGION);
EventSourceV2 updated = service.updateEventSource(updateWithKey(source, null), REGION);
verify(secrets).updateSecret(source.getSecretArn(), null, "", REGION);
assertFalse(updated.getConfiguration().get("WebhookEventsConfiguration").has("KmsKeyIdentifier"));
}
@Test
void updateWithAnEmptyKeyIdentifierEchoesItAndReturnsTheSecretToTheDefaultKey() {
customerKey("alias/one");
EventSourceV2 source = service.createEventSource(withKey(create("hook", bus, STATIC_AUTH), "alias/one"),
REGION);
EventSourceV2 updated = service.updateEventSource(updateWithKey(source, ""), REGION);
assertEquals("", updated.getConfiguration().get("WebhookEventsConfiguration").get("KmsKeyIdentifier")
.textValue());
verify(secrets).updateSecret(source.getSecretArn(), null, "", REGION);
verify(kms, times(1)).describeKey(any(), any());
}
@Test
void updateWithAnEmptyKeyIdentifierOnASourceWithNoKeyLeavesTheSecretAlone() {
EventSourceV2 source = service.createEventSource(withKey(create("hook", bus, STATIC_AUTH), ""), REGION);
service.updateEventSource(updateWithKey(source, ""), REGION);
verify(secrets, never()).updateSecret(any(), any(), any(), any());
}
@Test
void anUpdateWithNoConfigurationLeavesTheKeyAlone() {
customerKey("alias/one");
EventSourceV2 source = service.createEventSource(withKey(create("hook", bus, STATIC_AUTH), "alias/one"),
REGION);
service.updateEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\",\"Description\":\"d\"}"),
REGION);
verify(secrets, never()).updateSecret(any(), any(), any(), any());
}
// ──────────────────────────── Delete ────────────────────────────
@Test
@@ -12,6 +12,7 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.eventbridgev2.model.EventBusV2;
import io.floci.aws.services.eventbridgev2.model.SubscriberV2;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -66,7 +67,8 @@ class EventBridgeV2ServiceTest {
Clock clock = Clock.fixed(NOW, ZoneOffset.UTC);
EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources(
AccountAwareStorageBackend.inMemory(ACCOUNT), mock(SecretsManagerService.class), regionResolver, clock,
"http://floci.test:4566", mock(TlsCertificateManager.class), mock(EventBridgeService.class));
"http://floci.test:4566", mock(TlsCertificateManager.class), mock(EventBridgeService.class),
mock(KmsService.class));
service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT),
AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, eventSources, clock, true);
}
@@ -9,6 +9,7 @@ import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.eventbridgev2.model.EventBusV2;
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
import io.floci.aws.services.eventbridgev2.model.SubscriberV2;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -47,7 +48,8 @@ class EventBridgeV2StoredTagsTest {
sources = AccountAwareStorageBackend.inMemory(ACCOUNT);
EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources(sources,
mock(SecretsManagerService.class, RETURNS_DEEP_STUBS), regionResolver, clock,
"http://floci.test:4566", mock(TlsCertificateManager.class), mock(EventBridgeService.class));
"http://floci.test:4566", mock(TlsCertificateManager.class), mock(EventBridgeService.class),
mock(KmsService.class));
buses = AccountAwareStorageBackend.inMemory(ACCOUNT);
subscribers = AccountAwareStorageBackend.inMemory(ACCOUNT);
service = new EventBridgeV2Service(buses, subscribers, regionResolver, mock(EventBridgeV2Delivery.class),
@@ -11,6 +11,7 @@ import io.floci.aws.services.eventbridgev2.EventBridgeV2Webhooks.Answer;
import io.floci.aws.services.eventbridgev2.EventBridgeV2Webhooks.Request;
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
import io.floci.aws.services.eventbridgev2.model.SubscriberV2;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.Secret;
import io.floci.aws.services.secretsmanager.model.SecretVersion;
@@ -89,7 +90,7 @@ class EventBridgeV2WebhooksTest {
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
sources = new EventBridgeV2EventSources(
AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, "http://floci.test:4566",
mock(TlsCertificateManager.class), mock(EventBridgeService.class));
mock(TlsCertificateManager.class), mock(EventBridgeService.class), mock(KmsService.class));
service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT),
AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, sources, clock, true);
webhooks = new EventBridgeV2Webhooks(service, sources, secrets, clock);
@@ -510,6 +510,6 @@ class WebhookEventsConfigurationsTest {
private static String updateRefusal(String configurationJson, String storedAuthType) {
return assertThrows(AwsException.class, () -> WebhookEventsConfigurations.validateForUpdate(
json(configurationJson), storedAuthType)).getMessage();
json(configurationJson), storedAuthType, "us-east-1", "000000000000")).getMessage();
}
}
@@ -10,6 +10,7 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.Secret;
import io.floci.aws.testing.ManualClock;
@@ -52,7 +53,7 @@ final class WebhookSourceFixture {
clock = new ManualClock(NOW);
EventBridgeV2EventSources sources = new EventBridgeV2EventSources(
AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, "http://floci.test:4566",
mock(TlsCertificateManager.class), mock(EventBridgeService.class));
mock(TlsCertificateManager.class), mock(EventBridgeService.class), mock(KmsService.class));
service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT),
AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, sources, clock, true);
webhooks = new EventBridgeV2Webhooks(service, sources, secrets, clock);