feat(eventbridgev2): receive webhook events (#9424)

The webhook event sources #9321 added had a URL that answered nothing. A POST to it is now checked in the order AWS checks it: the method, the URL's host-bound token, the body size, the source's credential (a static token, Basic or an HMAC signature, read from its Secrets Manager secret and compared in constant time) and then the body, which must be one JSON value. A request that passes is published as an event on the source's bus with its listed headers as Metadata, and CONTENT_BASED deduplication drops a repeat within five minutes.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-25 07:09:43 -04:00
1 parent bc98bbbb23
commit 6a7428aabc
20 files changed
+2518 -17

No files matched your search

+43 -1
View File
@@ -107,7 +107,7 @@ Floci serves event sources of the `WebhookEventsConfiguration` kind. A request w
`arn:aws:events:<region>:<account>:event-sourcev2/webhook/<name>/<id>`.
- A source name is unique per account and Region, across event buses.
- The webhook URL is `<scheme>://<host id>.c01.events-webhook.<region>.<authority>/<token>/`. The scheme and
authority are those of Floci's base URL. The URL does not accept requests yet.
authority are those of Floci's base URL. A POST to it publishes an event, as described below.
- Each source has a Secrets Manager secret named `events-webhook!<uuid>`, owned by `events-webhook`. It holds the
static token, the HMAC secret, or the Basic credential as `{"username":"...","password":"..."}`. A credential
the request leaves out is generated. The secret ARN is in `EventSourceDetails.WebhookDetails.SecretArn`.
@@ -118,6 +118,48 @@ Floci serves event sources of the `WebhookEventsConfiguration` kind. A request w
- `DeleteEventSource` schedules the secret for deletion at once.
- `DescribeEventSource` and `ListEventSources` do not return `Revoked`.
### Receiving events
A POST to the webhook URL authenticates the caller and publishes the body as an event on the source's bus.
Subscribers receive it as they receive a `PutEvents` event, with the next sequence number of the bus.
The request is answered in this order.
1. A method other than POST is `400`, even on an unknown URL.
2. A path that is not exactly `/<token>/` or a token that does not belong to the host is `404`. A query string is accepted.
3. A body over 1048576 bytes is `400`.
4. A caller that fails authentication is `403`. So is a URL whose source was deleted.
5. A body that is not one JSON value is `400`.
The answers are `OK`, `Forbidden`, `Bad Request` and `Not Found` as `text/plain`, with `x-amzn-RequestId`.
A `400` also sends `Connection: close` and closes the connection.
- The body may be any JSON value. Floci refuses an empty body, a duplicate key at any depth, a second value,
trailing text, a byte order mark, text that is not UTF-8, `NaN`, single quotes, comments, trailing commas and a
leading zero.
Floats are written as doubles, so `1e2` becomes `100.0`. Integers keep their size. `Content-Type` is not checked.
- `StaticTokenAuthConfiguration` compares the whole value of `TokenHttpHeader` with the secret.
`BasicHttpAuthConfiguration` reads `Authorization` with the scheme `Basic` in any case and one space.
- `HmacAuthConfiguration` signs the body, the timestamp and the body, or the message id, the timestamp and the body,
with `Algorithm` `SHA1` or `SHA256`. `Encoding` is `HEX` or `BASE64`. A hex signature may be in any case.
A Base64 signature may lack padding and may not be URL-safe. `SecretEncoding` `BASE64` decodes the secret first.
`SignaturePrefix` is required when set. `Delimiter` splits a list of signatures and any one may match.
When `SignatureHttpHeader` and `TimestampHttpHeader` are the same header, the elements may come in any order.
A timestamp is epoch seconds or an ISO-8601 date and time with an offset. `TimestampToleranceInSeconds` applies
to past and future, and is 300 when the source does not set it. A message id with a `.` is refused.
- The event is `Data`, `Metadata` and `SystemMetadata`. `Data` is the parsed body. `Metadata` holds the
`MetadataHttpHeaders` of the source under lower-case names. Repeated headers are joined with `, `.
An empty value and a value over 1024 UTF-8 bytes are dropped. The names come in the order AWS gives them,
which is that of a hash map and not that of the list.
- `SystemMetadata` has `EventGroupId`, `DeduplicationId`, `ContentType`, `aws:IngestionTime`, `aws:EventId`,
`aws:SequenceNumber` and `aws:DeliveryType`. It has no `aws:Source` or `aws:DetailType`.
- A `WITH_METADATA` subscriber receives the three parts. A `RAW` subscriber receives the request body as sent.
- `DeduplicationType` `CONTENT_BASED` drops a request whose body bytes and copied metadata the source saw in the
last 5 minutes. The request is answered `200` and publishes nothing. `EventGroupId` and `DeduplicationId` are then
a 64 character hash, and otherwise a random UUID. The hash is SHA-256 over an encoding of Floci's own,
so it does not equal the hash AWS gives. The hashes are kept in memory and are lost on restart.
- The host of the request decides the source. The Region in the host is not checked.
- Not emulated: `429` throttling, `LogConfiguration` delivery and `Revoked`.
## IAM
Under IAM enforcement, EventBridge V2 operations are authorized as the `events` actions of the same
@@ -61,6 +61,9 @@ public class EventBridgeV2Delivery {
if ("WITH_METADATA".equals(type)) {
return event.withMetadata().toString();
}
if (event.rawData() != null) {
return event.rawData();
}
JsonNode data = event.data();
return data.isTextual() ? data.textValue() : data.toString();
}
@@ -53,6 +53,7 @@ public class EventBridgeV2EventSources implements Resettable {
private final Clock clock;
private final URI baseUrl;
private final SecureRandom random = new SecureRandom();
private final WebhookDeduplication deduplication;
@Inject
public EventBridgeV2EventSources(StorageFactory storageFactory, SecretsManagerService secrets,
@@ -69,6 +70,7 @@ public class EventBridgeV2EventSources implements Resettable {
this.regionResolver = regionResolver;
this.clock = clock;
this.baseUrl = URI.create(baseUrl);
this.deduplication = new WebhookDeduplication(clock);
}
/**
@@ -201,6 +203,7 @@ public class EventBridgeV2EventSources implements Resettable {
LOG.warnv("The secret {0} of event source {1} is already gone", source.getSecretArn(), source.getArn());
}
sources.delete(EventBridgeV2Service.storageKey(region, source.getName()));
deduplication.forget(source.getArn());
}
/**
@@ -253,9 +256,30 @@ public class EventBridgeV2EventSources implements Resettable {
+ source.getWebhookToken() + "/";
}
record LocatedSource(String accountId, EventSourceV2 source) {
}
/** The source whose URL has this host id, in whichever account holds it. */
Optional<LocatedSource> locate(String hostId) {
return sources.scanAllAccountEntries(key -> true).stream()
.filter(entry -> hostId.equals(entry.value().getWebhookHostId()))
.map(entry -> new LocatedSource(entry.accountId(), entry.value()))
.findFirst();
}
/** Records a request hash the source received and returns true, or false when it saw the hash lately. */
boolean firstSeen(EventSourceV2 source, String hash) {
return deduplication.firstSeen(source.getArn(), hash);
}
void forgetSeen(EventSourceV2 source, String hash) {
deduplication.forget(source.getArn(), hash);
}
@Override
public void clear() {
sources.clear();
deduplication.clear();
}
private String createSecret(JsonNode webhook, String region) {
@@ -483,26 +483,61 @@ public class EventBridgeV2Service implements Resettable {
results.add(new PutEventsResult(null, null, "MalformedDetail", "Detail is malformed."));
continue;
}
bus.setSequenceNumber(bus.getSequenceNumber() + 1);
String sequenceNumber = Long.toString(bus.getSequenceNumber());
PublishedEvent event = envelope(bus, entry, times.get(i), detail, sequenceNumber);
results.add(new PutEventsResult(event.systemMetadata().get("aws:EventId").asText(), sequenceNumber,
null, null));
for (SubscriberV2 subscriber : running) {
if (SubscriberFilters.matches(subscriber.getFilterConfiguration(), event)) {
deliveries.add(Map.entry(subscriber, event));
}
}
Instant time = times.get(i);
PublishedEvent event = accept(bus, running, deliveries,
sequenceNumber -> envelope(bus, entry, time, detail, sequenceNumber));
results.add(new PutEventsResult(event.systemMetadata().get("aws:EventId").asText(),
event.systemMetadata().get("aws:SequenceNumber").asText(), null, null));
}
buses.put(storageKey(region, bus.getName()), bus);
ordered = deliveriesByBus.computeIfAbsent(bus.getArn(),
arn -> new OrderedDeliveries(new ConcurrentLinkedQueue<>(), new ReentrantLock()));
ordered.pending().addAll(deliveries);
ordered = enqueue(bus, region, deliveries);
}
send(ordered);
return results;
}
/**
* Accepts an event a webhook event source received on the bus and delivers it to every running subscriber whose
* filters it matches, as {@code PutEvents} does. {@code build} makes the event from the sequence number the bus
* gives it.
*/
PublishedEvent publishWebhookEvent(String eventBusArn, String region, Function<String, PublishedEvent> build) {
List<Map.Entry<SubscriberV2, PublishedEvent>> deliveries = new ArrayList<>();
PublishedEvent event;
OrderedDeliveries ordered;
synchronized (this) {
EventBusV2 bus = requireEventBus(eventBusArn, region);
List<SubscriberV2> running = subscribersOf(bus, region).stream()
.filter(subscriber -> RUNNING.equals(subscriber.getState()))
.toList();
event = accept(bus, running, deliveries, build);
ordered = enqueue(bus, region, deliveries);
}
send(ordered);
return event;
}
private PublishedEvent accept(EventBusV2 bus, List<SubscriberV2> running,
List<Map.Entry<SubscriberV2, PublishedEvent>> deliveries,
Function<String, PublishedEvent> build) {
bus.setSequenceNumber(bus.getSequenceNumber() + 1);
PublishedEvent event = build.apply(Long.toString(bus.getSequenceNumber()));
for (SubscriberV2 subscriber : running) {
if (SubscriberFilters.matches(subscriber.getFilterConfiguration(), event)) {
deliveries.add(Map.entry(subscriber, event));
}
}
return event;
}
private OrderedDeliveries enqueue(EventBusV2 bus, String region,
List<Map.Entry<SubscriberV2, PublishedEvent>> deliveries) {
buses.put(storageKey(region, bus.getName()), bus);
OrderedDeliveries ordered = deliveriesByBus.computeIfAbsent(bus.getArn(),
arn -> new OrderedDeliveries(new ConcurrentLinkedQueue<>(), new ReentrantLock()));
ordered.pending().addAll(deliveries);
return ordered;
}
/**
* Sends a bus's queued deliveries in the order {@code PutEvents} queued them, which is sequence order, holding the
* bus's sending lock, so a request that took later sequence numbers never sends ahead of an earlier one. Every
@@ -0,0 +1,135 @@
package io.floci.aws.services.eventbridgev2;
import io.floci.aws.core.common.RequestHost;
import io.floci.aws.core.common.ServiceConfigAccess;
import io.floci.aws.services.eventbridgev2.EventBridgeV2Webhooks.Answer;
import io.floci.aws.services.eventbridgev2.EventBridgeV2Webhooks.Request;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.HttpVersion;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Serves the URLs of webhook event sources. A request whose Host is {@code <id>.c01.events-webhook.<region>.<host>}
* is answered here and any other host goes on to the other routes.
*/
@ApplicationScoped
public class EventBridgeV2WebhookDataPlane {
private static final Logger LOG = Logger.getLogger(EventBridgeV2WebhookDataPlane.class);
private static final Pattern WEBHOOK_HOST = Pattern.compile(
"(a[a-z2-7]{37})\\.c01\\.events-webhook\\.[a-z0-9-]+\\..+", Pattern.CASE_INSENSITIVE);
private static final String SERVICE = "eventsv2";
private static final Answer INTERNAL_ERROR = new Answer(500, "Internal Server Error");
private final EventBridgeV2Webhooks webhooks;
private final ServiceConfigAccess serviceConfigAccess;
private final Vertx vertx;
@Inject
public EventBridgeV2WebhookDataPlane(EventBridgeV2Webhooks webhooks, ServiceConfigAccess serviceConfigAccess,
Vertx vertx) {
this.webhooks = webhooks;
this.serviceConfigAccess = serviceConfigAccess;
this.vertx = vertx;
}
void register(@Observes Router router) {
router.route().handler(this::handle);
}
/** The host id of a webhook host, in lower case, or empty for any other host. */
static Optional<String> hostId(String host) {
if (host == null) {
return Optional.empty();
}
Matcher matcher = WEBHOOK_HOST.matcher(host);
return matcher.matches() ? Optional.of(matcher.group(1).toLowerCase(Locale.ROOT)) : Optional.empty();
}
void handle(RoutingContext context) {
HttpServerRequest request = context.request();
Optional<String> hostId = hostId(RequestHost.of(request));
if (hostId.isEmpty() || !serviceConfigAccess.isEnabled(SERVICE)) {
context.next();
return;
}
if ("100-continue".equalsIgnoreCase(request.getHeader("Expect"))) {
request.response().writeContinue();
}
BoundedBody body = new BoundedBody();
request.handler(body::add);
request.exceptionHandler(e -> LOG.debugv(e, "A webhook request for {0} was cut short", hostId.get()));
request.endHandler(ignored -> vertx.<Answer>executeBlocking(() -> webhooks.receive(new Request(
request.method().name(), hostId.get(), request.path(),
WebhookEvents.headerValues(request.headers()), body.bytes(), body.oversize())), false)
.onComplete(answered -> {
if (answered.failed()) {
LOG.errorv(answered.cause(), "A webhook request for {0} failed", hostId.get());
}
answer(request, answered.succeeded() ? answered.result() : INTERNAL_ERROR);
}));
request.resume();
}
private static void answer(HttpServerRequest request, Answer answer) {
byte[] text = answer.body().getBytes(StandardCharsets.UTF_8);
HttpServerResponse response = request.response();
response.setStatusCode(answer.status())
.putHeader("x-amzn-RequestId", UUID.randomUUID().toString())
.putHeader("Content-Type", "text/plain")
.putHeader("Content-Length", Integer.toString(text.length));
boolean closes = answer.closesConnection() && request.version() != HttpVersion.HTTP_2;
if (closes) {
response.putHeader("Connection", "close");
}
// Vert.x leaves the body out of a HEAD answer on HTTP/1.x only.
Future<Void> ended = request.method() == HttpMethod.HEAD ? response.end() : response.end(Buffer.buffer(text));
if (closes) {
// Vert.x closes by the Connection header of the request, not of the response.
ended.onComplete(ignored -> request.connection().close());
}
}
/** The request body up to the size limit, then only whether it went past it. */
private static final class BoundedBody {
private final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
private boolean oversize;
void add(Buffer chunk) {
if (oversize) {
return;
}
if (bytes.size() + chunk.length() > WebhookEvents.MAX_BODY_BYTES) {
oversize = true;
bytes.reset();
return;
}
bytes.writeBytes(chunk.getBytes());
}
byte[] bytes() {
return bytes.toByteArray();
}
boolean oversize() {
return oversize;
}
}
}
@@ -0,0 +1,135 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.eventbridgev2.EventBridgeV2EventSources.LocatedSource;
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Clock;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* What a webhook event source does with a request to its URL, in the order AWS checks it: the method, the URL, the
* size of the body, the credential and then the body. A request that passes becomes an event on the source's bus.
* It blocks on storage, so it is never called on the event loop.
*/
@ApplicationScoped
public class EventBridgeV2Webhooks {
/** {@code headers} are keyed by lower-case name. {@code body} is empty when {@code oversize} is set. */
record Request(String method, String hostId, String path, Map<String, String> headers, byte[] body,
boolean oversize) {
}
/** The reply: a status and its plain text body. A 400 also closes the connection. */
record Answer(int status, String body) {
boolean closesConnection() {
return status == 400;
}
}
static final Answer OK = new Answer(200, "OK");
static final Answer FORBIDDEN = new Answer(403, "Forbidden");
static final Answer BAD_REQUEST = new Answer(400, "Bad Request");
static final Answer NOT_FOUND = new Answer(404, "Not Found");
private static final Logger LOG = Logger.getLogger(EventBridgeV2Webhooks.class);
private static final Pattern PATH = Pattern.compile("/(k1[A-Za-z0-9_-]{64})/");
private final EventBridgeV2Service service;
private final EventBridgeV2EventSources sources;
private final SecretsManagerService secrets;
private final Clock clock;
@Inject
public EventBridgeV2Webhooks(EventBridgeV2Service service, EventBridgeV2EventSources sources,
SecretsManagerService secrets) {
this(service, sources, secrets, Clock.systemUTC());
}
EventBridgeV2Webhooks(EventBridgeV2Service service, EventBridgeV2EventSources sources,
SecretsManagerService secrets, Clock clock) {
this.service = service;
this.sources = sources;
this.secrets = secrets;
this.clock = clock;
}
Answer receive(Request request) {
if (!"POST".equals(request.method())) {
return BAD_REQUEST;
}
Matcher path = PATH.matcher(request.path());
if (!path.matches() || !WebhookTokens.isValid(request.hostId(), path.group(1))) {
return NOT_FOUND;
}
if (request.oversize()) {
return BAD_REQUEST;
}
Optional<LocatedSource> located = sources.locate(request.hostId());
if (located.isEmpty()) {
return FORBIDDEN;
}
EventSourceV2 source = located.get().source();
if (!MessageDigest.isEqual(path.group(1).getBytes(StandardCharsets.US_ASCII),
source.getWebhookToken().getBytes(StandardCharsets.US_ASCII))) {
return NOT_FOUND;
}
String accountId = located.get().accountId();
String region = AwsArnUtils.parse(source.getArn()).region();
JsonNode webhook = source.getConfiguration().path(WebhookEventsConfigurations.WEBHOOK);
Optional<String> secret = currentSecret(accountId, region, source);
if (secret.isEmpty()
|| !WebhookAuthenticator.allows(webhook, secret.get(), request.headers(), request.body(),
clock.instant())) {
return FORBIDDEN;
}
Optional<JsonNode> data = WebhookEvents.parseBody(request.body());
if (data.isEmpty()) {
return BAD_REQUEST;
}
Map<String, String> metadata = WebhookEvents.metadata(webhook.path("MetadataHttpHeaders"), request.headers());
boolean contentBased = WebhookEvents.CONTENT_BASED.equals(
webhook.path("DeduplicationConfiguration").path("DeduplicationType").asText());
String groupId = contentBased ? WebhookEvents.contentHash(request.body(), metadata)
: UUID.randomUUID().toString();
if (contentBased && !sources.firstSeen(source, groupId)) {
return OK;
}
try {
RequestScopes.runAs(accountId, region, () -> service.publishWebhookEvent(source.getEventBusArn(), region,
sequenceNumber -> WebhookEvents.event(data.get(), request.body(), metadata, groupId,
clock.instant(), UUID.randomUUID().toString(), sequenceNumber)));
} catch (RuntimeException e) {
if (contentBased) {
// The sender retries a request that failed, and the retry is not a repeat.
sources.forgetSeen(source, groupId);
}
throw e;
}
return OK;
}
private Optional<String> currentSecret(String accountId, String region, EventSourceV2 source) {
try {
return Optional.ofNullable(RequestScopes.callAs(accountId, region,
() -> secrets.getSecretValue(source.getSecretArn(), null, null, region).getSecretString()));
} catch (AwsException e) {
LOG.warnv("The secret of event source {0} could not be read: {1}", source.getArn(), e.getMessage());
return Optional.empty();
}
}
}
@@ -7,9 +7,14 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* An event on an EventBridge V2 bus, in the three parts filters, transformers and target parameters address:
* {@code Data}, the payload (for {@code PutEvents}, the EventBridge envelope); {@code Metadata}, the producer's
* keys; and {@code SystemMetadata}, the string fields EventBridge assigns.
* keys; and {@code SystemMetadata}, the string fields EventBridge assigns. A webhook event also keeps the request
* body as it was sent, which a {@code RAW} delivery passes on.
*/
record PublishedEvent(JsonNode data, ObjectNode metadata, ObjectNode systemMetadata) {
record PublishedEvent(JsonNode data, ObjectNode metadata, ObjectNode systemMetadata, String rawData) {
PublishedEvent(JsonNode data, ObjectNode metadata, ObjectNode systemMetadata) {
this(data, metadata, systemMetadata, null);
}
/** The event as {@code $events} and a {@code WITH_METADATA} delivery hold it. */
ObjectNode withMetadata() {
@@ -0,0 +1,257 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import org.jboss.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.time.DateTimeException;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Decides whether a webhook request carries the credential its event source holds, by the rules of the source's
* authentication type. Secrets and signatures are compared in constant time.
*/
final class WebhookAuthenticator {
private static final Logger LOG = Logger.getLogger(WebhookAuthenticator.class);
private static final ObjectMapper JSON = new ObjectMapper();
private static final Pattern EPOCH_SECONDS = Pattern.compile("[0-9]+");
private static final String BASIC_SCHEME = "Basic ";
private static final String MESSAGE_ID_COMPOSITION = "MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY";
private static final String TIMESTAMP_COMPOSITION = "TIMESTAMP_DOT_BODY";
// AWS holds a timestamp to this window when the source sets no TimestampToleranceInSeconds.
private static final long DEFAULT_TOLERANCE_SECONDS = 300;
private WebhookAuthenticator() {
}
/** {@code headers} are keyed by lower-case name. */
static boolean allows(JsonNode webhook, String secret, Map<String, String> headers, byte[] body, Instant now) {
JsonNode auth = webhook.path("AuthConfiguration");
if (auth.hasNonNull(WebhookEventsConfigurations.STATIC_TOKEN)) {
return staticToken(auth.get(WebhookEventsConfigurations.STATIC_TOKEN), secret, headers);
}
if (auth.hasNonNull(WebhookEventsConfigurations.BASIC)) {
return basic(secret, headers);
}
if (auth.hasNonNull(WebhookEventsConfigurations.HMAC)) {
return hmac(auth.get(WebhookEventsConfigurations.HMAC), secret, headers, body, now);
}
return false;
}
private static boolean staticToken(JsonNode configuration, String secret, Map<String, String> headers) {
String value = headers.get(configuration.path("TokenHttpHeader").asText().toLowerCase(Locale.ROOT));
return value != null && equal(value, secret);
}
private static boolean basic(String secret, Map<String, String> headers) {
String value = headers.get("authorization");
if (value == null || !value.regionMatches(true, 0, BASIC_SCHEME, 0, BASIC_SCHEME.length())) {
return false;
}
String credentials;
try {
credentials = new String(Base64.getDecoder().decode(value.substring(BASIC_SCHEME.length())),
StandardCharsets.UTF_8);
} catch (IllegalArgumentException ignored) {
// Not Base64, so it holds no credential.
return false;
}
int colon = credentials.indexOf(':');
if (colon < 0) {
return false;
}
JsonNode stored;
try {
stored = JSON.readTree(secret);
} catch (IOException ignored) {
// Refused below as a secret without the members. The message may quote the secret, so it is not logged.
stored = MissingNode.getInstance();
}
JsonNode storedUsername = stored.path("username");
JsonNode storedPassword = stored.path("password");
if (!storedUsername.isTextual() || !storedPassword.isTextual()) {
LOG.warn("The secret of a webhook event source with Basic authentication holds no username and password");
return false;
}
boolean user = equal(credentials.substring(0, colon), storedUsername.textValue());
boolean password = equal(credentials.substring(colon + 1), storedPassword.textValue());
return user & password;
}
private static boolean hmac(JsonNode configuration, String secret, Map<String, String> headers, byte[] body,
Instant now) {
String signatureHeader = lowerCase(text(configuration, "SignatureHttpHeader"));
String timestampHeader = lowerCase(text(configuration, "TimestampHttpHeader"));
String delimiter = text(configuration, "Delimiter");
String signaturePrefix = text(configuration, "SignaturePrefix");
String timestampPrefix = text(configuration, "TimestampPrefix");
String composition = configuration.path("SignedMessageComposition").asText("BODY");
String signatureValue = headers.get(signatureHeader);
if (signatureValue == null) {
return false;
}
List<String> signatures = new ArrayList<>();
String timestamp = null;
if (timestampHeader != null && timestampHeader.equals(signatureHeader)) {
for (String element : elements(signatureValue, delimiter)) {
if (timestamp == null && timestampPrefix != null && element.startsWith(timestampPrefix)) {
timestamp = element.substring(timestampPrefix.length());
} else if (signaturePrefix != null && element.startsWith(signaturePrefix)) {
signatures.add(element.substring(signaturePrefix.length()));
}
}
} else {
for (String element : elements(signatureValue, delimiter)) {
if (signaturePrefix == null) {
signatures.add(element);
} else if (element.startsWith(signaturePrefix)) {
signatures.add(element.substring(signaturePrefix.length()));
}
}
if (timestampHeader != null) {
timestamp = headers.get(timestampHeader);
if (timestamp != null && timestampPrefix != null) {
timestamp = timestamp.startsWith(timestampPrefix)
? timestamp.substring(timestampPrefix.length()) : null;
}
}
}
if (signatures.isEmpty() || (timestampHeader != null && !timestampAccepted(configuration, timestamp, now))) {
return false;
}
ByteArrayOutputStream message = new ByteArrayOutputStream();
if (MESSAGE_ID_COMPOSITION.equals(composition)) {
String messageIdHeader = lowerCase(text(configuration, "MessageIdHttpHeader"));
String messageId = messageIdHeader == null ? null : headers.get(messageIdHeader);
if (messageId == null || messageId.indexOf('.') >= 0 || timestamp == null) {
return false;
}
message.writeBytes((messageId + "." + timestamp + ".").getBytes(StandardCharsets.UTF_8));
} else if (TIMESTAMP_COMPOSITION.equals(composition)) {
if (timestamp == null) {
return false;
}
message.writeBytes((timestamp + ".").getBytes(StandardCharsets.UTF_8));
}
message.writeBytes(body);
byte[] key = key(configuration, secret);
if (key == null) {
return false;
}
byte[] expected = mac(configuration.path("Algorithm").asText(), key, message.toByteArray());
if (expected == null) {
return false;
}
boolean base64 = "BASE64".equals(configuration.path("Encoding").asText());
boolean matched = false;
for (String signature : signatures) {
byte[] decoded = decode(signature, base64);
matched |= decoded != null && MessageDigest.isEqual(expected, decoded);
}
return matched;
}
private static List<String> elements(String value, String delimiter) {
return delimiter == null || delimiter.isEmpty() ? List.of(value)
: List.of(value.split(Pattern.quote(delimiter), -1));
}
private static boolean timestampAccepted(JsonNode configuration, String text, Instant now) {
Instant sent = text == null ? null : instantOf(text);
if (sent == null) {
return false;
}
long tolerance = configuration.hasNonNull("TimestampToleranceInSeconds")
? configuration.get("TimestampToleranceInSeconds").asLong() : DEFAULT_TOLERANCE_SECONDS;
try {
return Duration.between(sent, now).abs().compareTo(Duration.ofSeconds(tolerance)) <= 0;
} catch (ArithmeticException ignored) {
// Too far from now to measure, so outside any tolerance.
return false;
}
}
/**
* Epoch seconds or an ISO-8601 date and time with an offset. A count of milliseconds reads as seconds far ahead,
* which the tolerance refuses.
*/
private static Instant instantOf(String text) {
try {
if (EPOCH_SECONDS.matcher(text).matches()) {
return Instant.ofEpochSecond(Long.parseLong(text));
}
return OffsetDateTime.parse(text).toInstant();
} catch (DateTimeException | NumberFormatException ignored) {
// Neither form, so not a time.
return null;
}
}
private static byte[] key(JsonNode configuration, String secret) {
if (!"BASE64".equals(configuration.path("SecretEncoding").asText())) {
return secret.getBytes(StandardCharsets.UTF_8);
}
try {
return Base64.getDecoder().decode(secret);
} catch (IllegalArgumentException e) {
LOG.warnv("The secret of a webhook event source with SecretEncoding BASE64 is not Base64: {0}",
e.getMessage());
return null;
}
}
private static byte[] mac(String algorithm, byte[] key, byte[] message) {
String name = "SHA1".equals(algorithm) ? "HmacSHA1" : "HmacSHA256";
try {
Mac mac = Mac.getInstance(name);
mac.init(new SecretKeySpec(key, name));
return mac.doFinal(message);
} catch (GeneralSecurityException | IllegalArgumentException e) {
LOG.warnv("The {0} of a webhook request could not be computed: {1}", name, e.getMessage());
return null;
}
}
private static byte[] decode(String signature, boolean base64) {
try {
return base64 ? Base64.getDecoder().decode(signature) : HexFormat.of().parseHex(signature);
} catch (IllegalArgumentException ignored) {
// Not in the encoding of the source, so it matches nothing.
return null;
}
}
private static String text(JsonNode node, String member) {
return node.hasNonNull(member) ? node.get(member).asText() : null;
}
private static String lowerCase(String name) {
return name == null ? null : name.toLowerCase(Locale.ROOT);
}
private static boolean equal(String given, String stored) {
return MessageDigest.isEqual(given.getBytes(StandardCharsets.UTF_8), stored.getBytes(StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,63 @@
package io.floci.aws.services.eventbridgev2;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* The request hashes each webhook event source saw in the last five minutes, for {@code CONTENT_BASED}
* deduplication. They are kept in memory only.
*/
final class WebhookDeduplication {
static final Duration WINDOW = Duration.ofMinutes(5);
private final Clock clock;
private final ConcurrentMap<String, Map<String, Instant>> seenBySource = new ConcurrentHashMap<>();
WebhookDeduplication(Clock clock) {
this.clock = clock;
}
/** Records the hash for the source and returns true, or returns false when the source saw it in the window. */
boolean firstSeen(String sourceArn, String hash) {
Instant now = clock.instant();
Instant oldest = now.minus(WINDOW);
Map<String, Instant> seen = seenBySource.computeIfAbsent(sourceArn, arn -> new LinkedHashMap<>());
synchronized (seen) {
// The hashes are in the order they were first seen, so the old ones are at the head.
Iterator<Instant> times = seen.values().iterator();
while (times.hasNext() && !times.next().isAfter(oldest)) {
times.remove();
}
Instant first = seen.get(hash);
if (first != null && first.isAfter(oldest)) {
return false;
}
seen.remove(hash);
seen.put(hash, now);
return true;
}
}
void forget(String sourceArn, String hash) {
Map<String, Instant> seen = seenBySource.get(sourceArn);
if (seen != null) {
synchronized (seen) {
seen.remove(hash);
}
}
}
void forget(String sourceArn) {
seenBySource.remove(sourceArn);
}
void clear() {
seenBySource.clear();
}
}
@@ -0,0 +1,152 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.core.StreamReadFeature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.Digests;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
/**
* The event a webhook request becomes: its body read as JSON, the headers copied into {@code Metadata}, the
* system metadata and the hash {@code CONTENT_BASED} deduplication compares.
*/
final class WebhookEvents {
static final int MAX_BODY_BYTES = 1_048_576;
static final String CONTENT_BASED = "CONTENT_BASED";
private static final int MAX_METADATA_VALUE_BYTES = 1024;
private static final byte[] UTF8_BOM = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
private static final DateTimeFormatter INGESTION_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
private static final ObjectMapper STRICT = JsonMapper.builder()
.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
.build();
private WebhookEvents() {
}
/**
* The body as one JSON value of any type, or empty when it is not one. A duplicate key at any depth, a second
* value, text after the value, a byte order mark and text that is not UTF-8 make it not one.
*/
static Optional<JsonNode> parseBody(byte[] body) {
if (startsWithBom(body)) {
return Optional.empty();
}
try {
// Jackson reads UTF-16 and UTF-32 from bytes by itself, so it is given the text.
String text = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(body)).toString();
JsonNode value = STRICT.readTree(text);
return value == null || value.isMissingNode() ? Optional.empty() : Optional.of(value);
} catch (IOException ignored) {
// Not UTF-8 or not one JSON value.
return Optional.empty();
}
}
private static boolean startsWithBom(byte[] body) {
return body.length >= UTF8_BOM.length && body[0] == UTF8_BOM[0] && body[1] == UTF8_BOM[1]
&& body[2] == UTF8_BOM[2];
}
/** The request's headers by lower-case name, a repeated header's values joined with {@code ", "}, trimmed. */
static Map<String, String> headerValues(Iterable<Map.Entry<String, String>> headers) {
Map<String, String> joined = new LinkedHashMap<>();
for (Map.Entry<String, String> header : headers) {
joined.merge(header.getKey().toLowerCase(Locale.ROOT), header.getValue(), (a, b) -> a + ", " + b);
}
joined.replaceAll((name, value) -> trim(value));
return joined;
}
/**
* The headers the source lists, under lower-case names. A header that is absent or empty, or whose value is
* longer than 1024 UTF-8 bytes, is left out. AWS delivers them in the order of a hash map sized for the list,
* not in the order of the list.
*/
static Map<String, String> metadata(JsonNode listed, Map<String, String> headers) {
Map<String, String> copied = new HashMap<>(listed.size());
for (JsonNode listedName : listed) {
String name = listedName.asText().toLowerCase(Locale.ROOT);
String value = headers.get(name);
if (value == null) {
continue;
}
value = trim(value);
if (!value.isEmpty() && value.getBytes(StandardCharsets.UTF_8).length <= MAX_METADATA_VALUE_BYTES) {
copied.put(name, value);
}
}
return copied;
}
/**
* The hash of the body bytes and the copied metadata, each part with its length so no two requests share an
* encoding. The headers are hashed by name order, so the hash does not follow the order they are delivered in.
* It holds nothing of the source, so two sources give the same hash for the same request.
*/
static String contentHash(byte[] body, Map<String, String> metadata) {
ByteArrayOutputStream encoded = new ByteArrayOutputStream();
field(encoded, body);
encoded.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(metadata.size()).array());
for (Map.Entry<String, String> header : new TreeMap<>(metadata).entrySet()) {
field(encoded, header.getKey().getBytes(StandardCharsets.UTF_8));
field(encoded, header.getValue().getBytes(StandardCharsets.UTF_8));
}
return Digests.sha256Hex(encoded.toByteArray());
}
private static void field(ByteArrayOutputStream out, byte[] bytes) {
out.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array());
out.writeBytes(bytes);
}
static PublishedEvent event(JsonNode data, byte[] rawBody, Map<String, String> metadata, String groupId,
Instant ingested, String eventId, String sequenceNumber) {
ObjectNode copied = JsonNodeFactory.instance.objectNode();
metadata.forEach(copied::put);
ObjectNode system = JsonNodeFactory.instance.objectNode();
system.put("EventGroupId", groupId);
system.put("DeduplicationId", groupId);
system.put("ContentType", "application/json");
system.put("aws:IngestionTime", INGESTION_TIME.format(ingested));
system.put("aws:EventId", eventId);
system.put("aws:SequenceNumber", sequenceNumber);
system.put("aws:DeliveryType", "LIVE");
return new PublishedEvent(data, copied, system, new String(rawBody, StandardCharsets.UTF_8));
}
private static String trim(String value) {
int start = 0;
int end = value.length();
while (start < end && isBlank(value.charAt(start))) {
start++;
}
while (end > start && isBlank(value.charAt(end - 1))) {
end--;
}
return value.substring(start, end);
}
private static boolean isBlank(char c) {
return c == ' ' || c == '\t';
}
}
@@ -4,8 +4,10 @@ import io.floci.aws.core.common.Base64Url;
import io.floci.aws.core.common.Digests;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
/**
* The host id and the path token of a webhook URL. The token holds 32 random bytes and the first 16 bytes of the
@@ -38,6 +40,25 @@ final class WebhookTokens {
return TOKEN_PREFIX + Base64Url.encode(token);
}
/** Whether {@code token} is one {@link #newToken} built for {@code hostId}. */
static boolean isValid(String hostId, String token) {
if (!token.startsWith(TOKEN_PREFIX)) {
return false;
}
byte[] decoded;
try {
decoded = Base64.getUrlDecoder().decode(token.substring(TOKEN_PREFIX.length()));
} catch (IllegalArgumentException ignored) {
// Not Base64, so not a token.
return false;
}
if (decoded.length != RANDOM_BYTES + CHECK_BYTES) {
return false;
}
byte[] expected = check(hostId, Arrays.copyOf(decoded, RANDOM_BYTES));
return MessageDigest.isEqual(expected, Arrays.copyOfRange(decoded, RANDOM_BYTES, decoded.length));
}
private static byte[] check(String hostId, byte[] payload) {
byte[] hostBytes = hostId.getBytes(StandardCharsets.US_ASCII);
byte[] input = Arrays.copyOf(hostBytes, hostBytes.length + payload.length);
@@ -64,6 +64,7 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
"execute-api", // ApiGatewayExecuteApiHostFilter: <api-id>.execute-api[.<region>].<host>
"lambda-url", // LambdaUrlRoutingFilter: <url-id>.lambda-url.<region>.<host>
"lambda-web", // LambdaWebDataPlane: <id>.<shard>.lambda-web.<region>.<host>, <id>.lambda-web.global.<host>
"events-webhook", // EventBridgeV2WebhookDataPlane: <id>.c01.events-webhook.<region>.<host>
"emr-serverless", // emr-serverless.<host>, an EMR Serverless endpoint, never a bucket
"cloudfront"); // CloudFrontDistributionFilter: <dist-id>.cloudfront.net
@@ -0,0 +1,34 @@
package io.floci.aws.services.eventbridgev2;
import io.floci.aws.testing.ParallelLocks;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.ResourceAccessMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
class EventBridgeV2WebhookDataPlaneTest {
private static final String ID = "abcdefghijklmnopqrstuvwxyz234567abcdef";
@Test
void onlyTheMintedHostShapeIsClaimed() {
assertEquals(Optional.of(ID), EventBridgeV2WebhookDataPlane.hostId(ID + ".c01.events-webhook.us-east-1.localhost:4566"));
assertEquals(Optional.of(ID), EventBridgeV2WebhookDataPlane.hostId(ID + ".c01.events-webhook.us-east-1.on.aws"));
assertEquals(Optional.of(ID), EventBridgeV2WebhookDataPlane.hostId(
ID.toUpperCase() + ".C01.EVENTS-WEBHOOK.US-EAST-1.LOCALHOST:4566"));
assertTrue(EventBridgeV2WebhookDataPlane.hostId(ID + ".c02.events-webhook.us-east-1.localhost").isEmpty());
assertTrue(EventBridgeV2WebhookDataPlane.hostId(ID + ".c01.events-webhook.localhost").isEmpty());
assertTrue(EventBridgeV2WebhookDataPlane.hostId("b" + ID.substring(1) + ".c01.events-webhook.us-east-1.localhost")
.isEmpty());
assertTrue(EventBridgeV2WebhookDataPlane.hostId("a" + ID.substring(2) + ".c01.events-webhook.us-east-1.localhost")
.isEmpty());
assertTrue(EventBridgeV2WebhookDataPlane.hostId(ID + "1.c01.events-webhook.us-east-1.localhost").isEmpty());
assertTrue(EventBridgeV2WebhookDataPlane.hostId("my.events-webhook.archive.localhost").isEmpty());
assertTrue(EventBridgeV2WebhookDataPlane.hostId("localhost:4566").isEmpty());
assertTrue(EventBridgeV2WebhookDataPlane.hostId(null).isEmpty());
}
}
@@ -0,0 +1,426 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpVersion;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.net.SocketAddress;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client;
import software.amazon.awssdk.services.eventbridgev2.model.CreateEventSourceResponse;
import software.amazon.awssdk.services.eventbridgev2.model.EventSourceConfiguration;
import software.amazon.awssdk.services.eventbridgev2.model.TransformerType;
import software.amazon.awssdk.services.eventbridgev2.model.WebhookAuthConfiguration;
import software.amazon.awssdk.services.eventbridgev2.model.WebhookEventsSourceConfiguration;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** A POST to the URL of a webhook event source becomes an event on its bus, read here from the queues of subscribers. */
@QuarkusTest
class EventBridgeV2WebhookIntegrationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String ROLE = "arn:aws:iam::000000000000:role/WebhookRole";
private static final String UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
private static final String HMAC_SECRET = "0123456789abcdef-hmac-key";
@Inject
Vertx vertx;
@Test
void eachAuthenticationTypeDeliversItsEventToTheWithMetadataAndRawSubscribers() throws Exception {
String suffix = suffix();
try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) {
Fixture fixture = fixture(events, sqs, suffix);
Endpoint token = source(events, fixture.bus(), "token-" + suffix, webhook -> webhook
.metadataHttpHeaders("X-Request-Id").authConfiguration(staticToken("X-Token", "s3cret-token")));
Endpoint basic = source(events, fixture.bus(), "basic-" + suffix, webhook -> webhook
.authConfiguration(auth -> auth.basicHttpAuthConfiguration(
credential -> credential.username("alice").password("p4ssword"))));
Endpoint hmac = source(events, fixture.bus(), "hmac-" + suffix, webhook -> webhook
.authConfiguration(auth -> auth.hmacAuthConfiguration(signing -> signing.algorithm("SHA256")
.encoding("HEX").signatureHttpHeader("X-Sig").signaturePrefix("sha256=")
.signedMessageComposition("BODY").secretValue(HMAC_SECRET))));
String tokenBody = "{\"n\":1,\"f\":1e2}";
String basicBody = "{\"n\":2}";
String hmacBody = " {\"n\":3, \"s\":\"\\u00e9\\/\"}\n";
post(token, tokenBody, "X-Token", "s3cret-token", "X-Request-Id", "r-1").then().statusCode(200)
.body(equalTo("OK"));
post(basic, basicBody, "Authorization", "Basic "
+ Base64.getEncoder().encodeToString("alice:p4ssword".getBytes(StandardCharsets.UTF_8)))
.then().statusCode(200).body(equalTo("OK"));
post(hmac, hmacBody, "X-Sig", "sha256=" + sign(HMAC_SECRET, hmacBody)).then().statusCode(200)
.body(equalTo("OK"));
List<ObjectNode> withMetadata = received(sqs, fixture.metadataQueue(), 3);
assertEquals(3, withMetadata.size());
assertEquals("{\"Data\":{\"n\":1,\"f\":100.0},\"Metadata\":{\"x-request-id\":\"r-1\"},"
+ system("1"), normalized(withMetadata.get(0)));
assertEquals("{\"Data\":{\"n\":2},\"Metadata\":{}," + system("2"), normalized(withMetadata.get(1)));
assertEquals("{\"Data\":{\"n\":3,\"s\":\"\u00e9/\"},\"Metadata\":{}," + system("3"),
normalized(withMetadata.get(2)));
List<String> raw = rawBodies(sqs, fixture.rawQueue(), 3);
assertEquals(List.of(tokenBody, basicBody, hmacBody), raw);
fixture.cleanUp(events, sqs, token, basic, hmac);
}
}
@Test
void aRequestThatFailsIsAnsweredAsMeasuredAndPublishesNothing() throws Exception {
String suffix = suffix();
try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) {
Fixture fixture = fixture(events, sqs, suffix);
Endpoint one = source(events, fixture.bus(), "one-" + suffix, webhook -> webhook
.authConfiguration(staticToken("X-Token", "one-token")));
Endpoint two = source(events, fixture.bus(), "two-" + suffix, webhook -> webhook
.authConfiguration(staticToken("X-Token", "two-token")));
expect(post(one, "{}", "X-Token", "wrong"), 403, "Forbidden");
expect(post(one, "{}"), 403, "Forbidden");
expect(post(one, "{}", "X-Token", "two-token"), 403, "Forbidden");
expect(post(one, "{bad", "X-Token", "wrong"), 403, "Forbidden");
expect(request(one.host(), one.path() + "?q=1", "{}", "X-Token", "one-token"), 200, "OK");
expect(request(one.host(), one.path().substring(0, one.path().length() - 1), "{}", "X-Token", "one-token"),
404, "Not Found");
expect(request(one.host(), one.path() + "x/", "{}", "X-Token", "one-token"), 404, "Not Found");
expect(request(one.host(), one.path().replaceFirst(".$", "A/"), "{}", "X-Token", "one-token"), 404,
"Not Found");
expect(request(one.host(), two.path(), "{}", "X-Token", "one-token"), 404, "Not Found");
expect(request(two.host(), one.path(), "{}", "X-Token", "two-token"), 404, "Not Found");
expect(given().header("Host", one.host()).header("X-Token", "one-token").when().get(one.path()), 400,
"Bad Request");
expect(given().header("Host", one.host().toUpperCase()).when().get("/nope"), 400, "Bad Request");
expect(post(one, "{bad", "X-Token", "one-token"), 400, "Bad Request");
expect(post(one, "", "X-Token", "one-token"), 400, "Bad Request");
expect(post(one, "{\"a\":1,\"a\":2}", "X-Token", "one-token"), 400, "Bad Request");
String tooLarge = "{\"pad\":\"" + "a".repeat(1_048_576 - 9) + "\"}";
assertEquals(1_048_577, tooLarge.length());
expect(post(one, tooLarge, "X-Token", "one-token"), 400, "Bad Request");
expect(post(one, tooLarge, "X-Token", "wrong"), 400, "Bad Request");
String atLimit = "{\"pad\":\"" + "a".repeat(1_048_576 - 10) + "\"}";
expect(post(one, atLimit, "X-Token", "one-token"), 200, "OK");
// The queue refuses the 1 MiB message, so only the first request reaches it.
assertEquals(1, messages(sqs, fixture.metadataQueue(), 2).size());
events.deleteEventSource(request -> request.eventSourceArn(one.arn()));
expect(post(one, "{}", "X-Token", "one-token"), 403, "Forbidden");
expect(post(one, "{bad", "X-Token", "one-token"), 403, "Forbidden");
assertEquals(0, messages(sqs, fixture.metadataQueue(), 1).size());
fixture.cleanUp(events, sqs, two);
}
}
@Test
void contentBasedDeduplicationDropsARepeatAndKeepsTheHashAsTheId() throws Exception {
String suffix = suffix();
try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) {
Fixture fixture = fixture(events, sqs, suffix);
Endpoint endpoint = source(events, fixture.bus(), "dedup-" + suffix, webhook -> webhook
.metadataHttpHeaders("X-Meta").deduplicationConfiguration(dedup -> dedup
.deduplicationType("CONTENT_BASED"))
.authConfiguration(staticToken("X-Token", "dedup-token")));
expect(post(endpoint, "{\"dd\":1}", "X-Token", "dedup-token"), 200, "OK");
expect(post(endpoint, "{\"dd\":1}", "X-Token", "dedup-token"), 200, "OK");
expect(post(endpoint, "{ \"dd\" : 1 }", "X-Token", "dedup-token"), 200, "OK");
expect(post(endpoint, "{\"dd\":1}", "X-Token", "dedup-token", "X-Meta", "m1"), 200, "OK");
expect(post(endpoint, "{\"dd\":1}", "X-Token", "dedup-token", "X-Meta", "m1", "X-Other", "o"), 200, "OK");
List<ObjectNode> delivered = received(sqs, fixture.metadataQueue(), 3);
assertEquals(3, delivered.size());
for (ObjectNode event : delivered) {
JsonNode system = event.get("SystemMetadata");
assertTrue(system.get("EventGroupId").asText().matches("[0-9a-f]{64}"), system.toString());
assertEquals(system.get("EventGroupId"), system.get("DeduplicationId"));
}
assertEquals(List.of("1", "2", "3"), delivered.stream()
.map(event -> event.get("SystemMetadata").get("aws:SequenceNumber").asText()).toList());
fixture.cleanUp(events, sqs, endpoint);
}
}
@Test
void aBadRequestClosesTheConnection() throws Exception {
String suffix = suffix();
try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) {
Fixture fixture = fixture(events, sqs, suffix);
Endpoint endpoint = source(events, fixture.bus(), "close-" + suffix, webhook -> webhook
.authConfiguration(staticToken("X-Token", "close-token")));
try (Socket socket = connect()) {
send(socket, "GET " + endpoint.path() + " HTTP/1.1\r\nHost: " + endpoint.host() + "\r\n\r\n");
// The read returns only once Floci closes the connection.
String answer = new String(socket.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
assertTrue(answer.startsWith("HTTP/1.1 400 Bad Request\r\n"), answer);
assertTrue(answer.contains("\r\nConnection: close\r\n"), answer);
assertTrue(answer.endsWith("\r\n\r\nBad Request"), answer);
}
fixture.cleanUp(events, sqs, endpoint);
}
}
@Test
void aRequestThatExpectsContinueIsToldToSendItsBody() throws Exception {
String suffix = suffix();
try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) {
Fixture fixture = fixture(events, sqs, suffix);
Endpoint endpoint = source(events, fixture.bus(), "expect-" + suffix, webhook -> webhook
.authConfiguration(staticToken("X-Token", "expect-token")));
String body = "{\"n\":1}";
try (Socket socket = connect()) {
send(socket, "POST " + endpoint.path() + " HTTP/1.1\r\nHost: " + endpoint.host()
+ "\r\nX-Token: expect-token\r\nContent-Length: " + body.length()
+ "\r\nExpect: 100-continue\r\nConnection: close\r\n\r\n");
String interim = readHead(socket.getInputStream());
assertTrue(interim.startsWith("HTTP/1.1 100 Continue\r\n"), interim);
send(socket, body);
String answer = new String(socket.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
assertTrue(answer.startsWith("HTTP/1.1 200 OK\r\n"), answer);
}
assertEquals(List.of(body), rawBodies(sqs, fixture.rawQueue(), 1));
fixture.cleanUp(events, sqs, endpoint);
}
}
@Test
void aHeadRequestOverHttp2IsAnsweredWithoutABody() throws Exception {
String suffix = suffix();
try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) {
Fixture fixture = fixture(events, sqs, suffix);
Endpoint endpoint = source(events, fixture.bus(), "head-" + suffix, webhook -> webhook
.authConfiguration(staticToken("X-Token", "head-token")));
HttpClient client = vertx.createHttpClient(new HttpClientOptions()
.setProtocolVersion(HttpVersion.HTTP_2).setHttp2ClearTextUpgrade(false));
try {
RequestOptions options = new RequestOptions()
.setServer(SocketAddress.inetSocketAddress(RestAssured.port, "localhost"))
.setHost(URI.create("http://" + endpoint.host()).getHost()).setPort(RestAssured.port)
.setMethod(HttpMethod.HEAD).setURI(endpoint.path());
String answer = client.request(options)
.compose(request -> request.send())
.compose(response -> response.body().map(body -> response.version() + " "
+ response.statusCode() + " " + response.getHeader("Content-Length") + " "
+ body.length()))
.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
assertEquals("HTTP_2 400 11 0", answer);
} finally {
client.close();
}
fixture.cleanUp(events, sqs, endpoint);
}
}
// ──────────────────────────── Fixtures ────────────────────────────
private record Fixture(String bus, String metadataQueue, String rawQueue, String metadataSubscriber,
String rawSubscriber) {
void cleanUp(EventBridgeV2Client events, SqsClient sqs, Endpoint... endpoints) {
for (Endpoint endpoint : endpoints) {
events.deleteEventSource(request -> request.eventSourceArn(endpoint.arn()));
}
events.deleteSubscriber(request -> request.subscriberArn(metadataSubscriber));
events.deleteSubscriber(request -> request.subscriberArn(rawSubscriber));
events.deleteEventBus(request -> request.eventBusArn(bus));
sqs.deleteQueue(request -> request.queueUrl(metadataQueue));
sqs.deleteQueue(request -> request.queueUrl(rawQueue));
}
}
private record Endpoint(String arn, String host, String path) {
}
private static Fixture fixture(EventBridgeV2Client events, SqsClient sqs, String suffix) {
String metadataQueue = sqs.createQueue(request -> request.queueName("v2-hook-meta-" + suffix)).queueUrl();
String rawQueue = sqs.createQueue(request -> request.queueName("v2-hook-raw-" + suffix)).queueUrl();
String bus = events.createEventBus(request -> request.name("v2-hook-" + suffix)).eventBusArn();
String metadataSubscriber = events.createSubscriber(request -> request.name("meta").eventBusArn(bus)
.invokeConfiguration(invoke -> invoke.targetArn(queueArn(sqs, metadataQueue)).roleArn(ROLE))
.transformer(transformer -> transformer.type(TransformerType.WITH_METADATA))).subscriberArn();
String rawSubscriber = events.createSubscriber(request -> request.name("raw").eventBusArn(bus)
.invokeConfiguration(invoke -> invoke.targetArn(queueArn(sqs, rawQueue)).roleArn(ROLE))
.transformer(transformer -> transformer.type(TransformerType.RAW))).subscriberArn();
return new Fixture(bus, metadataQueue, rawQueue, metadataSubscriber, rawSubscriber);
}
private static Endpoint source(EventBridgeV2Client events, String bus, String name,
Consumer<WebhookEventsSourceConfiguration.Builder> webhook) {
CreateEventSourceResponse created = events.createEventSource(request -> request.name(name).eventBusArn(bus)
.configuration(EventSourceConfiguration.fromWebhookEventsConfiguration(
configuration -> configuration.roleArn(ROLE).applyMutation(webhook))));
URI url = URI.create(created.eventSourceDetails().webhookDetails().webhookUrl());
return new Endpoint(created.eventSourceArn(), url.getAuthority(), url.getPath());
}
private static WebhookAuthConfiguration staticToken(String header, String secret) {
return WebhookAuthConfiguration.builder().staticTokenAuthConfiguration(
token -> token.tokenHttpHeader(header).secretValue(secret)).build();
}
// ──────────────────────────── Requests and reads ────────────────────────────
private static Response post(Endpoint endpoint, String body, String... headers) {
return request(endpoint.host(), endpoint.path(), body, headers);
}
private static Response request(String host, String path, String body, String... headers) {
RequestSpecification specification = given().header("Host", host)
.contentType("application/json").body(body.getBytes(StandardCharsets.UTF_8));
for (int i = 0; i < headers.length; i += 2) {
specification = specification.header(headers[i], headers[i + 1]);
}
return specification.when().post(path);
}
private static Socket connect() throws IOException {
Socket socket = new Socket("localhost", RestAssured.port);
// A connection Floci leaves open fails the read instead of leaving it waiting.
socket.setSoTimeout(10_000);
return socket;
}
private static void send(Socket socket, String text) throws IOException {
OutputStream out = socket.getOutputStream();
out.write(text.getBytes(StandardCharsets.UTF_8));
out.flush();
}
private static String readHead(InputStream in) throws IOException {
StringBuilder head = new StringBuilder();
while (head.indexOf("\r\n\r\n") < 0) {
int next = in.read();
if (next < 0) {
throw new IOException("The connection closed inside a response head: " + head);
}
head.append((char) next);
}
return head.toString();
}
private static void expect(Response response, int status, String text) {
response.then().statusCode(status).body(equalTo(text))
.header("Content-Type", "text/plain")
.header("Content-Length", Integer.toString(text.length()))
.header("x-amzn-RequestId", matchesPattern(UUID_PATTERN));
assertEquals(status == 400 ? "close" : null, response.header("Connection"));
}
private static List<ObjectNode> received(SqsClient sqs, String queueUrl, int expected) throws Exception {
List<ObjectNode> bodies = new ArrayList<>();
for (Message message : messages(sqs, queueUrl, expected)) {
bodies.add((ObjectNode) MAPPER.readTree(message.body()));
}
bodies.sort(Comparator.comparingLong(event -> Long.parseLong(
event.get("SystemMetadata").get("aws:SequenceNumber").asText())));
return bodies;
}
private static List<String> rawBodies(SqsClient sqs, String queueUrl, int expected) {
return messages(sqs, queueUrl, expected).stream().map(Message::body)
.sorted(Comparator.comparing(EventBridgeV2WebhookIntegrationTest::dataNumber)).toList();
}
private static int dataNumber(String body) {
try {
return MAPPER.readTree(body).path("n").asInt();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private static List<Message> messages(SqsClient sqs, String queueUrl, int expected) {
List<Message> messages = new ArrayList<>();
for (int attempt = 0; attempt < 3 && messages.size() < expected; attempt++) {
messages.addAll(sqs.receiveMessage(request -> request.queueUrl(queueUrl).maxNumberOfMessages(10)
.waitTimeSeconds(1)).messages());
}
return messages;
}
/** The event with the random ids and the time replaced, after checking their shape. */
private static String normalized(ObjectNode event) {
ObjectNode system = (ObjectNode) event.get("SystemMetadata");
assertTrue(system.get("EventGroupId").asText().matches(UUID_PATTERN), system.toString());
assertEquals(system.get("EventGroupId"), system.get("DeduplicationId"));
assertTrue(system.get("aws:IngestionTime").asText().matches("\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d{3}Z"));
assertTrue(system.get("aws:EventId").asText().matches(UUID_PATTERN), system.toString());
system.put("EventGroupId", "<id>");
system.put("DeduplicationId", "<id>");
system.put("aws:IngestionTime", "<time>");
system.put("aws:EventId", "<id>");
return event.toString();
}
private static String system(String sequenceNumber) {
return "\"SystemMetadata\":{\"EventGroupId\":\"<id>\",\"DeduplicationId\":\"<id>\","
+ "\"ContentType\":\"application/json\",\"aws:IngestionTime\":\"<time>\",\"aws:EventId\":\"<id>\","
+ "\"aws:SequenceNumber\":\"" + sequenceNumber + "\",\"aws:DeliveryType\":\"LIVE\"}}";
}
private static String sign(String secret, String body) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
return HexFormat.of().formatHex(mac.doFinal(body.getBytes(StandardCharsets.UTF_8)));
}
private static String queueArn(SqsClient sqs, String queueUrl) {
return sqs.getQueueAttributes(request -> request.queueUrl(queueUrl)
.attributeNames(QueueAttributeName.QUEUE_ARN)).attributes().get(QueueAttributeName.QUEUE_ARN);
}
private static EventBridgeV2Client events() {
return AwsTestClients.create(EventBridgeV2Client.builder(), "000000000000", Region.US_EAST_1);
}
private static SqsClient sqs() {
return AwsTestClients.create(SqsClient.builder(), "000000000000", Region.US_EAST_1);
}
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
}
@@ -0,0 +1,453 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
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.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.Secret;
import io.floci.aws.services.secretsmanager.model.SecretVersion;
import io.floci.aws.testing.ManualClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class EventBridgeV2WebhooksTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String ROLE = "arn:aws:iam::000000000000:role/Hook";
private static final String QUEUE = "arn:aws:sqs:us-east-1:000000000000:orders";
private static final String TOKEN_AUTH = "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Tok\","
+ "\"SecretValue\":\"s3cret\"}}";
private final Map<String, String> secretStrings = new HashMap<>();
private final List<String> deliveredBodies = new ArrayList<>();
private final List<PublishedEvent> delivered = new ArrayList<>();
private EventBridgeV2EventSources sources;
private EventBridgeV2Service service;
private EventBridgeV2Webhooks webhooks;
private ManualClock clock;
private String bus;
@BeforeEach
void setUp() {
SecretsManagerService secrets = mock(SecretsManagerService.class);
when(secrets.createSecret(any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(call -> {
Secret secret = new Secret();
secret.setArn("arn:aws:secretsmanager:us-east-1:000000000000:secret:" + call.getArgument(0) + "-AbCdEf");
secretStrings.put(secret.getArn(), call.getArgument(1));
return secret;
});
when(secrets.getSecretValue(any(), any(), any(), eq(REGION))).thenAnswer(call -> {
SecretVersion version = new SecretVersion();
version.setSecretString(secretStrings.get(call.<String>getArgument(0)));
return version;
});
when(secrets.describeSecret(any(), any())).thenReturn(new Secret());
EventBridgeV2Delivery delivery = mock(EventBridgeV2Delivery.class);
doAnswer(call -> {
SubscriberV2 subscriber = call.getArgument(0);
PublishedEvent event = call.getArgument(1);
delivered.add(event);
deliveredBodies.add(subscriber.getName() + "=" + EventBridgeV2Delivery.body(subscriber, event));
return null;
}).when(delivery).deliver(any(), any());
clock = new ManualClock(Instant.parse("2026-11-25T06:00:00.123Z"));
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
sources = new EventBridgeV2EventSources(
AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, "http://floci.test:4566");
service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT),
AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, sources, clock, true);
webhooks = new EventBridgeV2Webhooks(service, sources, secrets, clock);
bus = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn();
subscriber("meta", "{\"Type\":\"WITH_METADATA\"}", "RUNNING");
subscriber("raw", "{\"Type\":\"RAW\"}", "RUNNING");
}
// ──────────────────────────── Order of checks ────────────────────────────
@Test
void aMethodOtherThanPostIsBadRequestEvenOnAnUnknownUrl() {
Target target = source("hook", TOKEN_AUTH, "");
assertEquals(EventBridgeV2Webhooks.BAD_REQUEST, answer("GET", target, target.path(), Map.of(), "{}"));
assertEquals(EventBridgeV2Webhooks.BAD_REQUEST, answer("PUT", target, target.path(), Map.of(), "{}"));
assertEquals(EventBridgeV2Webhooks.BAD_REQUEST, answer("GET", target, "/nope", Map.of(), "{}"));
assertEquals(EventBridgeV2Webhooks.BAD_REQUEST, webhooks.receive(
new Request("DELETE", "a" + "b".repeat(37), "/", Map.of(), new byte[0], false)));
}
@Test
void aUrlThatIsNotTheSourcesIsNotFoundWhateverTheCredential() {
Target one = source("one", TOKEN_AUTH, "");
Target two = source("two", TOKEN_AUTH, "");
Map<String, String> good = Map.of("x-tok", "s3cret");
assertEquals(EventBridgeV2Webhooks.NOT_FOUND, answer("POST", one, one.path().substring(0, 60) + "/", good, "{}"));
assertEquals(EventBridgeV2Webhooks.NOT_FOUND,
answer("POST", one, one.path().substring(0, one.path().length() - 1), good, "{}"));
assertEquals(EventBridgeV2Webhooks.NOT_FOUND, answer("POST", one, one.path() + "extra/", good, "{}"));
assertEquals(EventBridgeV2Webhooks.NOT_FOUND, answer("POST", one, "/", good, "{}"));
assertEquals(EventBridgeV2Webhooks.NOT_FOUND, answer("POST", one, "/k1" + "A".repeat(64) + "/", good, "{}"));
assertEquals(EventBridgeV2Webhooks.NOT_FOUND, answer("POST", one, two.path(), good, "{}"));
assertEquals(EventBridgeV2Webhooks.NOT_FOUND, answer("POST", two, one.path(), good, "{}"));
assertEquals(EventBridgeV2Webhooks.NOT_FOUND, webhooks.receive(new Request("POST", "a" + "b".repeat(37),
one.path(), good, new byte[0], false)));
assertTrue(deliveredBodies.isEmpty());
}
@Test
void aBodyOverTheLimitIsBadRequestEvenWithABadCredential() {
Target target = source("hook", TOKEN_AUTH, "");
assertEquals(EventBridgeV2Webhooks.BAD_REQUEST,
webhooks.receive(new Request("POST", target.hostId(), target.path(), Map.of("x-tok", "wrong"),
new byte[0], true)));
assertEquals(EventBridgeV2Webhooks.BAD_REQUEST,
webhooks.receive(new Request("POST", target.hostId(), target.path(), Map.of("x-tok", "s3cret"),
new byte[0], true)));
}
@Test
void aBodyOfExactlyTheLimitIsAnEventAndTheLimitIs1048576() {
assertEquals(1_048_576, WebhookEvents.MAX_BODY_BYTES);
Target target = source("hook", TOKEN_AUTH, "");
String body = "{\"pad\":\"" + "a".repeat(1_048_576 - 10) + "\"}";
assertEquals(1_048_576, body.length());
assertEquals(EventBridgeV2Webhooks.OK, answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), body));
assertEquals(2, deliveredBodies.size());
}
@Test
void aBadCredentialIsForbiddenBeforeTheBodyIsRead() {
Target target = source("hook", TOKEN_AUTH, "");
assertEquals(EventBridgeV2Webhooks.FORBIDDEN, answer("POST", target, target.path(), Map.of("x-tok", "no"), "{bad"));
assertEquals(EventBridgeV2Webhooks.FORBIDDEN, answer("POST", target, target.path(), Map.of(), ""));
assertEquals(EventBridgeV2Webhooks.BAD_REQUEST,
answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), "{bad"));
assertEquals(EventBridgeV2Webhooks.BAD_REQUEST,
answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), ""));
assertTrue(deliveredBodies.isEmpty());
}
@Test
void aSourceThatWasDeletedAnswersForbiddenAtItsFormerUrl() {
Target target = source("hook", TOKEN_AUTH, "");
service.deleteEventSource(json("{\"EventSourceArn\":\"" + target.source().getArn() + "\"}"), REGION);
assertEquals(EventBridgeV2Webhooks.FORBIDDEN,
answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), "{}"));
}
@Test
void theAnswersAreTheMeasuredStatusesAndTexts() {
assertEquals(new Answer(200, "OK"), EventBridgeV2Webhooks.OK);
assertEquals(new Answer(403, "Forbidden"), EventBridgeV2Webhooks.FORBIDDEN);
assertEquals(new Answer(400, "Bad Request"), EventBridgeV2Webhooks.BAD_REQUEST);
assertEquals(new Answer(404, "Not Found"), EventBridgeV2Webhooks.NOT_FOUND);
assertTrue(EventBridgeV2Webhooks.BAD_REQUEST.closesConnection());
assertFalse(EventBridgeV2Webhooks.OK.closesConnection());
assertFalse(EventBridgeV2Webhooks.FORBIDDEN.closesConnection());
assertFalse(EventBridgeV2Webhooks.NOT_FOUND.closesConnection());
}
// ──────────────────────────── Events ────────────────────────────
@Test
void aValidRequestIsDeliveredToEachRunningSubscriberAsTheirTransformerSays() throws Exception {
Target target = source("hook", TOKEN_AUTH, ",\"MetadataHttpHeaders\":[\"X-Meta\",\"X-Missing\"]");
String body = " {\"e\":1e2, \"s\":\"\\/\"}\n";
assertEquals(EventBridgeV2Webhooks.OK, answer("POST", target, target.path(),
Map.of("x-tok", "s3cret", "x-meta", "m1", "x-unlisted", "u"), body));
assertEquals(2, deliveredBodies.size());
JsonNode meta = MAPPER.readTree(bodyOf("meta"));
assertEquals("{\"e\":100.0,\"s\":\"/\"}", meta.get("Data").toString());
assertEquals("{\"x-meta\":\"m1\"}", meta.get("Metadata").toString());
JsonNode system = meta.get("SystemMetadata");
assertEquals(List.of("EventGroupId", "DeduplicationId", "ContentType", "aws:IngestionTime", "aws:EventId",
"aws:SequenceNumber", "aws:DeliveryType"), system.properties().stream().map(Map.Entry::getKey).toList());
assertEquals(system.get("EventGroupId"), system.get("DeduplicationId"));
assertTrue(system.get("EventGroupId").asText().matches("[0-9a-f-]{36}"));
assertEquals("application/json", system.get("ContentType").asText());
assertEquals("2026-11-25T06:00:00.123Z", system.get("aws:IngestionTime").asText());
assertEquals("1", system.get("aws:SequenceNumber").asText());
assertEquals("LIVE", system.get("aws:DeliveryType").asText());
assertEquals(body, bodyOf("raw"));
}
@Test
void eachEventTakesTheBusNextSequenceNumberInOrderWithPutEvents() {
Target target = source("hook", TOKEN_AUTH, "");
service.putEvents(json("{\"EventBusArn\":\"" + bus + "\",\"Entries\":[{\"Source\":\"a\","
+ "\"DetailType\":\"t\"}]}"), REGION);
deliveredBodies.clear();
delivered.clear();
answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), "{\"n\":1}");
answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), "{\"n\":2}");
assertEquals(List.of("2", "2", "3", "3"), delivered.stream()
.map(event -> event.systemMetadata().get("aws:SequenceNumber").asText()).toList());
}
@Test
void aStoppedSubscriberGetsNothing() {
subscriber("stopped", "{\"Type\":\"RAW\"}", "STOPPED");
Target target = source("hook", TOKEN_AUTH, "");
answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), "{}");
assertEquals(2, deliveredBodies.size());
assertTrue(deliveredBodies.stream().noneMatch(delivery -> delivery.startsWith("stopped=")));
}
@Test
void aSubscriberWhoseFilterDoesNotMatchGetsNothing() {
subscriber("big", "{\"Type\":\"RAW\"}", "RUNNING", ",\"FilterConfiguration\":{\"Filters\":[{\"Scope\":\"DATA\","
+ "\"Pattern\":\"{\\\"total\\\":[{\\\"numeric\\\":[\\\">\\\",500]}]}\"}]}");
Target target = source("hook", TOKEN_AUTH, "");
answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), "{\"total\":900}");
answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), "{\"total\":20}");
assertEquals(1, deliveredBodies.stream().filter(delivery -> delivery.startsWith("big=")).count());
assertEquals(4, deliveredBodies.stream().filter(delivery -> !delivery.startsWith("big=")).count());
}
@Test
void anEventWithoutDeduplicationHasAFreshRandomIdEachTime() {
Target target = source("hook", TOKEN_AUTH, "");
answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), "{}");
answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), "{}");
assertEquals(4, delivered.size());
assertNotEquals(delivered.get(0).systemMetadata().get("EventGroupId"),
delivered.get(2).systemMetadata().get("EventGroupId"));
}
// ──────────────────────────── Authentication types ────────────────────────────
@Test
void basicIsCheckedAgainstTheUsernameAndPasswordOfTheSecret() {
Target target = source("basic", "{\"BasicHttpAuthConfiguration\":{\"Username\":\"alice\","
+ "\"Password\":\"pw1234\"}}", "");
String good = "Basic " + Base64.getEncoder().encodeToString("alice:pw1234".getBytes(StandardCharsets.UTF_8));
assertEquals(EventBridgeV2Webhooks.OK, answer("POST", target, target.path(), Map.of("authorization", good), "{}"));
assertEquals(EventBridgeV2Webhooks.FORBIDDEN,
answer("POST", target, target.path(), Map.of("authorization", good + "x"), "{}"));
}
@Test
void hmacIsCheckedOverTheRawBodyBytes() throws Exception {
Target target = source("hmac", "{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\","
+ "\"SignatureHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\","
+ "\"SecretValue\":\"0123456789abcdef\"}}", "");
String body = "{ \"a\" : 1 }";
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec("0123456789abcdef".getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
String signature = HexFormat.of().formatHex(mac.doFinal(body.getBytes(StandardCharsets.UTF_8)));
assertEquals(EventBridgeV2Webhooks.OK, answer("POST", target, target.path(), Map.of("x-sig", signature), body));
assertEquals(EventBridgeV2Webhooks.FORBIDDEN,
answer("POST", target, target.path(), Map.of("x-sig", signature), "{\"a\":1}"));
}
// ──────────────────────────── Deduplication ────────────────────────────
private static final String DEDUP = ",\"DeduplicationConfiguration\":{\"DeduplicationType\":\"CONTENT_BASED\"}";
@Test
void aRepeatedRequestAnswersOkAndPublishesNothing() {
Target target = source("hook", TOKEN_AUTH, DEDUP);
Map<String, String> headers = Map.of("x-tok", "s3cret");
assertEquals(EventBridgeV2Webhooks.OK, answer("POST", target, target.path(), headers, "{\"dd\":1}"));
assertEquals(2, delivered.size());
assertEquals(EventBridgeV2Webhooks.OK, answer("POST", target, target.path(), headers, "{\"dd\":1}"));
assertEquals(2, delivered.size());
JsonNode system = delivered.getFirst().systemMetadata();
assertTrue(system.get("EventGroupId").asText().matches("[0-9a-f]{64}"));
assertEquals(system.get("EventGroupId"), system.get("DeduplicationId"));
}
@Test
void anotherSpacingOfTheSameValueIsAnotherEvent() {
Target target = source("hook", TOKEN_AUTH, DEDUP);
Map<String, String> headers = Map.of("x-tok", "s3cret");
answer("POST", target, target.path(), headers, "{\"dd\":1}");
answer("POST", target, target.path(), headers, "{ \"dd\" : 1 }");
assertEquals(4, delivered.size());
assertNotEquals(delivered.get(0).systemMetadata().get("EventGroupId"),
delivered.get(2).systemMetadata().get("EventGroupId"));
}
@Test
void anotherSourceOnTheSameBusGetsItsOwnEventAndTheSameId() {
Target one = source("one", TOKEN_AUTH, DEDUP);
Target two = source("two", TOKEN_AUTH, DEDUP);
Map<String, String> headers = Map.of("x-tok", "s3cret");
answer("POST", one, one.path(), headers, "{\"dd\":1}");
answer("POST", two, two.path(), headers, "{\"dd\":1}");
assertEquals(4, delivered.size());
assertEquals(delivered.get(0).systemMetadata().get("EventGroupId"),
delivered.get(2).systemMetadata().get("EventGroupId"));
}
@Test
void theCopiedMetadataCountsButTheOrderTheHeadersArriveInAndAnUnlistedHeaderDoNot() {
Target target = source("hook", TOKEN_AUTH, DEDUP.concat(",\"MetadataHttpHeaders\":[\"X-Meta\",\"X-Two\"]"));
Map<String, String> base = Map.of("x-tok", "s3cret");
answer("POST", target, target.path(), base, "{\"dd\":2}");
assertEquals(2, delivered.size());
answer("POST", target, target.path(), Map.of("x-tok", "s3cret", "x-meta", "m1"), "{\"dd\":2}");
assertEquals(4, delivered.size());
answer("POST", target, target.path(), inOrder("x-tok", "s3cret", "x-meta", "m1", "x-two", "t"), "{\"dd\":2}");
assertEquals(6, delivered.size());
answer("POST", target, target.path(), inOrder("x-two", "t", "x-meta", "m1", "x-tok", "s3cret"), "{\"dd\":2}");
assertEquals(6, delivered.size());
answer("POST", target, target.path(),
Map.of("x-tok", "s3cret", "x-meta", "m1", "x-two", "t", "x-other", "o"), "{\"dd\":2}");
assertEquals(6, delivered.size());
answer("POST", target, target.path(), Map.of("x-tok", "s3cret", "x-meta", "m2", "x-two", "t"), "{\"dd\":2}");
assertEquals(8, delivered.size());
}
@Test
void aRepeatAfterFiveMinutesIsDeliveredAgain() {
Target target = source("hook", TOKEN_AUTH, DEDUP);
Map<String, String> headers = Map.of("x-tok", "s3cret");
answer("POST", target, target.path(), headers, "{\"dd\":1}");
clock.advance(Duration.ofMinutes(4).plusSeconds(59));
answer("POST", target, target.path(), headers, "{\"dd\":1}");
assertEquals(2, delivered.size());
clock.advance(Duration.ofSeconds(1));
answer("POST", target, target.path(), headers, "{\"dd\":1}");
assertEquals(4, delivered.size());
}
@Test
void aDroppedRepeatTakesNoSequenceNumber() {
Target target = source("hook", TOKEN_AUTH, DEDUP);
Map<String, String> headers = Map.of("x-tok", "s3cret");
answer("POST", target, target.path(), headers, "{\"dd\":1}");
answer("POST", target, target.path(), headers, "{\"dd\":1}");
answer("POST", target, target.path(), headers, "{\"dd\":2}");
assertEquals(List.of("1", "1", "2", "2"), delivered.stream()
.map(event -> event.systemMetadata().get("aws:SequenceNumber").asText()).toList());
}
@Test
void aRequestWhosePublishFailsIsNotKeptAsSeen() {
Target target = source("hook", TOKEN_AUTH, DEDUP);
String body = "{\"dd\":1}";
service.clear();
assertThrows(AwsException.class,
() -> answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), body));
assertTrue(sources.firstSeen(target.source(),
WebhookEvents.contentHash(body.getBytes(StandardCharsets.UTF_8), Map.of())));
}
@Test
void deletingASourceAndResettingForgetTheHashes() {
Target target = source("hook", TOKEN_AUTH, DEDUP);
assertTrue(sources.firstSeen(target.source(), "h1"));
assertFalse(sources.firstSeen(target.source(), "h1"));
service.deleteEventSource(json("{\"EventSourceArn\":\"" + target.source().getArn() + "\"}"), REGION);
assertTrue(sources.firstSeen(target.source(), "h1"));
sources.clear();
assertTrue(sources.firstSeen(target.source(), "h1"));
}
// ──────────────────────────── Helpers ────────────────────────────
private record Target(EventSourceV2 source, String hostId, String path) {
}
private Target source(String name, String auth, String extra) {
EventSourceV2 source = service.createEventSource(json("{\"ClientToken\":\"" + name + "-token\",\"Name\":\""
+ name + "\",\"EventBusArn\":\"" + bus + "\",\"Configuration\":{\"WebhookEventsConfiguration\":"
+ "{\"AuthConfiguration\":" + auth + ",\"RoleArn\":\"" + ROLE + "\"" + extra + "}}}"), REGION);
URI url = URI.create(service.webhookUrl(source));
return new Target(source, source.getWebhookHostId(), url.getPath());
}
private void subscriber(String name, String transformer, String state, String... extra) {
service.createSubscriber(json("{\"Name\":\"" + name + "\",\"EventBusArn\":\"" + bus + "\",\"State\":\"" + state
+ "\",\"InvokeConfiguration\":{\"TargetArn\":\"" + QUEUE + "\",\"RoleArn\":\"" + ROLE
+ "\"},\"Transformer\":" + transformer + String.join("", extra) + "}"), REGION);
}
private Answer answer(String method, Target target, String path, Map<String, String> headers, String body) {
return webhooks.receive(new Request(method, target.hostId(), path, headers,
body.getBytes(StandardCharsets.UTF_8), false));
}
private static Map<String, String> inOrder(String... namesAndValues) {
Map<String, String> headers = new LinkedHashMap<>();
for (int i = 0; i < namesAndValues.length; i += 2) {
headers.put(namesAndValues[i], namesAndValues[i + 1]);
}
return headers;
}
private String bodyOf(String subscriber) {
return deliveredBodies.stream().filter(delivery -> delivery.startsWith(subscriber + "="))
.map(delivery -> delivery.substring(subscriber.length() + 1)).findFirst().orElseThrow();
}
private static JsonNode json(String value) {
try {
return MAPPER.readTree(value);
} catch (Exception e) {
throw new IllegalArgumentException(value, e);
}
}
}
@@ -0,0 +1,339 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class WebhookAuthenticatorTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final Instant NOW = Instant.parse("2026-11-25T06:00:00Z");
private static final long NOW_SECONDS = NOW.getEpochSecond();
private static final byte[] BODY = "{\"n\":1}".getBytes(StandardCharsets.UTF_8);
private static final String SECRET = "whsec-0123456789abcdef";
// ──────────────────────────── Static token ────────────────────────────
@Test
void aStaticTokenMustEqualTheWholeHeaderValue() {
JsonNode webhook = webhook("{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"Authorization\"}}");
assertTrue(allows(webhook, "Bearer abc", Map.of("authorization", "Bearer abc")));
assertFalse(allows(webhook, "Bearer abc", Map.of("authorization", "abc")));
assertFalse(allows(webhook, "Bearer abc", Map.of("authorization", "bearer abc")));
assertFalse(allows(webhook, "Bearer abc", Map.of("authorization", "Bearer abc ")));
assertFalse(allows(webhook, "Bearer abc", Map.of()));
}
@Test
void aStaticTokenHeaderIsMatchedWhateverItsCase() {
JsonNode webhook = webhook("{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Webhook-Secret\"}}");
assertTrue(allows(webhook, "s3cret", Map.of("x-webhook-secret", "s3cret")));
assertFalse(allows(webhook, "s3cret", Map.of("x-webhook-secret", "S3CRET")));
}
// ──────────────────────────── Basic ────────────────────────────
@Test
void basicChecksTheUsernameAndThePassword() {
JsonNode webhook = webhook("{\"BasicHttpAuthConfiguration\":{}}");
String secret = "{\"username\":\"alice\",\"password\":\"p4ss:word\"}";
assertTrue(allows(webhook, secret, Map.of("authorization", "Basic " + b64("alice:p4ss:word"))));
assertFalse(allows(webhook, secret, Map.of("authorization", "Basic " + b64("alice:wrong"))));
assertFalse(allows(webhook, secret, Map.of("authorization", "Basic " + b64("bob:p4ss:word"))));
assertFalse(allows(webhook, secret, Map.of("authorization", "Basic " + b64("alice"))));
assertFalse(allows(webhook, secret, Map.of()));
}
@Test
void basicTakesTheSchemeInAnyCaseAndExactlyOneSpace() {
JsonNode webhook = webhook("{\"BasicHttpAuthConfiguration\":{}}");
String secret = "{\"username\":\"alice\",\"password\":\"pw\"}";
String credentials = b64("alice:pw");
assertTrue(allows(webhook, secret, Map.of("authorization", "basic " + credentials)));
assertTrue(allows(webhook, secret, Map.of("authorization", "BASIC " + credentials)));
assertFalse(allows(webhook, secret, Map.of("authorization", "Basic " + credentials)));
assertFalse(allows(webhook, secret, Map.of("authorization", credentials)));
assertFalse(allows(webhook, secret, Map.of("authorization", "Basic !!!notbase64")));
assertFalse(allows(webhook, secret, Map.of("authorization", "Bearer " + credentials)));
}
@Test
void aBasicSecretWithoutAUsernameAndAPasswordAllowsNoRequest() {
JsonNode webhook = webhook("{\"BasicHttpAuthConfiguration\":{}}");
Map<String, String> emptyCredentials = Map.of("authorization", "Basic " + b64(":"));
for (String secret : List.of("{}", "{\"username\":\"\"}", "{\"Username\":\"\",\"Password\":\"\"}", "\"text\"",
"12345678", "null", "", "not json")) {
assertFalse(allows(webhook, secret, emptyCredentials), secret);
}
}
// ──────────────────────────── HMAC, body only ────────────────────────────
@Test
void aHexSignatureWithAPrefixIsAcceptedInAnyCaseOfItsDigits() {
JsonNode webhook = hmac("\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"SignaturePrefix\":\"sha256=\","
+ "\"SignatureHttpHeader\":\"X-Hub-Signature-256\",\"SignedMessageComposition\":\"BODY\"");
String digest = hex(mac("HmacSHA256", SECRET.getBytes(StandardCharsets.UTF_8), BODY));
assertTrue(allows(webhook, SECRET, Map.of("x-hub-signature-256", "sha256=" + digest)));
assertTrue(allows(webhook, SECRET, Map.of("x-hub-signature-256", "sha256=" + digest.toUpperCase())));
assertFalse(allows(webhook, SECRET, Map.of("x-hub-signature-256", digest)));
assertFalse(allows(webhook, SECRET, Map.of("x-hub-signature-256", "sha256=" + digest.substring(1))));
assertFalse(allows(webhook, SECRET, Map.of("x-hub-signature-256", "sha256=" + "0".repeat(64))));
assertFalse(allows(webhook, SECRET, Map.of()));
}
@Test
void aSignatureOfAnotherBodyIsRefused() {
JsonNode webhook = hmac("\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"SignatureHttpHeader\":\"X-Sig\","
+ "\"SignedMessageComposition\":\"BODY\"");
byte[] other = "{\"n\":2}".getBytes(StandardCharsets.UTF_8);
assertTrue(allows(webhook, SECRET, Map.of("x-sig", hex(mac("HmacSHA256", key(SECRET), BODY)))));
assertFalse(allows(webhook, SECRET, Map.of("x-sig", hex(mac("HmacSHA256", key(SECRET), other)))));
}
@Test
void sha1SignaturesUseHmacSha1() {
JsonNode webhook = hmac("\"Algorithm\":\"SHA1\",\"Encoding\":\"HEX\",\"SignatureHttpHeader\":\"X-Sig\","
+ "\"SignedMessageComposition\":\"BODY\"");
assertTrue(allows(webhook, SECRET, Map.of("x-sig", hex(mac("HmacSHA1", key(SECRET), BODY)))));
assertFalse(allows(webhook, SECRET, Map.of("x-sig", hex(mac("HmacSHA256", key(SECRET), BODY)))));
}
@Test
void aRawSecretIsTheKeyAsTypedAndABase64SecretIsTheKeyDecoded() {
byte[] decoded = "0123456789abcdef-key".getBytes(StandardCharsets.UTF_8);
String base64Secret = Base64.getEncoder().encodeToString(decoded);
JsonNode raw = hmac("\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"SecretEncoding\":\"RAW\","
+ "\"SignatureHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\"");
JsonNode base64 = hmac("\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"SecretEncoding\":\"BASE64\","
+ "\"SignatureHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\"");
assertTrue(allows(raw, base64Secret, Map.of("x-sig", hex(mac("HmacSHA256", key(base64Secret), BODY)))));
assertFalse(allows(raw, base64Secret, Map.of("x-sig", hex(mac("HmacSHA256", decoded, BODY)))));
assertTrue(allows(base64, base64Secret, Map.of("x-sig", hex(mac("HmacSHA256", decoded, BODY)))));
assertFalse(allows(base64, base64Secret, Map.of("x-sig", hex(mac("HmacSHA256", key(base64Secret), BODY)))));
}
@Test
void aBase64SignatureMayBeUnpaddedButNotUrlSafe() {
JsonNode webhook = hmac("\"Algorithm\":\"SHA256\",\"Encoding\":\"BASE64\",\"SignatureHttpHeader\":\"X-Sig\","
+ "\"SignedMessageComposition\":\"BODY\"");
String secret = secretWhoseDigestNeedsUrlSafeCharacters();
byte[] digest = mac("HmacSHA256", key(secret), BODY);
String padded = Base64.getEncoder().encodeToString(digest);
assertTrue(padded.endsWith("="));
assertTrue(allows(webhook, secret, Map.of("x-sig", padded)));
assertTrue(allows(webhook, secret, Map.of("x-sig", Base64.getEncoder().withoutPadding().encodeToString(digest))));
assertFalse(allows(webhook, secret, Map.of("x-sig", Base64.getUrlEncoder().encodeToString(digest))));
assertFalse(allows(webhook, secret, Map.of("x-sig", " " + padded)));
}
/** A secret whose digest of the body has '+' or '/' in Base64, so the URL-safe form differs. */
private static String secretWhoseDigestNeedsUrlSafeCharacters() {
for (int i = 0; ; i++) {
String secret = "secret-for-digest-" + i;
String standard = Base64.getEncoder().encodeToString(mac("HmacSHA256", key(secret), BODY));
if (standard.contains("+") || standard.contains("/")) {
return secret;
}
}
}
@Test
void aSpaceDelimitedListOfPrefixedSignaturesMatchesWhenAnyOneDoes() {
JsonNode webhook = hmac("\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"SignaturePrefix\":\"v1,\","
+ "\"Delimiter\":\" \",\"SignatureHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\"");
String good = hex(mac("HmacSHA256", key(SECRET), BODY));
assertTrue(allows(webhook, SECRET, Map.of("x-sig", "v1," + "0".repeat(64) + " v1," + good)));
assertTrue(allows(webhook, SECRET, Map.of("x-sig", "v1," + good + " v1," + "0".repeat(64))));
assertFalse(allows(webhook, SECRET, Map.of("x-sig", "v1," + "0".repeat(64) + " v1," + "1".repeat(64))));
assertFalse(allows(webhook, SECRET, Map.of("x-sig", good)));
}
// ──────────────────────────── HMAC with a timestamp ────────────────────────────
private static final String STRIPE = "\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"SignatureHttpHeader\":"
+ "\"Stripe-Signature\",\"TimestampHttpHeader\":\"Stripe-Signature\",\"Delimiter\":\",\","
+ "\"SignaturePrefix\":\"v1=\",\"TimestampPrefix\":\"t=\",\"SignedMessageComposition\":"
+ "\"TIMESTAMP_DOT_BODY\",\"TimestampToleranceInSeconds\":300";
@Test
void theSameHeaderFormTakesItsElementsInAnyOrderAndAnySignatureMayMatch() {
JsonNode webhook = hmac(STRIPE);
String good = signTimestamped(Long.toString(NOW_SECONDS));
String bad = "0".repeat(64);
assertTrue(allows(webhook, SECRET, Map.of("stripe-signature", "t=" + NOW_SECONDS + ",v1=" + good)));
assertTrue(allows(webhook, SECRET, Map.of("stripe-signature", "v1=" + good + ",t=" + NOW_SECONDS)));
assertTrue(allows(webhook, SECRET,
Map.of("stripe-signature", "t=" + NOW_SECONDS + ",v1=" + bad + ",v1=" + good + ",v0=zzz")));
assertFalse(allows(webhook, SECRET, Map.of("stripe-signature", "t=" + NOW_SECONDS + ", v1=" + good)));
assertFalse(allows(webhook, SECRET, Map.of("stripe-signature", "t=" + NOW_SECONDS + ",v1=" + bad)));
assertFalse(allows(webhook, SECRET, Map.of("stripe-signature", "v1=" + good)));
assertFalse(allows(webhook, SECRET, Map.of("stripe-signature", "t=" + NOW_SECONDS)));
}
@Test
void theToleranceHoldsForThePastAndTheFuture() {
JsonNode webhook = hmac(STRIPE);
assertTrue(allows(webhook, SECRET, stripe(NOW_SECONDS - 280)));
assertTrue(allows(webhook, SECRET, stripe(NOW_SECONDS - 300)));
assertFalse(allows(webhook, SECRET, stripe(NOW_SECONDS - 301)));
assertTrue(allows(webhook, SECRET, stripe(NOW_SECONDS + 280)));
assertTrue(allows(webhook, SECRET, stripe(NOW_SECONDS + 300)));
assertFalse(allows(webhook, SECRET, stripe(NOW_SECONDS + 320)));
}
@Test
void aTimestampIsEpochSecondsOrIso8601AndNothingElse() {
JsonNode webhook = hmac(STRIPE);
assertTrue(allows(webhook, SECRET, stripeText(NOW.toString())));
assertTrue(allows(webhook, SECRET, stripeText("2026-11-25T15:00:00+09:00")));
assertFalse(allows(webhook, SECRET, stripeText(Long.toString(NOW.toEpochMilli()))));
assertFalse(allows(webhook, SECRET, stripeText(NOW_SECONDS + ".123")));
assertFalse(allows(webhook, SECRET, stripeText("abc")));
assertFalse(allows(webhook, SECRET, stripeText("")));
assertFalse(allows(webhook, SECRET, stripeText("99999999999999999999999")));
}
@Test
void withNoToleranceTheWindowIs300Seconds() {
JsonNode webhook = hmac(STRIPE.replace(",\"TimestampToleranceInSeconds\":300", ""));
assertTrue(allows(webhook, SECRET, stripe(NOW_SECONDS - 280)));
assertFalse(allows(webhook, SECRET, stripe(NOW_SECONDS - 301)));
assertTrue(allows(webhook, SECRET, stripe(NOW_SECONDS + 280)));
assertFalse(allows(webhook, SECRET, stripe(NOW_SECONDS + 320)));
assertFalse(allows(webhook, SECRET, stripeText(Long.toString(NOW.toEpochMilli()))));
assertFalse(allows(webhook, SECRET, stripeText("abc")));
}
@Test
void theSignedTextHoldsTheTimestampAsSent() {
JsonNode webhook = hmac(STRIPE);
String iso = NOW.toString();
assertTrue(allows(webhook, SECRET, stripeText(iso)));
assertFalse(allows(webhook, SECRET, Map.of("stripe-signature",
"t=" + iso + ",v1=" + signTimestamped(Long.toString(NOW_SECONDS)))));
}
@Test
void separateSignatureAndTimestampHeadersSignTheTimestampDotTheBody() {
JsonNode webhook = hmac("\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\",\"SignatureHttpHeader\":\"X-Sig\","
+ "\"TimestampHttpHeader\":\"X-Ts\",\"TimestampPrefix\":\"ts:\",\"SignedMessageComposition\":"
+ "\"TIMESTAMP_DOT_BODY\",\"TimestampToleranceInSeconds\":60");
String text = Long.toString(NOW_SECONDS);
String signature = signTimestamped(text);
assertTrue(allows(webhook, SECRET, Map.of("x-sig", signature, "x-ts", "ts:" + text)));
assertFalse(allows(webhook, SECRET, Map.of("x-sig", signature, "x-ts", text)));
assertFalse(allows(webhook, SECRET, Map.of("x-sig", signature)));
assertFalse(allows(webhook, SECRET, Map.of("x-sig", signature, "x-ts", "ts:" + (NOW_SECONDS - 61))));
}
@Test
void aMessageIdIsSignedBeforeTheTimestampAndMayNotHoldADot() {
JsonNode webhook = hmac("\"Algorithm\":\"SHA256\",\"Encoding\":\"BASE64\",\"SignaturePrefix\":\"v1,\","
+ "\"SignatureHttpHeader\":\"webhook-signature\",\"TimestampHttpHeader\":\"webhook-timestamp\","
+ "\"MessageIdHttpHeader\":\"webhook-id\",\"SignedMessageComposition\":"
+ "\"MESSAGE_ID_DOT_TIMESTAMP_DOT_BODY\",\"TimestampToleranceInSeconds\":300");
String timestamp = Long.toString(NOW_SECONDS);
String signature = "v1," + Base64.getEncoder().encodeToString(
mac("HmacSHA256", key(SECRET), ("msg_1." + timestamp + ".").getBytes(StandardCharsets.UTF_8), BODY));
assertTrue(allows(webhook, SECRET, Map.of("webhook-signature", signature, "webhook-timestamp", timestamp,
"webhook-id", "msg_1")));
assertFalse(allows(webhook, SECRET, Map.of("webhook-signature", signature, "webhook-timestamp", timestamp,
"webhook-id", "msg_2")));
assertFalse(allows(webhook, SECRET, Map.of("webhook-signature", signature, "webhook-timestamp", timestamp)));
String dotted = "v1," + Base64.getEncoder().encodeToString(mac("HmacSHA256", key(SECRET),
("msg.1." + timestamp + ".").getBytes(StandardCharsets.UTF_8), BODY));
assertFalse(allows(webhook, SECRET, Map.of("webhook-signature", dotted, "webhook-timestamp", timestamp,
"webhook-id", "msg.1")));
}
// ──────────────────────────── Helpers ────────────────────────────
private static boolean allows(JsonNode webhook, String secret, Map<String, String> headers) {
return WebhookAuthenticator.allows(webhook, secret, headers, BODY, NOW);
}
private static Map<String, String> stripe(long seconds) {
return stripeText(Long.toString(seconds));
}
private static Map<String, String> stripeText(String timestamp) {
return Map.of("stripe-signature", "t=" + timestamp + ",v1=" + signTimestamped(timestamp));
}
private static String signTimestamped(String timestamp) {
return hex(mac("HmacSHA256", key(SECRET), (timestamp + ".").getBytes(StandardCharsets.UTF_8), BODY));
}
private static JsonNode webhook(String auth) {
return json("{\"RoleArn\":\"arn:aws:iam::000000000000:role/r\",\"AuthConfiguration\":" + auth + "}");
}
private static JsonNode hmac(String members) {
return webhook("{\"HmacAuthConfiguration\":{" + members + "}}");
}
private static JsonNode json(String text) {
try {
return MAPPER.readTree(text);
} catch (Exception e) {
throw new IllegalArgumentException(text, e);
}
}
private static byte[] key(String secret) {
return secret.getBytes(StandardCharsets.UTF_8);
}
private static String b64(String text) {
return Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));
}
private static String hex(byte[] bytes) {
return HexFormat.of().formatHex(bytes);
}
private static byte[] mac(String algorithm, byte[] key, byte[]... parts) {
try {
Mac mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(key, algorithm));
for (byte[] part : parts) {
mac.update(part);
}
return mac.doFinal();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,85 @@
package io.floci.aws.services.eventbridgev2;
import io.floci.aws.testing.ManualClock;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class WebhookDeduplicationTest {
private final ManualClock clock = new ManualClock(Instant.parse("2026-11-25T06:00:00Z"));
private final WebhookDeduplication deduplication = new WebhookDeduplication(clock);
@Test
void aRepeatInsideTheWindowIsNotFirstSeen() {
assertTrue(deduplication.firstSeen("source-a", "h1"));
clock.advance(Duration.ofMinutes(4).plusSeconds(59));
assertFalse(deduplication.firstSeen("source-a", "h1"));
}
@Test
void aRepeatAfterFiveMinutesIsFirstSeenAgain() {
assertTrue(deduplication.firstSeen("source-a", "h1"));
clock.advance(Duration.ofMinutes(5));
assertTrue(deduplication.firstSeen("source-a", "h1"));
assertFalse(deduplication.firstSeen("source-a", "h1"));
}
@Test
void theWindowRunsFromTheFirstRequestAndDoesNotSlide() {
assertTrue(deduplication.firstSeen("source-a", "h1"));
clock.advance(Duration.ofMinutes(3));
assertFalse(deduplication.firstSeen("source-a", "h1"));
clock.advance(Duration.ofMinutes(2));
assertTrue(deduplication.firstSeen("source-a", "h1"));
}
@Test
void anotherHashAndAnotherSourceAreFirstSeen() {
assertTrue(deduplication.firstSeen("source-a", "h1"));
assertTrue(deduplication.firstSeen("source-a", "h2"));
assertTrue(deduplication.firstSeen("source-b", "h1"));
}
@Test
void forgettingASourceAndClearingDropTheHashes() {
deduplication.firstSeen("source-a", "h1");
deduplication.firstSeen("source-b", "h1");
deduplication.forget("source-a");
assertTrue(deduplication.firstSeen("source-a", "h1"));
assertFalse(deduplication.firstSeen("source-b", "h1"));
deduplication.clear();
assertTrue(deduplication.firstSeen("source-b", "h1"));
}
@Test
void forgettingOneHashLeavesTheOthersOfTheSource() {
deduplication.firstSeen("source-a", "h1");
deduplication.firstSeen("source-a", "h2");
deduplication.forget("source-a", "h1");
deduplication.forget("source-never-seen", "h1");
assertTrue(deduplication.firstSeen("source-a", "h1"));
assertFalse(deduplication.firstSeen("source-a", "h2"));
}
@Test
void eachHashLeavesFiveMinutesAfterItWasFirstSeen() {
assertTrue(deduplication.firstSeen("source-a", "h1"));
clock.advance(Duration.ofMinutes(3));
assertTrue(deduplication.firstSeen("source-a", "h2"));
clock.advance(Duration.ofMinutes(2));
assertTrue(deduplication.firstSeen("source-a", "h1"));
assertFalse(deduplication.firstSeen("source-a", "h2"));
clock.advance(Duration.ofMinutes(3));
assertTrue(deduplication.firstSeen("source-a", "h2"));
assertFalse(deduplication.firstSeen("source-a", "h1"));
}
}
@@ -0,0 +1,264 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.eventbridgev2.model.SubscriberV2;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class WebhookEventsTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
// ──────────────────────────── Body ────────────────────────────
@ParameterizedTest
@ValueSource(strings = {
"{\"a\":1}", "[1,2,3]", "\"str\"", "12.50", "null", "true", " [1, 2 ,3] ", "{}", "[]", "0", "-0.0",
"{\"a\":{\"x\":1},\"b\":{\"x\":2}}", "{\"raw\":\"é😀\"}"})
void anyJsonValueIsAcceptedWithSurroundingWhitespace(String body) {
assertTrue(WebhookEvents.parseBody(body.getBytes(StandardCharsets.UTF_8)).isPresent(), body);
}
@ParameterizedTest
@ValueSource(strings = {
"", " ", "{\"a\":{\"x\":1,\"x\":2}}", "{\"x\":1,\"x\":2}", "[{\"x\":1,\"x\":2}]", "{\"a\":1}\n{\"b\":2}",
"{\"a\":1} trailing", "{\"a\":1}{\"b\":2}", "[1] [2]", "1 2", "{\"nan\":NaN}", "{'single':1}",
"{\"c\":1,/*x*/\"d\":2}", "{\"c\":1,//x\n\"d\":2}", "{\"a\":1,}", "[1,]", "01", "{\"a\":01}", "{\"a\":",
"{bad"})
void aBodyThatIsNotOneStrictJsonValueIsRefused(String body) {
assertTrue(WebhookEvents.parseBody(body.getBytes(StandardCharsets.UTF_8)).isEmpty(), body);
}
@Test
void aByteOrderMarkIsRefused() {
byte[] json = "{\"bom\":1}".getBytes(StandardCharsets.UTF_8);
byte[] withBom = new byte[json.length + 3];
withBom[0] = (byte) 0xEF;
withBom[1] = (byte) 0xBB;
withBom[2] = (byte) 0xBF;
System.arraycopy(json, 0, withBom, 3, json.length);
assertTrue(WebhookEvents.parseBody(json).isPresent());
assertTrue(WebhookEvents.parseBody(withBom).isEmpty());
}
@ParameterizedTest
@ValueSource(strings = {"UTF-16", "UTF-16LE", "UTF-16BE", "UTF-32", "UTF-32LE", "UTF-32BE", "ISO-8859-1"})
void aBodyInAnotherEncodingThanUtf8IsRefused(String charset) {
assertTrue(WebhookEvents.parseBody("{\"a\":\"é\"}".getBytes(Charset.forName(charset))).isEmpty());
}
@Test
void anOverlongUtf8SequenceIsRefused() {
assertTrue(WebhookEvents.parseBody(new byte[] {'"', (byte) 0xC0, (byte) 0x80, '"'}).isEmpty());
}
@Test
void numbersAreWrittenAsJacksonWritesDoubles() throws Exception {
String body = "{\"n\":1.0,\"e\":1e2,\"big\":12345678901234567890123,\"f\":0.1000,\"neg\":-0.0,\"exp\":1E-7,"
+ "\"twelve\":12.50}";
JsonNode data = WebhookEvents.parseBody(body.getBytes(StandardCharsets.UTF_8)).orElseThrow();
assertEquals("{\"n\":1.0,\"e\":100.0,\"big\":12345678901234567890123,\"f\":0.1,\"neg\":-0.0,"
+ "\"exp\":1.0E-7,\"twelve\":12.5}", data.toString());
}
@Test
void escapesAreDecodedAndTheOrderOfKeysIsKept() {
String body = "{ \"b\" : 1 ,\n \"a\" : [ 1 , 2 ] , \"u\":\"\\u00e9\\u3042\\ud83d\\ude00\", \"s\":\"\\/\","
+ "\"t\":\"\\u0041\\n\" }";
JsonNode data = WebhookEvents.parseBody(body.getBytes(StandardCharsets.UTF_8)).orElseThrow();
assertEquals("{\"b\":1,\"a\":[1,2],\"u\":\"éあ😀\",\"s\":\"/\",\"t\":\"A\\n\"}",
data.toString());
}
// ──────────────────────────── Metadata ────────────────────────────
@Test
void repeatedHeadersAreJoinedWithACommaAndASpaceAndTheNameIsLowerCased() {
List<Map.Entry<String, String>> headers = new ArrayList<>();
headers.add(Map.entry("X-Meta", "a"));
headers.add(Map.entry("x-meta", "b"));
headers.add(Map.entry("X-Other", " padded \t"));
Map<String, String> values = WebhookEvents.headerValues(headers);
assertEquals("a, b", values.get("x-meta"));
assertEquals("padded", values.get("x-other"));
}
@Test
void metadataHoldsTheListedHeadersUnderLowerCaseNames() throws Exception {
Map<String, String> headers = Map.of("x-b", "2", "x-a", "1", "x-unlisted", "3");
Map<String, String> metadata = WebhookEvents.metadata(MAPPER.readTree("[\"X-A\",\"X-B\",\"X-Missing\"]"),
headers);
assertEquals(Map.of("x-a", "1", "x-b", "2"), metadata);
}
@Test
void metadataIsInTheOrderOfAHashMapSizedForTheListAndNotInTheOrderOfTheList() throws Exception {
JsonNode three = MAPPER.readTree("[\"X-Event-Type\",\"User-Agent\",\"Content-Type\"]");
JsonNode four = MAPPER.readTree("[\"webhook-id\",\"X-Multi\",\"X-Empty\",\"X-Long\"]");
assertEquals(List.of("x-event-type", "content-type", "user-agent"), List.copyOf(WebhookEvents.metadata(three,
Map.of("user-agent", "probe/1.0", "content-type", "application/json", "x-event-type", "order.created"))
.keySet()));
assertEquals(List.of("x-multi", "webhook-id"), List.copyOf(WebhookEvents.metadata(four,
Map.of("webhook-id", "same", "x-multi", "v1")).keySet()));
assertEquals(List.of("x-multi", "webhook-id", "x-long"), List.copyOf(WebhookEvents.metadata(four,
Map.of("webhook-id", "msg_l", "x-multi", "padded", "x-long", "L".repeat(1024))).keySet()));
assertEquals(List.of("x-meta", "x-two"), List.copyOf(WebhookEvents.metadata(
MAPPER.readTree("[\"X-Meta\",\"X-Two\"]"), Map.of("x-two", "t", "x-meta", "m1")).keySet()));
}
@Test
void anEmptyValueIsDroppedAndAValueOver1024BytesIsDroppedButOneOf1024IsKept() throws Exception {
Map<String, String> headers = Map.of("x-empty", " ", "x-max", "a".repeat(1024), "x-over", "a".repeat(1025),
"x-wide", "é".repeat(513));
Map<String, String> metadata = WebhookEvents.metadata(
MAPPER.readTree("[\"x-empty\",\"x-max\",\"x-over\",\"x-wide\"]"), headers);
assertEquals(List.of("x-max"), List.copyOf(metadata.keySet()));
}
@Test
void aSourceThatListsNoHeadersCopiesNone() throws Exception {
assertTrue(WebhookEvents.metadata(MAPPER.readTree("[]"), Map.of("x-a", "1")).isEmpty());
assertTrue(WebhookEvents.metadata(MAPPER.missingNode(), Map.of("x-a", "1")).isEmpty());
}
// ──────────────────────────── The event ────────────────────────────
@Test
void systemMetadataHasExactlyTheMeasuredKeysInOrder() throws Exception {
PublishedEvent event = event("{\"k\":1}", Map.of("x-meta", "m"), "group-1",
Instant.parse("2026-11-25T05:59:02.982123456Z"), "10000000000000003");
assertEquals("{\"EventGroupId\":\"group-1\",\"DeduplicationId\":\"group-1\","
+ "\"ContentType\":\"application/json\",\"aws:IngestionTime\":\"2026-11-25T05:59:02.982Z\","
+ "\"aws:EventId\":\"event-1\",\"aws:SequenceNumber\":\"10000000000000003\","
+ "\"aws:DeliveryType\":\"LIVE\"}", event.systemMetadata().toString());
assertEquals("{\"x-meta\":\"m\"}", event.metadata().toString());
}
@Test
void theIngestionTimeAlwaysHasThreeFractionDigits() throws Exception {
assertEquals("2026-11-25T05:59:02.000Z", event("1", Map.of(), "g", Instant.parse("2026-11-25T05:59:02Z"), "1")
.systemMetadata().get("aws:IngestionTime").asText());
assertEquals("2026-11-25T05:59:02.500Z", event("1", Map.of(), "g", Instant.parse("2026-11-25T05:59:02.5Z"),
"1").systemMetadata().get("aws:IngestionTime").asText());
}
@Test
void aWithMetadataDeliveryIsTheThreePartsAndARawOneIsTheBodyAsSent() throws Exception {
String body = "{ \"e\" : 1e2,\n \"s\":\"\\/\" }";
PublishedEvent event = event(body, Map.of("x-meta", "m"), "g", Instant.parse("2026-11-25T05:59:02.982Z"), "7");
assertEquals("{\"Data\":{\"e\":100.0,\"s\":\"/\"},\"Metadata\":{\"x-meta\":\"m\"},\"SystemMetadata\":"
+ event.systemMetadata() + "}", EventBridgeV2Delivery.body(subscriber("WITH_METADATA"), event));
assertEquals(body, EventBridgeV2Delivery.body(subscriber("RAW"), event));
assertEquals(body, EventBridgeV2Delivery.body(subscriber(null), event));
}
@Test
void aRawDeliveryOfAPutEventsEventIsStillItsData() {
PublishedEvent event = new PublishedEvent(MAPPER.createObjectNode().put("a", 1),
MAPPER.createObjectNode(), MAPPER.createObjectNode());
assertEquals("{\"a\":1}", EventBridgeV2Delivery.body(subscriber("RAW"), event));
}
// ──────────────────────────── Deduplication hash ────────────────────────────
@Test
void theHashIsA64CharacterLowerCaseHexDigest() {
String hash = WebhookEvents.contentHash("{}".getBytes(StandardCharsets.UTF_8), Map.of());
assertTrue(hash.matches("[0-9a-f]{64}"), hash);
}
@Test
void theHashFollowsTheBodyBytesAndNotTheValueTheyHold() {
byte[] compact = "{\"dd\":1}".getBytes(StandardCharsets.UTF_8);
byte[] spaced = "{ \"dd\" : 1 }".getBytes(StandardCharsets.UTF_8);
assertEquals(WebhookEvents.contentHash(compact, Map.of()), WebhookEvents.contentHash(compact.clone(), Map.of()));
assertNotEquals(WebhookEvents.contentHash(compact, Map.of()), WebhookEvents.contentHash(spaced, Map.of()));
}
@Test
void theHashFollowsTheCopiedMetadata() {
byte[] body = "{\"dd\":2}".getBytes(StandardCharsets.UTF_8);
Map<String, String> one = Map.of("x-meta", "m1");
Map<String, String> two = new LinkedHashMap<>();
two.put("x-meta", "m1");
two.put("x-two", "t");
assertNotEquals(WebhookEvents.contentHash(body, Map.of()), WebhookEvents.contentHash(body, one));
assertNotEquals(WebhookEvents.contentHash(body, one), WebhookEvents.contentHash(body, two));
assertEquals(WebhookEvents.contentHash(body, two), WebhookEvents.contentHash(body, new LinkedHashMap<>(two)));
assertNotEquals(WebhookEvents.contentHash(body, Map.of("x-meta", "m2")), WebhookEvents.contentHash(body, one));
}
@Test
void theHashDoesNotFollowTheOrderTheHeadersAreCopiedIn() {
byte[] body = "{\"dd\":2}".getBytes(StandardCharsets.UTF_8);
Map<String, String> forward = new LinkedHashMap<>();
forward.put("c", "1");
forward.put("d", "2");
Map<String, String> backward = new LinkedHashMap<>();
backward.put("d", "2");
backward.put("c", "1");
assertEquals(WebhookEvents.contentHash(body, forward), WebhookEvents.contentHash(body, backward));
}
@Test
void theHashEncodingCannotBeConfusedByMovingBytesBetweenParts() {
byte[] body = "ab".getBytes(StandardCharsets.UTF_8);
assertNotEquals(WebhookEvents.contentHash("a".getBytes(StandardCharsets.UTF_8), Map.of("b", "c")),
WebhookEvents.contentHash(body, Map.of("", "c")));
assertNotEquals(WebhookEvents.contentHash(body, Map.of("a", "bc")),
WebhookEvents.contentHash(body, Map.of("ab", "c")));
assertFalse(WebhookEvents.contentHash(body, Map.of()).isEmpty());
}
// ──────────────────────────── Helpers ────────────────────────────
private static PublishedEvent event(String body, Map<String, String> metadata, String groupId, Instant ingested,
String sequenceNumber) {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
Optional<JsonNode> data = WebhookEvents.parseBody(bytes);
return WebhookEvents.event(data.orElseThrow(), bytes, metadata, groupId, ingested, "event-1", sequenceNumber);
}
private static SubscriberV2 subscriber(String transformerType) {
SubscriberV2 subscriber = new SubscriberV2();
if (transformerType != null) {
subscriber.setTransformer(MAPPER.createObjectNode().put("Type", transformerType));
}
return subscriber;
}
}
@@ -6,6 +6,7 @@ import java.security.SecureRandom;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class WebhookTokensTest {
@@ -22,4 +23,27 @@ class WebhookTokensTest {
assertTrue(token.matches("k1[A-Za-z0-9_-]{64}"), token);
assertEquals(48, Base64.getUrlDecoder().decode(token.substring(2)).length);
}
@Test
void aTokenIsValidOnlyForTheHostItWasBuiltFor() {
String host = WebhookTokens.newHostId(random);
String token = WebhookTokens.newToken(host, random);
assertTrue(WebhookTokens.isValid(host, token));
assertFalse(WebhookTokens.isValid(WebhookTokens.newHostId(random), token));
}
@Test
void aTokenThatWasChangedOrIsMalformedIsNotValid() {
String host = WebhookTokens.newHostId(random);
String token = WebhookTokens.newToken(host, random);
String altered = token.substring(0, 10) + (token.charAt(10) == 'A' ? 'B' : 'A') + token.substring(11);
assertFalse(WebhookTokens.isValid(host, altered));
assertFalse(WebhookTokens.isValid(host, token.substring(0, token.length() - 1)));
assertFalse(WebhookTokens.isValid(host, "k2" + token.substring(2)));
assertFalse(WebhookTokens.isValid(host, "k1" + "!".repeat(64)));
assertFalse(WebhookTokens.isValid(host, "k1" + "A".repeat(64)));
assertFalse(WebhookTokens.isValid(host, ""));
}
}
@@ -554,6 +554,8 @@ class S3VirtualHostFilterTest {
// Lambda function URLs
"url-id.lambda-url.us-east-1.localhost, localhost",
"url-id.lambda-url.localhost:4566, localhost",
// EventBridge webhook event source URLs
"ahostid.c01.events-webhook.us-east-1.localhost:4566, localhost",
// CloudFront distribution domains routed at the Floci endpoint
"e123.cloudfront.localhost, localhost",
})
@@ -658,6 +660,7 @@ class S3VirtualHostFilterTest {
@CsvSource({
"my.execute-api.archive.localhost, localhost",
"my.lambda-url.archive.localhost, localhost",
"my.events-webhook.archive.localhost, localhost",
"my.emr-serverless.archive.localhost, localhost",
"my.cloudfront.archive.localhost, localhost",
})