feat(notification): implement the notification delivery platform

Maps the 31-module plan onto the registry's 19 leaves as packages; the two
edges the registry forbids (provider->httpclient, inbox->messaging) are
replaced by application-owned ports. See docs/notification/module-mapping.md.

Acceptance is not delivery: ProviderSubmissionResult refuses to carry a
delivery outcome, and AMBIGUOUS is a first-class terminal state that blocks
automatic retry and fallback until reconciliation resolves it.

Providers: SES (SigV4 + SNS callback), Twilio (X-Twilio-Signature +
reconciliation), FCM (FID-primary batch), APNs, Web Push (RFC 8030/8291/8292),
SMTP and webhook. Contact points are AES-256-GCM encrypted with a separate
HMAC lookup fingerprint; nothing raw reaches a log, metric tag or exception.

Dispatch commits the attempt row, calls the provider with no transaction open,
then records the outcome; the durable queue uses FOR UPDATE SKIP LOCKED.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-08-14 13:57:27 +09:00
co-authored by Claude Opus 5
parent 3b5aee50e3
commit 701ba67456
511 changed files with 30537 additions and 23 deletions
@@ -0,0 +1,38 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
/**
* Security chain for the provider callback endpoints.
*
* <p>Callbacks authenticate with a provider signature, not with a user session, so they get their
* own chain: CSRF and session creation are off, and the ordinary user chain never sees them.
* Putting them on the user chain would either break every provider or force the user chain to be
* permissive.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(
prefix = "ca-skeleton.notification.platform.callbacks",
name = "enabled",
havingValue = "true")
public class CallbackMvcSecurityConfiguration {
/** Dedicated, ordered-first chain for the callback path. */
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
public SecurityFilterChain notificationCallbackFilterChain(HttpSecurity http) throws Exception {
return http.securityMatcher("/internal/notification/callbacks/**")
.csrf(csrf -> csrf.disable())
.sessionManagement(
session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(requests -> requests.anyRequest().permitAll())
.build();
}
}
@@ -0,0 +1,75 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback;
import dev.caskeleton.application.notification.platform.api.ProviderId;
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
import dev.caskeleton.application.notification.platform.callback.CallbackRequest;
import jakarta.servlet.http.HttpServletRequest;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/**
* Builds the transport-neutral callback request.
*
* <p>Both the servlet and reactive endpoints use this, so signature verification sees exactly the
* same canonical bytes and URL regardless of which stack received the call.
*/
public final class CallbackRequestFactory {
private final ExternalRequestUrlResolver urlResolver;
private final Clock clock;
public CallbackRequestFactory(ExternalRequestUrlResolver urlResolver, Clock clock) {
this.urlResolver = Objects.requireNonNull(urlResolver, "urlResolver");
this.clock = Objects.requireNonNull(clock, "clock");
}
/** Build from a servlet request plus the already-read raw body. */
public CallbackRequest create(
String provider, String profile, HttpServletRequest request, byte[] body) {
Objects.requireNonNull(provider, "provider");
Objects.requireNonNull(profile, "profile");
Objects.requireNonNull(request, "request");
Objects.requireNonNull(body, "body");
Map<String, List<String>> headers = new LinkedHashMap<>();
for (String name : Collections.list(request.getHeaderNames())) {
headers.put(name, new ArrayList<>(Collections.list(request.getHeaders(name))));
}
return new CallbackRequest(
new ProviderId(provider),
new ProviderProfileId(profile),
urlResolver.resolve(request),
request.getMethod(),
Optional.ofNullable(request.getContentType()),
headers,
body,
clock.instant());
}
/** Build from an already-resolved external URL, used by the reactive endpoint. */
public CallbackRequest create(
String provider,
String profile,
String externalUrl,
String method,
Optional<String> contentType,
Map<String, List<String>> headers,
byte[] body) {
return new CallbackRequest(
new ProviderId(provider),
new ProviderProfileId(profile),
externalUrl,
method,
contentType,
headers,
body,
clock.instant());
}
}
@@ -0,0 +1,71 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
/**
* Reconstructs the URL the provider actually called.
*
* <p>Several providers sign the request URL, so getting this wrong turns every valid webhook into a
* signature failure. Forwarded headers are only honoured when the immediate peer is a configured
* trusted proxy: trusting them unconditionally would let any caller choose the URL that gets
* verified, which defeats the signature entirely.
*/
public final class ExternalRequestUrlResolver {
private final Set<String> trustedProxies;
public ExternalRequestUrlResolver(Set<String> trustedProxies) {
this.trustedProxies = Set.copyOf(Objects.requireNonNull(trustedProxies, "trustedProxies"));
}
/** External URL of a request. */
public String resolve(HttpServletRequest request) {
Objects.requireNonNull(request, "request");
String scheme = request.getScheme();
String host = request.getServerName();
int port = request.getServerPort();
if (trustedProxies.contains(request.getRemoteAddr())) {
String forwarded = request.getHeader("Forwarded");
if (forwarded != null) {
for (String element : forwarded.split(";", -1)) {
String trimmed = element.trim().toLowerCase(Locale.ROOT);
if (trimmed.startsWith("proto=")) {
scheme = trimmed.substring("proto=".length());
} else if (trimmed.startsWith("host=")) {
host = element.trim().substring("host=".length());
port = -1;
}
}
} else {
String protoHeader = request.getHeader("X-Forwarded-Proto");
String hostHeader = request.getHeader("X-Forwarded-Host");
if (protoHeader != null) {
scheme = protoHeader;
}
if (hostHeader != null) {
host = hostHeader;
port = -1;
}
}
}
StringBuilder url = new StringBuilder(scheme).append("://").append(host);
boolean defaultPort =
port < 0
|| ("https".equalsIgnoreCase(scheme) && port == 443)
|| ("http".equalsIgnoreCase(scheme) && port == 80);
if (!defaultPort) {
url.append(':').append(port);
}
url.append(request.getRequestURI());
String query = request.getQueryString();
if (query != null && !query.isBlank()) {
url.append('?').append(query);
}
return url.toString();
}
}
@@ -0,0 +1,75 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback;
import dev.caskeleton.application.notification.platform.api.error.CallbackValidationException;
import dev.caskeleton.application.notification.platform.callback.ProviderCallbackIngestionService;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Objects;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Servlet callback endpoint.
*
* <p>The body arrives as raw bytes, never as a parsed form. Providers sign the exact octets, and
* letting the container parse and re-encode them is the most common cause of a valid webhook
* failing verification.
*
* <p>The response is a bare {@code 204}: no body, no diagnostics. A provider only needs to know the
* event is recorded, and an error body would be a channel for leaking what the platform knows.
*
* <p>Registered only in a servlet application and only when callbacks are enabled. An annotated
* controller is also honoured by WebFlux, so without the servlet condition a reactive deployment
* would map both this and the functional router onto the same path — and a provider signature would
* then be verified twice against two different canonical URLs.
*/
@RestController
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnProperty(
prefix = "ca-skeleton.notification.platform.callbacks",
name = "enabled",
havingValue = "true")
@RequestMapping("/internal/notification/callbacks")
public final class NotificationCallbackMvcController {
/** Hard body ceiling applied before any provider adapter is consulted. */
public static final int MAX_BODY_BYTES = 65_536;
private final ProviderCallbackIngestionService ingestion;
private final CallbackRequestFactory requestFactory;
public NotificationCallbackMvcController(
ProviderCallbackIngestionService ingestion, CallbackRequestFactory requestFactory) {
this.ingestion = Objects.requireNonNull(ingestion, "ingestion");
this.requestFactory = Objects.requireNonNull(requestFactory, "requestFactory");
}
/** Receive one provider callback. */
@PostMapping(path = "/{provider}/{profile}")
public ResponseEntity<Void> callback(
@PathVariable String provider,
@PathVariable String profile,
HttpServletRequest request,
@RequestBody byte[] body) {
if (body.length > MAX_BODY_BYTES) {
return ResponseEntity.status(HttpStatus.CONTENT_TOO_LARGE).build();
}
// A duplicate answers 204 exactly like a first delivery. The provider did its job either way,
// and any other status would make it retry an event that is already recorded.
ingestion.ingest(requestFactory.create(provider, profile, request, body));
return ResponseEntity.noContent().build();
}
/** A rejected callback never reveals why beyond the status code. */
@ExceptionHandler(CallbackValidationException.class)
public ResponseEntity<Void> onValidationFailure(CallbackValidationException failure) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
}
@@ -0,0 +1,48 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback.reactive;
import java.util.Objects;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.web.reactive.function.server.ServerRequest;
import reactor.core.publisher.Mono;
/**
* Reads the raw body with a hard ceiling and no buffer leaks.
*
* <p>Every {@link DataBuffer} is released on success, on error and on cancellation. A reactive
* endpoint that forgets the cancellation path leaks native memory exactly when it is under the load
* that caused the cancellation.
*/
public final class BoundedCallbackBodyReader {
private final int maxBytes;
public BoundedCallbackBodyReader(int maxBytes) {
if (maxBytes < 1) {
throw new IllegalArgumentException("maxBytes");
}
this.maxBytes = maxBytes;
}
/** Read at most the configured number of bytes. */
public Mono<byte[]> read(ServerRequest request) {
Objects.requireNonNull(request, "request");
return DataBufferUtils.join(request.bodyToFlux(DataBuffer.class), maxBytes)
.map(
buffer -> {
try {
byte[] bytes = new byte[buffer.readableByteCount()];
buffer.read(bytes);
return bytes;
} finally {
DataBufferUtils.release(buffer);
}
})
.defaultIfEmpty(new byte[0]);
}
/** Configured ceiling. */
public int maxBytes() {
return maxBytes;
}
}
@@ -0,0 +1,58 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback.reactive;
import dev.caskeleton.adapter.inbound.web.notification.platform.callback.CallbackRequestFactory;
import dev.caskeleton.application.notification.platform.callback.ProviderCallbackIngestionService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
/**
* Registers the reactive callback transport, and only it.
*
* <p>This configuration is {@code REACTIVE}-only and the servlet controller carries the matching
* {@code SERVLET} condition, so exactly one of the two is ever registered — by construction rather
* than by convention. Both on the same path would mean a provider signature is verified twice
* against two different canonical URLs, a failure that shows up only in production and only for
* signed providers, and reads like a credential problem.
*
* <p>The body ceiling is read as a property rather than through the platform settings type: that
* type belongs to the outbound notification adapter, which this inbound adapter must not depend on.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnProperty(
prefix = "ca-skeleton.notification.platform.callbacks",
name = "enabled",
havingValue = "true")
public class CallbackWebFluxConfiguration {
/** Bounded body reader; the ceiling applies before any provider adapter is consulted. */
@Bean
@ConditionalOnMissingBean
public BoundedCallbackBodyReader notificationCallbackBodyReader(
@Value("${ca-skeleton.notification.platform.callbacks.max-body-bytes:65536}") int maxBytes) {
return new BoundedCallbackBodyReader(maxBytes);
}
/** Reactive handler. */
@Bean
@ConditionalOnMissingBean
public NotificationCallbackWebFluxHandler notificationCallbackWebFluxHandler(
ProviderCallbackIngestionService ingestion,
CallbackRequestFactory requestFactory,
BoundedCallbackBodyReader bodyReader) {
return new NotificationCallbackWebFluxHandler(ingestion, requestFactory, bodyReader);
}
/** Functional route for the callback path. */
@Bean
public RouterFunction<ServerResponse> notificationCallbackRoutes(
NotificationCallbackWebFluxHandler handler) {
return new CallbackWebFluxRouter(handler).routes();
}
}
@@ -0,0 +1,30 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback.reactive;
import java.util.Objects;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
/**
* Routes the reactive callback path.
*
* <p>Kept separate from the servlet controller so that only one of the two is ever registered; two
* endpoints on the same path would mean a provider's signature is verified twice against two
* different canonical URLs.
*/
public final class CallbackWebFluxRouter {
private final NotificationCallbackWebFluxHandler handler;
public CallbackWebFluxRouter(NotificationCallbackWebFluxHandler handler) {
this.handler = Objects.requireNonNull(handler, "handler");
}
/** Router function for the callback path. */
public RouterFunction<ServerResponse> routes() {
return RouterFunctions.route(
RequestPredicates.POST("/internal/notification/callbacks/{provider}/{profile}"),
handler::handle);
}
}
@@ -0,0 +1,85 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback.reactive;
import dev.caskeleton.adapter.inbound.web.notification.platform.callback.CallbackRequestFactory;
import dev.caskeleton.application.notification.platform.api.error.CallbackValidationException;
import dev.caskeleton.application.notification.platform.callback.ProviderCallbackIngestionService;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.springframework.core.io.buffer.DataBufferLimitException;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
/**
* Reactive callback endpoint.
*
* <p>Ingestion is blocking — it writes to the database — so it runs on {@code boundedElastic} and
* never on the event loop. Running it inline would stall every other connection the loop is
* serving.
*
* <p>It shares the canonicalisation and the ingestion service with the servlet endpoint, so a
* deployment can switch web stacks without changing what a provider signature is checked against.
*/
public final class NotificationCallbackWebFluxHandler {
private final ProviderCallbackIngestionService ingestion;
private final CallbackRequestFactory requestFactory;
private final BoundedCallbackBodyReader bodyReader;
public NotificationCallbackWebFluxHandler(
ProviderCallbackIngestionService ingestion,
CallbackRequestFactory requestFactory,
BoundedCallbackBodyReader bodyReader) {
this.ingestion = Objects.requireNonNull(ingestion, "ingestion");
this.requestFactory = Objects.requireNonNull(requestFactory, "requestFactory");
this.bodyReader = Objects.requireNonNull(bodyReader, "bodyReader");
}
/** Handle one callback. */
public Mono<ServerResponse> handle(ServerRequest request) {
String provider = request.pathVariable("provider");
String profile = request.pathVariable("profile");
return bodyReader
.read(request)
.flatMap(
body ->
Mono.fromCallable(
() ->
ingestion.ingest(
requestFactory.create(
provider,
profile,
request.uri().toString(),
request.method().name(),
request.headers().contentType().map(Object::toString),
headers(request),
body)))
.subscribeOn(Schedulers.boundedElastic()))
.then(ServerResponse.noContent().build())
.onErrorResume(
DataBufferLimitException.class,
failure -> ServerResponse.status(HttpStatus.CONTENT_TOO_LARGE).build())
.onErrorResume(
CallbackValidationException.class,
failure -> ServerResponse.status(HttpStatus.BAD_REQUEST).build());
}
private static Map<String, List<String>> headers(ServerRequest request) {
Map<String, List<String>> headers = new java.util.LinkedHashMap<>();
request
.headers()
.asHttpHeaders()
.forEach((name, values) -> headers.put(name, List.copyOf(values)));
return Map.copyOf(headers);
}
/** Content type of a request, if declared. */
public static Optional<String> contentType(ServerRequest request) {
return request.headers().contentType().map(Object::toString);
}
}
@@ -0,0 +1,396 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import dev.caskeleton.application.notification.platform.api.ProviderId;
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
import dev.caskeleton.application.notification.platform.api.error.CallbackValidationException;
import dev.caskeleton.application.notification.platform.api.error.FailureCategory;
import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode;
import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor;
import dev.caskeleton.application.notification.platform.callback.AppendEventResult;
import dev.caskeleton.application.notification.platform.callback.CallbackLimits;
import dev.caskeleton.application.notification.platform.callback.CallbackRequest;
import dev.caskeleton.application.notification.platform.callback.CallbackVerificationResult;
import dev.caskeleton.application.notification.platform.callback.NormalizedProviderEvent;
import dev.caskeleton.application.notification.platform.callback.ProjectionResult;
import dev.caskeleton.application.notification.platform.callback.ProviderCallbackAdapter;
import dev.caskeleton.application.notification.platform.callback.ProviderCallbackAdapterRegistry;
import dev.caskeleton.application.notification.platform.callback.ProviderCallbackIngestionService;
import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger;
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService;
import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord;
import dev.caskeleton.application.notification.platform.callback.ProviderEventRecordId;
import dev.caskeleton.application.notification.platform.callback.VerifiedCallback;
import dev.caskeleton.application.notification.platform.callback.VerifiedProviderEvent;
import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort;
import dev.caskeleton.application.notification.platform.observation.NotificationSecurityAuditPort;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
/**
* What the servlet transport is responsible for handing the callback pipeline.
*
* <p>The pipeline itself belongs to application-core and is tested there. What is only testable
* here is the translation: the exact received octets, the externally-visible URL, and headers that
* survive the servlet container's own casing. Each is a common cause of a valid webhook failing
* verification, and none is visible from a unit test of the provider adapter.
*
* <p>The capture point is the provider adapter's {@code verify}, which is the first thing in the
* pipeline to see the whole request. It rejects, so the test never needs a ledger.
*/
class NotificationCallbackMvcControllerTest {
private static final Clock CLOCK =
Clock.fixed(Instant.parse("2026-08-14T00:00:00Z"), ZoneOffset.UTC);
private static final String TRUSTED_PROXY = "10.0.0.1";
private final List<CallbackRequest> verified = new ArrayList<>();
private final List<String> rejections = new ArrayList<>();
private final NotificationCallbackMvcController controller =
new NotificationCallbackMvcController(
new ProviderCallbackIngestionService(
new CapturingRegistry(),
new UnusedLedger(),
// Never reached: verification always fails in this fixture, and the pipeline appends
// only after a valid signature.
new ProviderEventProjectionService(
new UnusedLedger(),
providerId -> java.util.Optional.empty(),
new UnusedAttemptResolver(),
new UnusedProjectionStore(),
(attempt, facts) -> {
throw new UnsupportedOperationException();
},
new UnusedTransactions(),
new DiscardingMetrics()),
new UnusedPayloadProtection(),
new RecordingSecurityAudit(),
new DiscardingMetrics(),
CLOCK),
new CallbackRequestFactory(new ExternalRequestUrlResolver(Set.of(TRUSTED_PROXY)), CLOCK));
@Test
void theExactReceivedOctetsReachTheAdapterUnparsed() {
byte[] body =
"MessageSid=SM1&MessageStatus=delivered&Signed=a+b%2Fc".getBytes(StandardCharsets.UTF_8);
assertThatThrownBy(
() ->
controller.callback(
"twilio", "twilio-primary", request("application/x-www-form-urlencoded"), body))
.isInstanceOf(CallbackValidationException.class);
// Byte for byte, including the percent-encoding a form parse would have consumed and re-encoded
// differently — which is the single most common cause of a valid webhook failing its signature.
assertThat(verified).hasSize(1);
assertThat(verified.get(0).body()).isEqualTo(body);
assertThat(verified.get(0).contentType()).contains("application/x-www-form-urlencoded");
assertThat(verified.get(0).httpMethod()).isEqualTo("POST");
}
@Test
void aForwardedHostFromAnUntrustedPeerIsIgnored() {
var request = request("application/json");
request.setRemoteAddr("203.0.113.9");
request.addHeader("X-Forwarded-Proto", "https");
request.addHeader("X-Forwarded-Host", "attacker.example.com");
assertThatThrownBy(
() ->
controller.callback(
"twilio", "twilio-primary", request, "{}".getBytes(StandardCharsets.UTF_8)))
.isInstanceOf(CallbackValidationException.class);
// Honouring the header unconditionally would let any caller choose the URL that gets verified,
// which defeats the signature entirely.
assertThat(verified.get(0).externalUrl()).doesNotContain("attacker.example.com");
}
@Test
void aForwardedHostFromATrustedProxyBecomesTheCanonicalUrl() {
var request = request("application/json");
request.setRemoteAddr(TRUSTED_PROXY);
request.addHeader("X-Forwarded-Proto", "https");
request.addHeader("X-Forwarded-Host", "callback.example.com");
assertThatThrownBy(
() ->
controller.callback(
"twilio", "twilio-primary", request, "{}".getBytes(StandardCharsets.UTF_8)))
.isInstanceOf(CallbackValidationException.class);
assertThat(verified.get(0).externalUrl())
.isEqualTo(
"https://callback.example.com/internal/notification/callbacks/twilio/twilio-primary");
}
@Test
void headersSurviveTheContainersCasingAndStayAddressableEitherWay() {
var request = request("application/json");
request.addHeader("X-Twilio-Signature", "abc123");
assertThatThrownBy(
() ->
controller.callback(
"twilio", "twilio-primary", request, "{}".getBytes(StandardCharsets.UTF_8)))
.isInstanceOf(CallbackValidationException.class);
assertThat(verified.get(0).header("x-twilio-signature")).contains("abc123");
assertThat(verified.get(0).header("X-TWILIO-SIGNATURE")).contains("abc123");
}
@Test
void aBodyOverTheTransportCeilingIsRefusedBeforeAnyAdapterIsConsulted() {
byte[] oversized = new byte[NotificationCallbackMvcController.MAX_BODY_BYTES + 1];
var response =
controller.callback("twilio", "twilio-primary", request("application/json"), oversized);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CONTENT_TOO_LARGE);
// Nothing downstream sees it, so no signature check ever runs over an attacker-sized payload.
assertThat(verified).isEmpty();
}
@Test
void aRejectedCallbackRevealsNothingBeyondTheStatusCode() {
var response =
controller.onValidationFailure(
new CallbackValidationException(
NotificationFailureDescriptor.preDispatch(
NotificationFailureCode.CALLBACK_SIGNATURE_INVALID,
FailureCategory.CALLBACK_VALIDATION_FAILURE)));
// The endpoint is unauthenticated by design — the signature is the authentication — so an error
// body is a free oracle for whoever is probing it.
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(response.getBody()).isNull();
}
@Test
void aRejectedSignatureIsRecordedAsASecurityEventRatherThanADeliveryEvent() {
assertThatThrownBy(
() ->
controller.callback(
"twilio",
"twilio-primary",
request("application/json"),
"{}".getBytes(StandardCharsets.UTF_8)))
.isInstanceOf(CallbackValidationException.class);
// Writing it to the ledger would let anyone who can reach the endpoint fill a recipient's
// delivery history with noise.
assertThat(rejections).containsExactly("SIGNATURE_MISMATCH");
}
private static MockHttpServletRequest request(String contentType) {
var request =
new MockHttpServletRequest(
"POST", "/internal/notification/callbacks/twilio/twilio-primary");
request.setContentType(contentType);
return request;
}
/** Registry whose adapter records the request and then refuses it. */
private final class CapturingRegistry implements ProviderCallbackAdapterRegistry {
@Override
public ProviderCallbackAdapter require(ProviderProfileId profileId) {
return new ProviderCallbackAdapter() {
@Override
public ProviderId providerId() {
return new ProviderId("twilio");
}
@Override
public CallbackVerificationResult verify(CallbackRequest request) {
verified.add(request);
return CallbackVerificationResult.invalid("SIGNATURE_MISMATCH");
}
@Override
public List<NormalizedProviderEvent> normalize(VerifiedCallback callback) {
throw new UnsupportedOperationException("verification always fails in this fixture");
}
};
}
@Override
public CallbackLimits limitsFor(ProviderProfileId profileId) {
return new CallbackLimits(
65_536L, Set.of("application/json", "application/x-www-form-urlencoded"));
}
}
/** Security audit that keeps the rejection reason. */
private final class RecordingSecurityAudit implements NotificationSecurityAuditPort {
@Override
public void callbackSignatureRejected(ProviderProfileId profileId, String reasonCode) {
rejections.add(reasonCode);
}
@Override
public void callbackRejectedByLimit(ProviderProfileId profileId, String reasonCode) {
rejections.add(reasonCode);
}
}
/** Metrics are exercised elsewhere; discarding them keeps this test about the transport. */
private static final class DiscardingMetrics implements NotificationMetricsPort {
@Override
public void increment(String metricName, Map<String, String> tags) {
// Intentionally empty.
}
@Override
public void record(String metricName, Map<String, String> tags, Duration value) {
// Intentionally empty.
}
@Override
public void gauge(String metricName, Map<String, String> tags, double value) {
// Intentionally empty.
}
}
/** Never reached: attempt correlation happens only for an accepted callback. */
private static final class UnusedAttemptResolver
implements dev.caskeleton.application.notification.platform.callback
.DeliveryAttemptResolverPort {
@Override
public java.util.Optional<
dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot>
byAttemptId(DeliveryAttemptId attemptId) {
return java.util.Optional.empty();
}
@Override
public java.util.Optional<
dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot>
byProviderRequestId(ProviderProfileId profileId, String providerRequestIdHash) {
return java.util.Optional.empty();
}
}
/** Never reached: projection runs only after a signature has been accepted. */
private static final class UnusedProjectionStore
implements dev.caskeleton.application.notification.platform.callback
.DeliveryProjectionStorePort {
@Override
public dev.caskeleton.application.notification.platform.callback.DeliveryProjection load(
DeliveryAttemptId attemptId) {
throw new UnsupportedOperationException();
}
@Override
public void save(
DeliveryAttemptId attemptId,
dev.caskeleton.application.notification.platform.callback.DeliveryProjection projection) {
throw new UnsupportedOperationException();
}
}
/** Never reached: nothing in this fixture gets as far as a transaction. */
private static final class UnusedTransactions
implements dev.caskeleton.application.transaction.TransactionPort {
@Override
public <T> T inWrite(java.util.function.Supplier<T> action) {
throw new UnsupportedOperationException();
}
@Override
public <T> T inRootWrite(java.util.function.Supplier<T> action) {
throw new UnsupportedOperationException();
}
@Override
public <T> T inRead(java.util.function.Supplier<T> action) {
throw new UnsupportedOperationException();
}
@Override
public <T> T inNew(java.util.function.Supplier<T> action) {
throw new UnsupportedOperationException();
}
}
/** Never reached: every request in this fixture is rejected before the payload is retained. */
private static final class UnusedPayloadProtection
implements dev.caskeleton.application.notification.platform.callback
.CallbackPayloadProtectionPort {
@Override
public byte[] protectRawPayload(byte[] rawBody) {
throw new UnsupportedOperationException();
}
@Override
public String digest(byte[] rawBody) {
throw new UnsupportedOperationException();
}
@Override
public String fingerprint(
ProviderProfileId profileId, NormalizedProviderEvent event, String rawPayloadDigest) {
throw new UnsupportedOperationException();
}
}
/** Never reached: every request in this fixture is rejected before the append. */
private static final class UnusedLedger implements ProviderEventLedger {
@Override
public AppendEventResult append(VerifiedProviderEvent event) {
throw new UnsupportedOperationException();
}
@Override
public AppendEventResult appendAll(List<VerifiedProviderEvent> events) {
throw new UnsupportedOperationException();
}
@Override
public List<ProviderEventRecord> pendingProjection(int limit) {
throw new UnsupportedOperationException();
}
@Override
public void markApplied(ProviderEventRecordId eventId, ProjectionResult result) {
throw new UnsupportedOperationException();
}
@Override
public void markFailed(ProviderEventRecordId eventId, String errorCode) {
throw new UnsupportedOperationException();
}
@Override
public List<ProviderEventRecord> unmatched(int limit) {
throw new UnsupportedOperationException();
}
@Override
public List<ProviderEventRecord> eventsForAttempt(DeliveryAttemptId attemptId) {
throw new UnsupportedOperationException();
}
}
}