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

@@ -2,12 +2,15 @@ package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -94,25 +97,83 @@ public final class RequestConstraintCheck {
};
}
/**
* The orders of a violation list that the vendored file cannot say. A service measures them on AWS.
*
* @param patternBeforeLength a string reports its pattern before its length
* @param mapsInHashOrder a map is quoted in the order of a {@link HashMap} sized for its entries, not in
* request order
*/
public record ViolationOrder(boolean patternBeforeLength, boolean mapsInHashOrder) {
public static final ViolationOrder STANDARD = new ViolationOrder(false, false);
}
private final JsonNode model;
private final Map<String, Pattern> patterns;
private final Messages messages;
private final ViolationOrder order;
private final Set<String> wordable = ConcurrentHashMap.newKeySet();
private RequestConstraintCheck(JsonNode model, Messages messages) {
private RequestConstraintCheck(JsonNode model, Messages messages, ViolationOrder order) {
this.model = model;
this.messages = messages;
this.order = order;
this.patterns = VendoredShapes.patterns(model.path("shapes"));
}
/** The vendored resource {@code name}; {@code description} names it in a failure. */
public static RequestConstraintCheck load(String name, String description, Messages messages) {
return load(name, description, messages, ViolationOrder.STANDARD);
}
public static RequestConstraintCheck load(String name, String description, Messages messages,
ViolationOrder order) {
return VendoredResources.read(name, description,
input -> new RequestConstraintCheck(MAPPER.readTree(input), messages));
input -> new RequestConstraintCheck(MAPPER.readTree(input), messages, order));
}
public static RequestConstraintCheck of(JsonNode model, Messages messages) {
return new RequestConstraintCheck(model, messages);
return of(model, messages, ViolationOrder.STANDARD);
}
public static RequestConstraintCheck of(JsonNode model, Messages messages, ViolationOrder order) {
return new RequestConstraintCheck(model, messages, order);
}
/**
* A copy of {@code value} that keeps only the members {@code shapeName} declares. Structures and lists are
* walked and a map is copied as given.
*/
public JsonNode modeled(String shapeName, JsonNode value) {
JsonNode shape = model.path("shapes").path(shapeName);
switch (shape.path("type").asText()) {
case "structure" -> {
if (!value.isObject()) {
return value.deepCopy();
}
ObjectNode copy = MAPPER.createObjectNode();
for (Map.Entry<String, JsonNode> field : value.properties()) {
JsonNode member = shape.path("members").get(field.getKey());
if (member != null) {
copy.set(field.getKey(), modeled(member.asText(), field.getValue()));
}
}
return copy;
}
case "list" -> {
if (!value.isArray()) {
return value.deepCopy();
}
ArrayNode copy = MAPPER.createArrayNode();
for (JsonNode item : value) {
copy.add(modeled(shape.path("member").asText(), item));
}
return copy;
}
default -> {
return value.deepCopy();
}
}
}
/** Whether the vendored model declares an input for {@code operation}. */
@@ -230,7 +291,8 @@ public final class RequestConstraintCheck {
/**
* Every constraint {@code request} breaks for {@code operation}, worded as a Smithy validation
* error and in the model's member order, to be thrown with
* error. Members come in the order the vendored shape lists them in, which a generator may set. A string's
* pattern and length, and the text a map is quoted as, follow the {@link ViolationOrder}. To be thrown with
* {@link SmithyValidationErrors#exception(String, List)}. Paths join the member names with a dot,
* each with its first letter lower-cased. A shape marked {@code sensitive} leaves its value out
* of the wording. A value of the wrong JSON type is thrown at once through {@link Messages#type}.
@@ -339,7 +401,8 @@ public final class RequestConstraintCheck {
if (!value.isTextual()) {
throw messages.type(errorPath, type);
}
found.addAll(VendoredShapes.stringViolations(shape, patterns.get(name), value.textValue(), path, form));
found.addAll(VendoredShapes.stringViolations(shape, patterns.get(name), value.textValue(), path,
form, order.patternBeforeLength()));
}
case "integer", "long" -> collectInteger(shape, type, value, path, errorPath, form, found);
case "float", "double" -> {
@@ -366,16 +429,16 @@ public final class RequestConstraintCheck {
private void collectInteger(JsonNode shape, String type, JsonNode value, String path, String errorPath,
SmithyValidationErrors.Violations form, List<String> found) {
if (!value.isIntegralNumber()) {
boolean fits = "integer".equals(type) ? value.isIntegralNumber() && value.canConvertToInt()
: value.isIntegralNumber() && value.canConvertToLong();
if (!fits) {
throw messages.type(errorPath, type);
}
BigInteger number = value.bigIntegerValue();
if (shape.has("min") && number.compareTo(BigInteger.valueOf(shape.get("min").asLong())) < 0) {
long number = value.longValue();
if (shape.has("min") && number < shape.get("min").asLong()) {
found.add(form.valueTooSmall(path, value.asText(), shape.get("min").asLong()));
} else if (shape.has("max") && number.compareTo(BigInteger.valueOf(shape.get("max").asLong())) > 0) {
} else if (shape.has("max") && number > shape.get("max").asLong()) {
found.add(form.valueTooLarge(path, value.asText(), shape.get("max").asLong()));
} else if (!("integer".equals(type) ? value.canConvertToInt() : value.canConvertToLong())) {
throw messages.type(errorPath, type);
}
}
@@ -404,11 +467,7 @@ public final class RequestConstraintCheck {
if (!value.isObject()) {
throw messages.type(errorPath, "map");
}
List<String> entries = new ArrayList<>();
for (Map.Entry<String, JsonNode> entry : value.properties()) {
entries.add(entry.getKey() + "=" + elementText(entry.getValue()));
}
String mapText = "{" + String.join(", ", entries) + "}";
String mapText = mapText(value);
String size = sizeViolation(shape, value.size());
if (size != null) {
found.add(form.constraint(path, mapText, size));
@@ -486,6 +545,14 @@ public final class RequestConstraintCheck {
return null;
}
private String mapText(JsonNode map) {
Map<String, String> quoted = order.mapsInHashOrder() ? new HashMap<>(map.size()) : new LinkedHashMap<>();
for (Map.Entry<String, JsonNode> entry : map.properties()) {
quoted.put(entry.getKey(), elementText(entry.getValue()));
}
return quoted.toString();
}
private static String elementsText(JsonNode list) {
List<String> texts = new ArrayList<>();
list.forEach(item -> texts.add(elementText(item)));
@@ -43,20 +43,46 @@ final class VendoredShapes {
*/
static List<String> stringViolations(JsonNode shape, Pattern pattern, String text, String path,
SmithyValidationErrors.Violations messages) {
return stringViolations(shape, pattern, text, path, messages, false);
}
/** {@link #stringViolations} that reports the pattern before the length when {@code patternBeforeLength}. */
static List<String> stringViolations(JsonNode shape, Pattern pattern, String text, String path,
SmithyValidationErrors.Violations messages, boolean patternBeforeLength) {
List<String> violations = new ArrayList<>();
if (patternBeforeLength) {
addPattern(violations, shape, pattern, text, path, messages);
addLength(violations, shape, text, path, messages);
} else {
addLength(violations, shape, text, path, messages);
addPattern(violations, shape, pattern, text, path, messages);
}
addEnum(violations, shape, text, path, messages);
return violations;
}
private static void addLength(List<String> violations, JsonNode shape, String text, String path,
SmithyValidationErrors.Violations messages) {
String length = messages.lengthOutOfRange(path, text,
shape.path("min").asInt(0), shape.path("max").asInt(Integer.MAX_VALUE));
if (length != null) {
violations.add(length);
}
}
private static void addPattern(List<String> violations, JsonNode shape, Pattern pattern, String text,
String path, SmithyValidationErrors.Violations messages) {
if (pattern != null && !pattern.matcher(text).matches()) {
violations.add(messages.pattern(path, text, VendoredPatterns.quoted(shape)));
}
}
private static void addEnum(List<String> violations, JsonNode shape, String text, String path,
SmithyValidationErrors.Violations messages) {
List<String> allowed = enumValues(shape);
if (!allowed.isEmpty() && !allowed.contains(text)) {
violations.add(messages.notInEnum(text, path, allowed));
}
return violations;
}
/** The values a shape's enum admits, in the model's order, or none for a shape without one. */
@@ -0,0 +1,361 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.Digests;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.eventbridgev2.model.EventBusV2;
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.Secret;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.URI;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
/**
* The webhook event sources of EventBridge V2: their storage, the secret each one keeps its credential in and the
* URL it is reached at. The event bus a source belongs to is the bus service's, so each call that needs one is
* given the lookup.
*/
@ApplicationScoped
public class EventBridgeV2EventSources implements Resettable {
private static final String OWNING_SERVICE = "events-webhook";
private static final Logger LOG = Logger.getLogger(EventBridgeV2EventSources.class);
private static final int GENERATED_SECRET_BYTES = 32;
private static final String TOKEN_NAMESPACE = "event-sourcev2";
private final AccountAwareStorageBackend<EventSourceV2> sources;
private final SecretsManagerService secrets;
private final RegionResolver regionResolver;
private final Clock clock;
private final URI baseUrl;
private final SecureRandom random = new SecureRandom();
@Inject
public EventBridgeV2EventSources(StorageFactory storageFactory, SecretsManagerService secrets,
RegionResolver regionResolver, EmulatorConfig config) {
this(storageFactory.create("eventbridgev2", "eventbridgev2-event-sources.json",
new TypeReference<Map<String, EventSourceV2>>() {}),
secrets, regionResolver, Clock.systemUTC(), config.effectiveBaseUrl());
}
EventBridgeV2EventSources(AccountAwareStorageBackend<EventSourceV2> sources, SecretsManagerService secrets,
RegionResolver regionResolver, Clock clock, String baseUrl) {
this.sources = sources;
this.secrets = secrets;
this.regionResolver = regionResolver;
this.clock = clock;
this.baseUrl = URI.create(baseUrl);
}
/**
* Creates a webhook event source on a bus of the caller's, {@code ACTIVE} at once, with the secret that holds
* its credential. A retry with the {@code ClientToken} of an earlier create returns that source when it repeats
* the request, and fails when it changes it.
*/
EventSourceV2 create(JsonNode request, String region, Function<String, Optional<EventBusV2>> findBusByName) {
EventBridgeV2RequestShapes.check("CreateEventSource", request);
String name = request.get("Name").textValue();
String eventBusArn = request.get("EventBusArn").textValue();
JsonNode configuration = request.get("Configuration");
String roleArn = configuration.path(WebhookEventsConfigurations.WEBHOOK).path("RoleArn").asText(null);
requireEndpointRegion(eventBusArn, region, "EventBusArn");
requireOwnAccount(eventBusArn);
if (roleArn != null) {
requireOwnAccount(roleArn);
}
String clientToken = request.path("ClientToken").textValue();
if (clientToken == null) {
throw EventBridgeV2Service.invalidInput("ClientToken is required");
}
JsonNode webhook = WebhookEventsConfigurations.validateForCreate(configuration);
// The request carries credentials, so only its hash is kept.
String requestHash = Digests.sha256Hex(EventBridgeV2Service.withoutClientToken(request));
Optional<EventSourceV2> retried = EventBridgeV2Service.retried(() -> inRegion(region),
clientToken, requestHash, EventSourceV2::getClientToken, EventSourceV2::getCreateRequestHash,
() -> new AwsException("IdempotentParameterMismatchException",
"ClientToken was used by a previous request with different parameters", 409));
if (retried.isPresent()) {
return retried.get();
}
requireBus(eventBusArn, findBusByName);
String key = EventBridgeV2Service.storageKey(region, name);
if (sources.get(key).isPresent()) {
throw new AwsException("ResourceAlreadyExistsException", "Resource already exists", 409);
}
String hostId = WebhookTokens.newHostId(random);
Instant now = clock.instant();
EventSourceV2 source = new EventSourceV2();
source.setName(name);
source.setArn(regionResolver.buildArn("events", region,
"event-sourcev2/webhook/" + name + "/" + EventBridgeV2Service.newId(random)));
source.setEventBusArn(eventBusArn);
source.setDescription(request.path("Description").textValue());
source.setConfiguration(WebhookEventsConfigurations.echo(webhook));
source.setState(EventBridgeV2Service.ACTIVE);
source.setCreationTime(now);
source.setLastModifiedTime(now);
source.setTags(tags(request.get("Tags")));
source.setClientToken(clientToken);
source.setCreateRequestHash(requestHash);
source.setWebhookHostId(hostId);
source.setWebhookToken(WebhookTokens.newToken(hostId, random));
source.setSecretArn(createSecret(webhook, region));
try {
sources.put(key, source);
} catch (RuntimeException e) {
deleteOrphanedSecret(source.getSecretArn(), region);
throw e;
}
return source;
}
/**
* Replaces the description the request gives and the whole webhook configuration. The credentials, the URL and
* the secret stay as they are. A refused update changes nothing.
*/
EventSourceV2 update(JsonNode request, String region) {
EventBridgeV2RequestShapes.check("UpdateEventSource", request);
String arn = request.get("EventSourceArn").textValue();
checkArn(arn, region);
JsonNode configuration = request.hasNonNull("Configuration") ? request.get("Configuration") : null;
String roleArn = configuration == null ? null
: configuration.path(WebhookEventsConfigurations.WEBHOOK).path("RoleArn").asText(null);
if (roleArn != null) {
requireOwnAccount(roleArn);
}
EventSourceV2 source = require(arn, region);
JsonNode webhook = configuration == null ? null : WebhookEventsConfigurations.validateForUpdate(
configuration, WebhookEventsConfigurations.authType(
source.getConfiguration().get(WebhookEventsConfigurations.WEBHOOK)));
EventSourceV2 changed = new EventSourceV2();
changed.setName(source.getName());
changed.setArn(source.getArn());
changed.setEventBusArn(source.getEventBusArn());
changed.setDescription(request.hasNonNull("Description") ? request.get("Description").textValue()
: source.getDescription());
changed.setConfiguration(webhook == null ? source.getConfiguration()
: WebhookEventsConfigurations.echo(webhook));
changed.setState(source.getState());
changed.setCreationTime(source.getCreationTime());
changed.setLastModifiedTime(clock.instant());
changed.setTags(source.getTags());
changed.setClientToken(source.getClientToken());
changed.setCreateRequestHash(source.getCreateRequestHash());
changed.setWebhookHostId(source.getWebhookHostId());
changed.setWebhookToken(source.getWebhookToken());
changed.setSecretArn(source.getSecretArn());
sources.put(EventBridgeV2Service.storageKey(region, source.getName()), changed);
return changed;
}
EventSourceV2 describe(JsonNode request, String region) {
return find("DescribeEventSource", request, region);
}
private EventSourceV2 find(String operation, JsonNode request, String region) {
EventBridgeV2RequestShapes.check(operation, request);
String arn = request.get("EventSourceArn").textValue();
checkArn(arn, region);
return require(arn, region);
}
/** Deletes the source and schedules its secret for deletion, unless the secret is already scheduled. */
void delete(JsonNode request, String region) {
EventSourceV2 source = find("DeleteEventSource", request, region);
try {
if (secrets.describeSecret(source.getSecretArn(), region).getDeletedDate() == null) {
secrets.deleteSecret(source.getSecretArn(), null, false, region);
}
} catch (AwsException e) {
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
throw e;
}
LOG.warnv("The secret {0} of event source {1} is already gone", source.getSecretArn(), source.getArn());
}
sources.delete(EventBridgeV2Service.storageKey(region, source.getName()));
}
/**
* One page of the Region's sources, or those of one bus, whose name starts with {@code NamePrefix}, in order of
* their ids. A token that is not one of ours is refused before the bus is looked up.
*/
PaginatedResult<EventSourceV2> list(JsonNode request, String region,
Function<String, Optional<EventBusV2>> findBusByName) {
EventBridgeV2RequestShapes.check("ListEventSources", request);
String eventBusArn = request.path("EventBusArn").textValue();
String namePrefix = request.path("NamePrefix").textValue();
String nextToken = request.path("NextToken").textValue();
if (eventBusArn != null) {
requireEndpointRegion(eventBusArn, region, "EventBusArn");
}
String namespace = tokenNamespace(region, eventBusArn, namePrefix);
if (nextToken != null && !Pagination.tokenStartsWith(nextToken, namespace + ":")) {
throw invalidNextToken();
}
if (eventBusArn != null) {
if (AwsArnUtils.isForeignAccount(AwsArnUtils.parse(eventBusArn), regionResolver.getAccountId())) {
throw busMissing();
}
requireBus(eventBusArn, findBusByName);
}
List<EventSourceV2> listed = inRegion(region).stream()
.filter(source -> eventBusArn == null || eventBusArn.equals(source.getEventBusArn()))
.filter(source -> namePrefix == null || source.getName().startsWith(namePrefix))
.toList();
int maxResults = request.hasNonNull("MaxResults") ? request.get("MaxResults").intValue()
: EventBridgeV2Service.MAX_LIST_RESULTS;
return Pagination.paginate(listed, EventBridgeV2EventSources::id, maxResults, nextToken, namespace,
token -> invalidNextToken());
}
private static String tokenNamespace(String region, String eventBusArn, String namePrefix) {
String filters = region + "\n" + (eventBusArn == null ? "-" : "+" + eventBusArn) + "\n"
+ (namePrefix == null ? "-" : "+" + namePrefix);
return TOKEN_NAMESPACE + "-" + Digests.sha256Hex(filters);
}
boolean hasSourcesOn(String eventBusArn, String region) {
return inRegion(region).stream().anyMatch(source -> eventBusArn.equals(source.getEventBusArn()));
}
/** The URL a source receives its events at, in the scheme of Floci's own base URL. */
String webhookUrl(EventSourceV2 source) {
return baseUrl.getScheme() + "://" + source.getWebhookHostId() + ".c01.events-webhook."
+ AwsArnUtils.parse(source.getArn()).region() + "." + baseUrl.getAuthority() + "/"
+ source.getWebhookToken() + "/";
}
@Override
public void clear() {
sources.clear();
}
private String createSecret(JsonNode webhook, String region) {
JsonNode auth = webhook.get("AuthConfiguration");
String authType = WebhookEventsConfigurations.authType(webhook);
String secretString;
if (WebhookEventsConfigurations.BASIC.equals(authType)) {
JsonNode basic = auth.get(WebhookEventsConfigurations.BASIC);
ObjectNode credential = JsonNodeFactory.instance.objectNode();
credential.put("username", basic.hasNonNull("Username") ? basic.get("Username").textValue() : generated());
credential.put("password", basic.hasNonNull("Password") ? basic.get("Password").textValue() : generated());
secretString = credential.toString();
} else if (WebhookEventsConfigurations.HMAC.equals(authType)) {
String given = WebhookEventsConfigurations.hmacSecretValue(auth.get(WebhookEventsConfigurations.HMAC));
secretString = given != null ? given : generated();
} else {
JsonNode staticToken = auth.get(WebhookEventsConfigurations.STATIC_TOKEN);
secretString = staticToken.hasNonNull("SecretValue") ? staticToken.get("SecretValue").textValue()
: generated();
}
return secrets.createSecret("events-webhook!" + UUID.randomUUID(), secretString, null, null, null,
List.of(new Secret.Tag("aws:secretsmanager:owningService", OWNING_SERVICE)), OWNING_SERVICE,
region).getArn();
}
private void deleteOrphanedSecret(String secretArn, String region) {
try {
secrets.deleteSecret(secretArn, null, true, region);
} catch (RuntimeException e) {
LOG.warnv(e, "The secret {0} of an event source that was not stored could not be deleted", secretArn);
}
}
private String generated() {
byte[] bytes = new byte[GENERATED_SECRET_BYTES];
random.nextBytes(bytes);
return Base64.getEncoder().encodeToString(bytes);
}
private static void requireBus(String eventBusArn, Function<String, Optional<EventBusV2>> findBusByName) {
String busName = EventBridgeV2Service.busName(eventBusArn);
EventBusV2 bus = findBusByName.apply(busName).orElseThrow(EventBridgeV2EventSources::busMissing);
if (!eventBusArn.equals(bus.getArn())) {
throw new AwsException("ResourceNotFoundException", "Event bus not found: " + busName, 404);
}
}
private static AwsException busMissing() {
return new AwsException("ResourceNotFoundException", "Resource does not exist", 404);
}
private static AwsException invalidNextToken() {
return EventBridgeV2Service.invalidInput("Invalid nextToken");
}
private void checkArn(String eventSourceArn, String region) {
requireEndpointRegion(eventSourceArn, region, "EventSourceArn");
requireOwnAccount(eventSourceArn);
}
private EventSourceV2 require(String eventSourceArn, String region) {
String[] resource = AwsArnUtils.parse(eventSourceArn).resource().split("/");
Optional<EventSourceV2> found = resource.length == 4 && "event-sourcev2".equals(resource[0])
? sources.get(EventBridgeV2Service.storageKey(region, resource[2]))
.filter(source -> eventSourceArn.equals(source.getArn()))
: Optional.empty();
return found.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"EventSource not found: " + eventSourceArn, 404));
}
private void requireEndpointRegion(String arn, String region, String member) {
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
if (!parsed.region().equals(region) || !parsed.partition().equals(regionResolver.partitionForRegion(region))) {
throw EventBridgeV2Service.invalidInput(
"The region or partition in " + member + " does not match this endpoint");
}
}
private void requireOwnAccount(String arn) {
if (AwsArnUtils.isForeignAccount(AwsArnUtils.parse(arn), regionResolver.getAccountId())) {
throw new AwsException("AccessDeniedException", "Access denied.", 403);
}
}
private List<EventSourceV2> inRegion(String region) {
String prefix = region + "::";
return sources.scan(key -> key.startsWith(prefix));
}
private static Map<String, String> tags(JsonNode node) {
Map<String, String> tags = new LinkedHashMap<>();
if (node != null && node.isObject()) {
for (Map.Entry<String, JsonNode> tag : node.properties()) {
tags.put(tag.getKey(), tag.getValue().textValue());
}
}
return tags;
}
static String id(EventSourceV2 source) {
return source.getArn().substring(source.getArn().length() - EventBridgeV2Service.ID_LENGTH);
}
}
@@ -8,6 +8,7 @@ import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.services.eventbridgev2.model.EventBusV2;
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
import io.floci.aws.services.eventbridgev2.model.SubscriberV2;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -52,6 +53,11 @@ public class EventBridgeV2Handler {
case "ListSubscribers" -> handleListSubscribers(request, region);
case "UpdateSubscriber" -> handleUpdateSubscriber(request, region);
case "DeleteSubscriber" -> handleDeleteSubscriber(request, region);
case "CreateEventSource" -> handleCreateEventSource(request, region);
case "DescribeEventSource" -> handleDescribeEventSource(request, region);
case "ListEventSources" -> handleListEventSources(request, region);
case "UpdateEventSource" -> handleUpdateEventSource(request, region);
case "DeleteEventSource" -> handleDeleteEventSource(request, region);
case "PutEvents" -> handlePutEvents(request, region);
default -> throw new AwsException("UnsupportedOperation",
"Operation " + operation + " is not supported.", 400);
@@ -195,6 +201,82 @@ public class EventBridgeV2Handler {
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleCreateEventSource(JsonNode request, String region) {
EventSourceV2 source = service.createEventSource(request, region);
ObjectNode response = eventSourceIdentity(source);
response.set("EventSourceDetails", eventSourceDetails(source));
response.put("CreationTime", epochSeconds(source.getCreationTime()));
return Response.ok(response).build();
}
private Response handleDescribeEventSource(JsonNode request, String region) {
EventSourceV2 source = service.describeEventSource(request, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("EventSourceArn", source.getArn());
response.put("Name", source.getName());
response.put("EventBusArn", source.getEventBusArn());
response.set("Configuration", source.getConfiguration());
if (source.getDescription() != null) {
response.put("Description", source.getDescription());
}
response.put("State", source.getState());
response.set("EventSourceDetails", eventSourceDetails(source));
response.put("CreationTime", epochSeconds(source.getCreationTime()));
response.put("LastModifiedTime", epochSeconds(source.getLastModifiedTime()));
return Response.ok(response).build();
}
private Response handleUpdateEventSource(JsonNode request, String region) {
EventSourceV2 source = service.updateEventSource(request, region);
ObjectNode response = eventSourceIdentity(source);
response.put("LastModifiedTime", epochSeconds(source.getLastModifiedTime()));
return Response.ok(response).build();
}
private Response handleDeleteEventSource(JsonNode request, String region) {
service.deleteEventSource(request, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleListEventSources(JsonNode request, String region) {
PaginatedResult<EventSourceV2> page = service.listEventSources(request, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode sources = response.putArray("EventSources");
for (EventSourceV2 source : page.items()) {
ObjectNode summary = sources.addObject();
summary.put("EventSourceArn", source.getArn());
summary.put("Name", source.getName());
summary.put("EventBusArn", source.getEventBusArn());
summary.put("Type", "WEBHOOK_EVENTS");
summary.put("State", source.getState());
summary.put("CreationTime", epochSeconds(source.getCreationTime()));
summary.put("LastModifiedTime", epochSeconds(source.getLastModifiedTime()));
summary.put("EventSourceAccountId", AwsArnUtils.parse(source.getArn()).accountId());
}
if (page.nextToken() != null) {
response.put("NextToken", page.nextToken());
}
return Response.ok(response).build();
}
/** The members {@code CreateEventSource} and {@code UpdateEventSource} both answer with. */
private ObjectNode eventSourceIdentity(EventSourceV2 source) {
ObjectNode response = objectMapper.createObjectNode();
response.put("EventSourceArn", source.getArn());
response.put("Name", source.getName());
response.put("EventBusArn", source.getEventBusArn());
response.put("State", source.getState());
return response;
}
private ObjectNode eventSourceDetails(EventSourceV2 source) {
ObjectNode details = objectMapper.createObjectNode();
ObjectNode webhook = details.putObject("WebhookDetails");
webhook.put("WebhookUrl", service.webhookUrl(source));
webhook.put("SecretArn", source.getSecretArn());
return details;
}
private Response handlePutEvents(JsonNode request, String region) {
List<EventBridgeV2Service.PutEventsResult> results = service.putEvents(request, region);
ObjectNode response = objectMapper.createObjectNode();
@@ -0,0 +1,85 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestConstraintCheck;
import io.floci.aws.core.common.SmithyValidationErrors;
import java.util.List;
/**
* Checks EventBridge V2 event source requests against the constraints generated by
* {@code tools/aws/regen_eventbridgev2_shapes.py}. The first ten violations are answered together as
* {@code InvalidInputException}, in the wording AWS uses. A member of the wrong type is answered as
* {@code SerializationException} with no message.
*/
final class EventBridgeV2RequestShapes {
private static final int MAX_VIOLATIONS = 10;
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
"aws/eventbridgev2-request-shapes.json", "EventBridge V2 request shapes", new Messages(),
new RequestConstraintCheck.ViolationOrder(true, true));
private EventBridgeV2RequestShapes() {
}
/** {@code value} without the members that {@code shapeName} does not declare. */
static JsonNode modeled(String shapeName, JsonNode value) {
return CHECK.modeled(shapeName, value);
}
static void check(String operation, JsonNode request) {
List<String> violations = CHECK.violations(operation, withoutWhsecPrefix(request));
if (!violations.isEmpty()) {
throw SmithyValidationErrors.exception("InvalidInputException",
violations.subList(0, Math.min(violations.size(), MAX_VIOLATIONS)));
}
}
/** Only {@code violations} is used, and it reaches nothing but the type message. */
private static final class Messages implements RequestConstraintCheck.Messages {
private final RequestConstraintCheck.Messages standard =
RequestConstraintCheck.standardMessages("InvalidInputException");
@Override
public AwsException type(String path, String type) {
return new AwsException("SerializationException", null, 400);
}
@Override
public AwsException bounds(String path, String type, Long min, Long max, Number size) {
return standard.bounds(path, type, min, max, size);
}
@Override
public AwsException pattern(String path, String pattern) {
return standard.pattern(path, pattern);
}
@Override
public AwsException enumValue(String path, List<String> values) {
return standard.enumValue(path, values);
}
@Override
public AwsException required(String path) {
return standard.required(path);
}
}
/** AWS judges the length of a Base64 HMAC secret without its {@code whsec_} prefix. */
private static JsonNode withoutWhsecPrefix(JsonNode request) {
JsonNode hmac = request.path("Configuration").path(WebhookEventsConfigurations.WEBHOOK)
.path("AuthConfiguration").path(WebhookEventsConfigurations.HMAC);
String secret = WebhookEventsConfigurations.hmacSecretValue(hmac);
if (secret == null || secret.equals(hmac.path("SecretValue").textValue())) {
return request;
}
ObjectNode copy = request.deepCopy();
((ObjectNode) copy.path("Configuration").path(WebhookEventsConfigurations.WEBHOOK)
.path("AuthConfiguration").path(WebhookEventsConfigurations.HMAC)).put("SecretValue", secret);
return copy;
}
}
@@ -18,6 +18,7 @@ import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.eventbridgev2.model.EventBusV2;
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
import io.floci.aws.services.eventbridgev2.model.SubscriberV2;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -41,6 +42,7 @@ import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Pattern;
/**
@@ -70,10 +72,10 @@ public class EventBridgeV2Service implements Resettable {
"KinesisParameters", "StepFunctionsParameters", "HttpParameters", "UniversalTargetParameters",
"EventBusV2Parameters");
private static final String ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
private static final int ID_LENGTH = 25;
static final int ID_LENGTH = 25;
private static final int MAX_TAGS = 200;
private static final int MAX_ENTRIES = 100;
private static final int MAX_LIST_RESULTS = 100;
static final int MAX_LIST_RESULTS = 100;
private static final List<String> UPDATABLE_SETTINGS = List.of("Description", "State", "FilterConfiguration",
"BatchConfiguration", "Transformer", "RetryPolicy", "OnFailureConfiguration", "LogConfiguration");
private static final String PUT_EVENTS_CONTENT_TYPE = "application/eventbridge+json";
@@ -82,6 +84,7 @@ public class EventBridgeV2Service implements Resettable {
private final AccountAwareStorageBackend<SubscriberV2> subscribers;
private final RegionResolver regionResolver;
private final EventBridgeV2Delivery delivery;
private final EventBridgeV2EventSources eventSources;
private final Clock clock;
private final boolean enabled;
private final SecureRandom random = new SecureRandom();
@@ -89,21 +92,24 @@ public class EventBridgeV2Service implements Resettable {
@Inject
public EventBridgeV2Service(StorageFactory storageFactory, RegionResolver regionResolver,
EventBridgeV2Delivery delivery, EmulatorConfig config) {
EventBridgeV2Delivery delivery, EventBridgeV2EventSources eventSources,
EmulatorConfig config) {
this(storageFactory.create("eventbridgev2", "eventbridgev2-buses.json",
new TypeReference<Map<String, EventBusV2>>() {}),
storageFactory.create("eventbridgev2", "eventbridgev2-subscribers.json",
new TypeReference<Map<String, SubscriberV2>>() {}),
regionResolver, delivery, Clock.systemUTC(), config.services().eventbridgev2().enabled());
regionResolver, delivery, eventSources, Clock.systemUTC(), config.services().eventbridgev2().enabled());
}
EventBridgeV2Service(AccountAwareStorageBackend<EventBusV2> buses,
AccountAwareStorageBackend<SubscriberV2> subscribers, RegionResolver regionResolver,
EventBridgeV2Delivery delivery, Clock clock, boolean enabled) {
EventBridgeV2Delivery delivery, EventBridgeV2EventSources eventSources, Clock clock,
boolean enabled) {
this.buses = buses;
this.subscribers = subscribers;
this.regionResolver = regionResolver;
this.delivery = delivery;
this.eventSources = eventSources;
this.clock = clock;
this.enabled = enabled;
}
@@ -128,16 +134,11 @@ public class EventBridgeV2Service implements Resettable {
String clientToken = optionalClientToken(request);
String createRequest = withoutClientToken(request);
if (clientToken != null) {
Optional<EventBusV2> retried = buses.scan(key -> key.startsWith(region + "::")).stream()
.filter(bus -> clientToken.equals(bus.getClientToken()))
.findFirst();
if (retried.isPresent()) {
if (!createRequest.equals(retried.get().getCreateRequest())) {
throw idempotentMismatch(clientToken);
}
return retried.get();
}
Optional<EventBusV2> retried = retried(() -> buses.scan(key -> key.startsWith(region + "::")), clientToken,
createRequest, EventBusV2::getClientToken, EventBusV2::getCreateRequest,
() -> idempotentMismatch(clientToken));
if (retried.isPresent()) {
return retried.get();
}
String key = storageKey(region, name);
if (buses.get(key).isPresent()) {
@@ -206,10 +207,16 @@ public class EventBridgeV2Service implements Resettable {
deleteEventBus(requireText(request, "EventBusArn"), region);
}
/** Deletes a bus, which must have no subscribers left. */
/** Deletes a bus, which must have no subscribers or event sources left. */
public synchronized void deleteEventBus(String eventBusArn, String region) {
EventBusV2 bus = requireEventBus(eventBusArn, region);
if (!subscribersOf(bus, region).isEmpty()) {
boolean hasSubscribers = !subscribersOf(bus, region).isEmpty();
if (eventSources.hasSourcesOn(bus.getArn(), region)) {
throw new AwsException("ResourceInUseException", "The event bus cannot be deleted because it has "
+ (hasSubscribers ? "subscribers and event sources" : "one or more event sources")
+ " that are not revoked. Delete or revoke them and retry.", 409);
}
if (hasSubscribers) {
throw new AwsException("ResourceInUseException",
"Event bus " + bus.getName() + " still has subscribers; delete them first.", 409);
}
@@ -251,16 +258,11 @@ public class EventBridgeV2Service implements Resettable {
}
String clientToken = optionalClientToken(request);
String createRequest = withoutClientToken(request);
if (clientToken != null) {
Optional<SubscriberV2> retried = subscribers.scan(key -> key.startsWith(region + "::")).stream()
.filter(subscriber -> clientToken.equals(subscriber.getClientToken()))
.findFirst();
if (retried.isPresent()) {
if (!createRequest.equals(retried.get().getCreateRequest())) {
throw idempotentMismatch(clientToken);
}
return retried.get();
}
Optional<SubscriberV2> retried = retried(() -> subscribers.scan(key -> key.startsWith(region + "::")),
clientToken, createRequest, SubscriberV2::getClientToken, SubscriberV2::getCreateRequest,
() -> idempotentMismatch(clientToken));
if (retried.isPresent()) {
return retried.get();
}
EventBusV2 bus = requireEventBus(eventBusArn, region);
String key = subscriberKey(region, bus.getName(), name);
@@ -410,6 +412,36 @@ public class EventBridgeV2Service implements Resettable {
.filter(bus -> bus.getArn().equals(eventBusArn));
}
// ──────────────────────────── Event sources ────────────────────────────
public synchronized EventSourceV2 createEventSource(JsonNode request, String region) {
return eventSources.create(request, region, name -> buses.get(storageKey(region, name)));
}
public synchronized EventSourceV2 describeEventSource(JsonNode request, String region) {
return eventSources.describe(request, region);
}
public synchronized EventSourceV2 updateEventSource(JsonNode request, String region) {
return eventSources.update(request, region);
}
public synchronized void deleteEventSource(JsonNode request, String region) {
eventSources.delete(request, region);
}
/**
* One page of the Region's event sources, or those of the bus {@code EventBusArn} names, whose name starts
* with {@code NamePrefix}, in order of the ids in their ARNs.
*/
public synchronized PaginatedResult<EventSourceV2> listEventSources(JsonNode request, String region) {
return eventSources.list(request, region, name -> buses.get(storageKey(region, name)));
}
public String webhookUrl(EventSourceV2 source) {
return eventSources.webhookUrl(source);
}
// ──────────────────────────── Events ────────────────────────────
/** A bus's deliveries waiting to be sent, in sequence order, and the lock held while sending them. */
@@ -754,6 +786,10 @@ public class EventBridgeV2Service implements Resettable {
}
private String newId() {
return newId(random);
}
static String newId(SecureRandom random) {
StringBuilder id = new StringBuilder(ID_LENGTH);
for (int i = 0; i < ID_LENGTH; i++) {
id.append(ID_ALPHABET.charAt(random.nextInt(ID_ALPHABET.length())));
@@ -761,7 +797,25 @@ public class EventBridgeV2Service implements Resettable {
return id.toString();
}
private static String storageKey(String region, String name) {
/**
* The resource an earlier create made with the same {@code ClientToken}, empty when there is none. A request
* that differs from the earlier one fails with {@code mismatch}.
*/
static <T> Optional<T> retried(Supplier<List<T>> candidates, String clientToken, String createRequest,
Function<T, String> tokenOf, Function<T, String> requestOf,
Supplier<AwsException> mismatch) {
if (clientToken == null) {
return Optional.empty();
}
Optional<T> found = candidates.get().stream().filter(candidate -> clientToken.equals(tokenOf.apply(candidate)))
.findFirst();
if (found.isPresent() && !createRequest.equals(requestOf.apply(found.get()))) {
throw mismatch.get();
}
return found;
}
static String storageKey(String region, String name) {
return region + "::" + name;
}
@@ -888,7 +942,7 @@ public class EventBridgeV2Service implements Resettable {
* The request without its {@code ClientToken}, every object's fields in name order, so a retry that sends the same
* values with its fields or tags in another order compares equal to the request it repeats.
*/
private static String withoutClientToken(JsonNode request) {
static String withoutClientToken(JsonNode request) {
JsonNode copy = request.deepCopy();
if (copy instanceof ObjectNode object) {
object.remove("ClientToken");
@@ -935,7 +989,7 @@ public class EventBridgeV2Service implements Resettable {
"ClientToken " + clientToken + " was used with a different request.", 409);
}
private static AwsException invalidInput(String message) {
static AwsException invalidInput(String message) {
return new AwsException("InvalidInputException", message, 400);
}
}
@@ -0,0 +1,312 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import static io.floci.aws.services.eventbridgev2.EventBridgeV2Service.invalidInput;
/**
* The request rules of a webhook event source that AWS checks after the constraints of its model, reported one at
* a time. It also builds the form of the configuration that {@code DescribeEventSource} returns.
*/
final class WebhookEventsConfigurations {
static final String WEBHOOK = "WebhookEventsConfiguration";
static final String STATIC_TOKEN = "StaticTokenAuthConfiguration";
static final String BASIC = "BasicHttpAuthConfiguration";
static final String HMAC = "HmacAuthConfiguration";
private static final String AUTH = "WebhookEventsConfiguration.AuthConfiguration";
private static final String METADATA = "WebhookEventsConfiguration.MetadataHttpHeaders";
private static final String HMAC_INVALID = AUTH + ".HmacAuthConfiguration is invalid: ";
private static final String WHSEC = "whsec_";
private static final int MIN_HMAC_SECRET_BYTES = 16;
private static final String ONLY_WEBHOOK = "Only WebhookEventsConfiguration event sources are supported.";
private static final List<String> SECRET_MEMBERS = List.of("SecretValue", "Username", "Password");
private static final List<String> AUTH_MEMBERS = List.of(STATIC_TOKEN, BASIC, HMAC);
private static final Set<String> REFUSED_COMMON_HEADERS = lowerCased("Host", "X-Forwarded-For",
"X-Forwarded-Host", "X-Forwarded-Proto", "Connection", "Transfer-Encoding", "Cookie", "Via", "Upgrade",
"TE", "Keep-Alive", "Forwarded", "Proxy-Authorization", "Trailer", "Proxy-Connection", "Max-Forwards");
private static final Set<String> REFUSED_AUTH_HEADERS = withExtras(REFUSED_COMMON_HEADERS,
"Content-Length", "Set-Cookie");
private static final Set<String> REFUSED_METADATA_HEADERS = withExtras(REFUSED_COMMON_HEADERS, "Authorization");
private WebhookEventsConfigurations() {
}
/**
* Checks a create request's {@code Configuration} and returns its webhook configuration. A configuration of
* another variant is refused, as Floci serves webhook event sources only.
*/
static JsonNode validateForCreate(JsonNode configuration) {
Map.Entry<String, JsonNode> variant = onlyVariant(configuration);
if (!WEBHOOK.equals(variant.getKey())) {
throw invalidInput(ONLY_WEBHOOK);
}
validateWebhook(variant.getValue());
return variant.getValue();
}
/**
* Checks an update request's {@code Configuration} against the authentication type the source was created
* with, and returns its webhook configuration.
*/
static JsonNode validateForUpdate(JsonNode configuration, String storedAuthType) {
Map.Entry<String, JsonNode> variant = onlyVariant(configuration);
if (!WEBHOOK.equals(variant.getKey())) {
throw invalidInput("EventSource type is immutable: the configuration variant must remain "
+ "WEBHOOK_EVENTS");
}
JsonNode webhook = variant.getValue();
JsonNode auth = webhook.path("AuthConfiguration");
for (String member : AUTH_MEMBERS) {
for (String secret : SECRET_MEMBERS) {
if (auth.path(member).hasNonNull(secret)) {
throw invalidInput("UpdateEventSource does not accept SecretValue, Username or Password; "
+ "webhook credentials change only through RotateWebhookCredentials");
}
}
}
List<String> present = presentAuthMembers(auth);
if (present.size() == 1 && !present.getFirst().equals(storedAuthType)) {
throw invalidInput("The webhook authentication type can't be changed after the EventSource is created");
}
validateWebhook(webhook);
return webhook;
}
private static List<Map.Entry<String, JsonNode>> variants(JsonNode configuration) {
List<Map.Entry<String, JsonNode>> members = new ArrayList<>();
for (Map.Entry<String, JsonNode> member : configuration.properties()) {
if (!member.getValue().isNull()) {
members.add(member);
}
}
return members;
}
private static Map.Entry<String, JsonNode> onlyVariant(JsonNode configuration) {
List<Map.Entry<String, JsonNode>> members = variants(configuration);
if (members.size() != 1) {
throw invalidInput("Exactly one Configuration sub-field must be provided");
}
return members.getFirst();
}
private static List<String> presentAuthMembers(JsonNode auth) {
List<String> present = new ArrayList<>();
for (String member : AUTH_MEMBERS) {
if (auth.hasNonNull(member)) {
present.add(member);
}
}
return present;
}
private static void validateWebhook(JsonNode webhook) {
JsonNode auth = webhook.path("AuthConfiguration");
List<String> present = presentAuthMembers(auth);
if (present.size() != 1) {
throw invalidInput(AUTH + " must set exactly one of StaticTokenAuthConfiguration, "
+ "BasicHttpAuthConfiguration or HmacAuthConfiguration");
}
String authHeaderMember = switch (present.getFirst()) {
case BASIC -> {
validateBasic(auth.get(BASIC));
yield null;
}
case STATIC_TOKEN -> {
refuseAuthHeader(STATIC_TOKEN, "TokenHttpHeader",
auth.get(STATIC_TOKEN).path("TokenHttpHeader").asText());
yield "TokenHttpHeader";
}
default -> {
validateHmac(auth.get(HMAC));
yield "SignatureHttpHeader";
}
};
if (authHeaderMember == null) {
validateMetadataHeaders(webhook.get("MetadataHttpHeaders"), null, null);
return;
}
validateMetadataHeaders(webhook.get("MetadataHttpHeaders"),
auth.get(present.getFirst()).path(authHeaderMember).asText(),
present.getFirst() + "." + authHeaderMember);
}
private static void validateBasic(JsonNode basic) {
if (basic.hasNonNull("Username") != basic.hasNonNull("Password")) {
throw invalidInput(AUTH + ".BasicHttpAuthConfiguration must set both Username and Password, or neither. "
+ "Supplying only one is not valid; omit both to have EventBridge generate the credential.");
}
}
private static void validateHmac(JsonNode hmac) {
String secret = hmacSecretValue(hmac);
boolean base64 = "BASE64".equals(hmac.path("SecretEncoding").asText(null));
int secretBytes = 0;
if (secret != null) {
if (base64) {
try {
secretBytes = Base64.getDecoder().decode(secret).length;
} catch (IllegalArgumentException e) {
throw invalidInput(AUTH + ".HmacAuthConfiguration.SecretValue must be standard Base64 when "
+ "SecretEncoding is BASE64");
}
} else {
secretBytes = secret.getBytes(StandardCharsets.UTF_8).length;
}
}
String signature = hmac.path("SignatureHttpHeader").asText(null);
String timestamp = hmac.path("TimestampHttpHeader").asText(null);
String messageId = hmac.path("MessageIdHttpHeader").asText(null);
String composition = hmac.path("SignedMessageComposition").asText(null);
boolean signsTimestamp = "TIMESTAMP_DOT_BODY".equals(composition)
|| "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY".equals(composition);
if (secret != null && secretBytes < MIN_HMAC_SECRET_BYTES) {
throw hmacInvalid("SecretValue must be at least 16 bytes (for BASE64, after decoding)");
}
if (hmac.hasNonNull("TimestampToleranceInSeconds") && timestamp == null) {
throw hmacInvalid("TimestampToleranceInSeconds requires TimestampHttpHeader to be set");
}
if (timestamp != null && !signsTimestamp) {
throw hmacInvalid("TimestampHttpHeader and TimestampToleranceInSeconds require a "
+ "SignedMessageComposition that signs the timestamp (TIMESTAMP_DOT_BODY or "
+ "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY)");
}
if (signsTimestamp && timestamp == null) {
throw hmacInvalid(composition + " requires TimestampHttpHeader to be set");
}
if ("MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY".equals(composition) && messageId == null) {
throw hmacInvalid("MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY requires MessageIdHttpHeader to be set");
}
if (timestamp != null && signature != null && signature.equalsIgnoreCase(timestamp)) {
if (!hmac.hasNonNull("Delimiter")) {
throw hmacInvalid("Delimiter is required when SignatureHttpHeader and TimestampHttpHeader are the "
+ "same");
}
if (!hmac.hasNonNull("SignaturePrefix") || !hmac.hasNonNull("TimestampPrefix")) {
throw hmacInvalid("SignaturePrefix and TimestampPrefix are both required when SignatureHttpHeader "
+ "and TimestampHttpHeader are the same");
}
}
refuseAuthHeader(HMAC, "SignatureHttpHeader", signature);
refuseAuthHeader(HMAC, "TimestampHttpHeader", timestamp);
refuseAuthHeader(HMAC, "MessageIdHttpHeader", messageId);
}
private static void refuseAuthHeader(String configuration, String member, String header) {
if (header != null && REFUSED_AUTH_HEADERS.contains(header.toLowerCase(Locale.ROOT))) {
throw invalidInput(AUTH + "." + configuration + "." + member + " can't be the header " + header
+ ": it is not allowed. Header names are case-insensitive.");
}
}
private static void validateMetadataHeaders(JsonNode headers, String authHeader, String authHeaderMember) {
if (headers == null || !headers.isArray()) {
return;
}
Set<String> seen = new HashSet<>();
for (JsonNode node : headers) {
String header = node.asText();
String key = header.toLowerCase(Locale.ROOT);
if (REFUSED_METADATA_HEADERS.contains(key)) {
throw invalidInput(METADATA + " can't include the header " + header + ": it is not allowed");
}
if (authHeader != null && authHeader.equalsIgnoreCase(header)) {
throw invalidInput(METADATA + " can't include the header " + header + " because it is "
+ authHeaderMember);
}
if (!seen.add(key)) {
throw invalidInput(METADATA + " lists the header " + header
+ " more than once. Header names are case-insensitive.");
}
}
}
private static AwsException hmacInvalid(String reason) {
return invalidInput(HMAC_INVALID + reason);
}
// ──────────────────────────── Forms of the configuration ────────────────────────────
/**
* The {@code SecretValue} of an HMAC configuration as stored and checked: with {@code SecretEncoding} BASE64,
* the {@code whsec_} prefix signing tools put on a Base64 secret is removed. Null when none is given.
*/
static String hmacSecretValue(JsonNode hmac) {
JsonNode node = hmac.get("SecretValue");
if (node == null || !node.isTextual()) {
return null;
}
String value = node.textValue();
return "BASE64".equals(hmac.path("SecretEncoding").asText(null)) && value.startsWith(WHSEC)
? value.substring(WHSEC.length()) : value;
}
/** The authentication type of a webhook configuration, the name of its one authentication member. */
static String authType(JsonNode webhook) {
List<String> present = presentAuthMembers(webhook.path("AuthConfiguration"));
return present.isEmpty() ? null : present.getFirst();
}
/**
* The {@code Configuration} a describe returns for a validated request: as given, less the members the model
* does not declare and the members that hold secrets, and with no member that was sent as null.
*/
static JsonNode echo(JsonNode webhook) {
ObjectNode copy = (ObjectNode) EventBridgeV2RequestShapes.modeled("WebhookEventsSourceConfiguration", webhook);
JsonNode auth = copy.path("AuthConfiguration");
for (String member : AUTH_MEMBERS) {
if (auth.get(member) instanceof ObjectNode configuration) {
SECRET_MEMBERS.forEach(configuration::remove);
}
}
dropNulls(copy);
ObjectNode configuration = copy.objectNode();
configuration.set(WEBHOOK, copy);
return configuration;
}
private static void dropNulls(JsonNode node) {
if (node instanceof ObjectNode object) {
Iterator<Map.Entry<String, JsonNode>> fields = object.properties().iterator();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
if (field.getValue().isNull()) {
fields.remove();
} else {
dropNulls(field.getValue());
}
}
}
}
// ──────────────────────────── Helpers ────────────────────────────
private static Set<String> lowerCased(String... names) {
Set<String> set = new HashSet<>();
for (String name : names) {
set.add(name.toLowerCase(Locale.ROOT));
}
return Set.copyOf(set);
}
private static Set<String> withExtras(Set<String> common, String... extras) {
Set<String> set = new HashSet<>(common);
set.addAll(lowerCased(extras));
return Set.copyOf(set);
}
}
@@ -0,0 +1,47 @@
package io.floci.aws.services.eventbridgev2;
import io.floci.aws.core.common.Base64Url;
import io.floci.aws.core.common.Digests;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
/**
* The host id and the path token of a webhook URL. The token holds 32 random bytes and the first 16 bytes of the
* SHA-256 of the host id and those bytes.
*/
final class WebhookTokens {
private static final int HOST_ID_LENGTH = 38;
private static final String TOKEN_PREFIX = "k1";
private static final String HOST_ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
private static final int RANDOM_BYTES = 32;
private static final int CHECK_BYTES = 16;
private WebhookTokens() {
}
static String newHostId(SecureRandom random) {
StringBuilder id = new StringBuilder(HOST_ID_LENGTH).append('a');
while (id.length() < HOST_ID_LENGTH) {
id.append(HOST_ID_ALPHABET.charAt(random.nextInt(HOST_ID_ALPHABET.length())));
}
return id.toString();
}
static String newToken(String hostId, SecureRandom random) {
byte[] payload = new byte[RANDOM_BYTES];
random.nextBytes(payload);
byte[] token = Arrays.copyOf(payload, RANDOM_BYTES + CHECK_BYTES);
System.arraycopy(check(hostId, payload), 0, token, RANDOM_BYTES, CHECK_BYTES);
return TOKEN_PREFIX + Base64Url.encode(token);
}
private static byte[] check(String hostId, byte[] payload) {
byte[] hostBytes = hostId.getBytes(StandardCharsets.US_ASCII);
byte[] input = Arrays.copyOf(hostBytes, hostBytes.length + payload.length);
System.arraycopy(payload, 0, input, hostBytes.length, payload.length);
return Arrays.copyOf(Digests.sha256(input), CHECK_BYTES);
}
}
@@ -0,0 +1,147 @@
package io.floci.aws.services.eventbridgev2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* An EventBridge V2 webhook event source. The configuration is kept in the form the source returns it, without
* the credentials, which live in the secret.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class EventSourceV2 {
private String name;
private String arn;
private String eventBusArn;
private String description;
private JsonNode configuration;
private String state;
private Instant creationTime;
private Instant lastModifiedTime;
private Map<String, String> tags = new LinkedHashMap<>();
private String clientToken;
private String createRequestHash;
private String webhookHost;
private String webhookToken;
private String secretArn;
public EventSourceV2() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getArn() {
return arn;
}
public void setArn(String arn) {
this.arn = arn;
}
public String getEventBusArn() {
return eventBusArn;
}
public void setEventBusArn(String eventBusArn) {
this.eventBusArn = eventBusArn;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public JsonNode getConfiguration() {
return configuration;
}
public void setConfiguration(JsonNode configuration) {
this.configuration = configuration;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Instant getCreationTime() {
return creationTime;
}
public void setCreationTime(Instant creationTime) {
this.creationTime = creationTime;
}
public Instant getLastModifiedTime() {
return lastModifiedTime;
}
public void setLastModifiedTime(Instant lastModifiedTime) {
this.lastModifiedTime = lastModifiedTime;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public String getClientToken() {
return clientToken;
}
public void setClientToken(String clientToken) {
this.clientToken = clientToken;
}
public String getCreateRequestHash() {
return createRequestHash;
}
public void setCreateRequestHash(String createRequestHash) {
this.createRequestHash = createRequestHash;
}
public String getWebhookHostId() {
return webhookHost;
}
public void setWebhookHostId(String webhookHost) {
this.webhookHost = webhookHost;
}
public String getWebhookToken() {
return webhookToken;
}
public void setWebhookToken(String webhookToken) {
this.webhookToken = webhookToken;
}
public String getSecretArn() {
return secretArn;
}
public void setSecretArn(String secretArn) {
this.secretArn = secretArn;
}
}