mirror of
https://github.com/floci-io/floci.git
synced 2026-12-03 18:18:02 -05:00
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:
1 parent
bc98bbbb23
commit
6a7428aabc
20 files changed
+2518
-17
No files matched your search
@@ -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
|
||||
|
||||
|
||||
Reference in new issue
Block a user