feat: public WhatsApp webhook with signature checks on both sides

mobile-api answers Meta's handshake only for the right verify token and
accepts events only with a valid X-Hub-Signature-256 under a company's
app secret, capped at 1 MB and rate limited per IP, on an exact
exemption. It forwards the exact bytes and signature; the WhatsApp
service re-verifies them itself, so the ingest trusts no caller. The
gateway exempts exactly POST /whatsapp/webhook/ingest from the user JWT,
and the log redactor masks the handshake's token and challenge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-02 11:03:56 +08:00
1 parent 846c22697e
commit a397de8c30
18 files changed
+759 -40

No files matched your search

@@ -63,8 +63,8 @@ class DtoJsonTest {
@Test
void webhookIngestRequestKeys() throws Exception {
WebhookIngestRequest r = new WebhookIngestRequest(List.of("INS"), mapper.readTree("{\"entry\":[]}"));
assertEquals(new TreeSet<>(List.of("matchedCompanyCodes", "payload")), keys(r));
WebhookIngestRequest r = new WebhookIngestRequest("e30=", "sha256=00");
assertEquals(new TreeSet<>(List.of("rawBody", "signature")), keys(r));
assertEquals(r, mapper.readValue(mapper.writeValueAsString(r), WebhookIngestRequest.class));
}
}
@@ -0,0 +1,314 @@
package com.solvway.mobile.api.whatsapp;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
import com.solvway.core.utils.JwtTokenUtil;
import com.solvway.core.utils.PubSubUtil;
import com.solvway.mobile.api.config.AuthAppKeyConfig;
import com.solvway.mobile.api.config.PubSubConfig;
import com.solvway.mobile.api.controller.PublicWhatsAppWebhookController;
import com.solvway.mobile.api.controller.publicapi.PublicRegistrationController;
import com.solvway.mobile.api.dto.whatsapp.WebhookIngestRequest;
import com.solvway.mobile.api.service.AuthenticationService;
import com.solvway.mobile.api.service.MemberService;
import com.solvway.mobile.api.service.PublicRegistrationService;
import com.solvway.mobile.api.service.UserService;
import com.solvway.mobile.api.useraccess.AppAccessAspect;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.slf4j.LoggerFactory;
import org.springframework.aop.aspectj.annotation.AspectJProxyFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.client.RestClientException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class WhatsAppWebhookTest {
private static final String INGEST = "http://gw/whatsapp/webhook/ingest";
private static final String BODY = "{\"entry\":[{\"changes\":[{\"value\":{\"messages\":[{\"text\":{\"body\":\"hello secret text\"}}]}}]}]}";
private RestTemplateCustomUtil rest;
private PublicRegistrationService limiter;
private MockEnvironment env;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
when(rest.getURLforApiService("/whatsapp/webhook/ingest")).thenReturn(INGEST);
limiter = mock(PublicRegistrationService.class);
env = new MockEnvironment().withProperty("WHATSAPP_COMPANIES", "INS, cv")
.withProperty("WHATSAPP_INS_APP_SECRET", "ins-secret").withProperty("WHATSAPP_CV_APP_SECRET", "cv-secret")
.withProperty("WHATSAPP_VERIFY_TOKEN", "verify-me");
}
private MockMvc mvc() {
return MockMvcBuilders.standaloneSetup(new PublicWhatsAppWebhookController(new WhatsAppWebhookService(env, rest, limiter))).build();
}
static String sign(String secret, byte[] body) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
return "sha256=" + HexFormat.of().formatHex(mac.doFinal(body));
}
/** The service gets the exact bytes (Base64) and Meta's header untouched; it re-verifies, so no codes are sent. */
private void assertForwarded(byte[] body, String signature) {
ArgumentCaptor<Object> sent = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(INGEST), eq(Void.class), sent.capture());
WebhookIngestRequest req = (WebhookIngestRequest) sent.getValue();
assertThat(Base64.getDecoder().decode(req.rawBody())).isEqualTo(body);
assertThat(req.signature()).isEqualTo(signature);
}
private void neverForwarded() {
verify(rest, never()).postForEntity(anyString(), any(Class.class), any());
}
// handshake
@Test
void handshakeRightTokenEchoesChallenge() throws Exception {
mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", "verify-me").param("hub.challenge", "12345"))
.andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)).andExpect(content().string("12345"));
}
@Test
void handshakeWrongTokenIs403WithoutChallenge() throws Exception {
mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", "nope").param("hub.challenge", "12345"))
.andExpect(status().isForbidden()).andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("12345"))));
}
@Test
void handshakeWrongModeIs403() throws Exception {
mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "unsubscribe").param("hub.verify_token", "verify-me").param("hub.challenge", "12345"))
.andExpect(status().isForbidden());
}
@Test
void handshakeBlankConfiguredTokenNeverMatches() throws Exception {
env.setProperty("WHATSAPP_VERIFY_TOKEN", " ");
mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", " ").param("hub.challenge", "12345"))
.andExpect(status().isForbidden());
mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.challenge", "12345"))
.andExpect(status().isForbidden());
}
@Test
void handshakeUnsetTokenNeverMatches() throws Exception {
env.getPropertySources().remove("test");
MockEnvironment bare = new MockEnvironment();
MockMvcBuilders.standaloneSetup(new PublicWhatsAppWebhookController(new WhatsAppWebhookService(bare, rest, limiter))).build()
.perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", "").param("hub.challenge", "12345"))
.andExpect(status().isForbidden());
}
// signature
@Test
void validInsSignatureForwardsWithInsOnly() throws Exception {
byte[] body = BODY.getBytes(StandardCharsets.UTF_8);
mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)
.header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isOk());
assertForwarded(body, sign("ins-secret", body));
}
@Test
void eventSignedWithCvSecretForwardsOnlyCv() throws Exception {
byte[] body = BODY.getBytes(StandardCharsets.UTF_8);
mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)
.header("X-Hub-Signature-256", sign("cv-secret", body))).andExpect(status().isOk());
assertForwarded(body, sign("cv-secret", body));
}
@Test
void sharedSecretMatchesEveryCompany() throws Exception {
env.setProperty("WHATSAPP_CV_APP_SECRET", "ins-secret");
byte[] body = BODY.getBytes(StandardCharsets.UTF_8);
mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)
.header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isOk());
assertForwarded(body, sign("ins-secret", body));
}
@Test
void missingOrGarbledSignatureIs401AndNothingForwarded() throws Exception {
byte[] body = BODY.getBytes(StandardCharsets.UTF_8);
String good = sign("ins-secret", body);
mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)).andExpect(status().isUnauthorized());
for (String bad : List.of("", "sha256=", "sha256=zz", good.substring("sha256=".length()), "sha1=" + good.substring(7),
good + "00", good.substring(0, good.length() - 2), "sha256=" + "0".repeat(64))) {
mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)
.header("X-Hub-Signature-256", bad)).andExpect(status().isUnauthorized());
}
neverForwarded();
}
@Test
void bodyAlteredAfterSigningIs401() throws Exception {
String sig = sign("ins-secret", BODY.getBytes(StandardCharsets.UTF_8));
mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON)
.content((BODY + " ").getBytes(StandardCharsets.UTF_8)).header("X-Hub-Signature-256", sig)).andExpect(status().isUnauthorized());
neverForwarded();
}
@Test
void companyWithoutSecretIsSkippedAndNeverMatches() throws Exception {
env.withProperty("WHATSAPP_COMPANIES", "INS,CV,XX");
byte[] body = BODY.getBytes(StandardCharsets.UTF_8);
mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)
.header("X-Hub-Signature-256", sign("x", body))).andExpect(status().isUnauthorized());
neverForwarded();
}
@Test
void declaredOversizeBodyIs413BeforeAnyHmac() throws Exception {
byte[] body = new byte[1024 * 1024 + 1];
mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)
.header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isPayloadTooLarge());
neverForwarded();
}
@Test
void streamExceedingTheCapWithoutContentLengthIs413AndReadsNoMoreThanCapPlusOne() throws Exception {
java.util.concurrent.atomic.AtomicLong read = new java.util.concurrent.atomic.AtomicLong();
jakarta.servlet.http.HttpServletRequest req = mock(jakarta.servlet.http.HttpServletRequest.class);
when(req.getContentLengthLong()).thenReturn(-1L);
when(req.getInputStream()).thenReturn(new jakarta.servlet.ServletInputStream() {
public int read() { read.incrementAndGet(); return 'a'; }
public int read(byte[] b, int off, int len) { read.addAndGet(len); return len; }
public boolean isFinished() { return false; }
public boolean isReady() { return true; }
public void setReadListener(jakarta.servlet.ReadListener l) { }
});
WhatsAppWebhookService service = new WhatsAppWebhookService(env, rest, limiter);
assertThat(org.assertj.core.api.Assertions.catchThrowable(() -> service.receive(req, "sha256=" + "0".repeat(64))))
.isInstanceOfSatisfying(org.springframework.web.server.ResponseStatusException.class,
e -> assertThat(e.getStatusCode().value()).isEqualTo(413));
assertThat(read.get()).isLessThanOrEqualTo(1024 * 1024 + 1 + 8192);
neverForwarded();
}
@Test
void bodyExactlyAtTheCapIsStillRead() throws Exception {
byte[] body = new byte[1024 * 1024];
mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)
.header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isBadRequest()); // signed, not JSON
}
@Test
void companyWithoutSecretWarnsOnlyOnce() throws Exception {
env.withProperty("WHATSAPP_COMPANIES", "INS,XX");
ListAppender<ILoggingEvent> logs = new ListAppender<>();
logs.start();
Logger logger = (Logger) LoggerFactory.getLogger(WhatsAppWebhookService.class);
logger.addAppender(logs);
try {
MockMvc mvc = mvc();
byte[] body = BODY.getBytes(StandardCharsets.UTF_8);
for (int i = 0; i < 3; i++) {
mvc.perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)
.header("X-Hub-Signature-256", sign("x", body)));
}
assertThat(logs.list.stream().filter(e -> e.getFormattedMessage().contains("XX skipped"))).hasSize(1);
} finally {
logger.detachAppender(logs);
}
}
@Test
void signedButMalformedJsonIs400() throws Exception {
byte[] body = "{not json".getBytes(StandardCharsets.UTF_8);
mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)
.header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isBadRequest());
neverForwarded();
}
@Test
void forwardFailureStillAnswers200AndLogsNoContent() throws Exception {
ListAppender<ILoggingEvent> logs = new ListAppender<>();
logs.start();
Logger logger = (Logger) LoggerFactory.getLogger(WhatsAppWebhookService.class);
logger.addAppender(logs);
try {
when(rest.postForEntity(eq(INGEST), eq(Void.class), any())).thenThrow(new RestClientException("boom hello secret text"));
byte[] body = BODY.getBytes(StandardCharsets.UTF_8);
String sig = sign("ins-secret", body);
mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)
.header("X-Hub-Signature-256", sig)).andExpect(status().isOk());
assertThat(logs.list).isNotEmpty();
for (ILoggingEvent e : logs.list) {
assertThat(e.getFormattedMessage()).doesNotContain("hello").doesNotContain("secret").doesNotContain(sig).doesNotContain("verify-me");
assertThat(e.getThrowableProxy()).isNull();
}
} finally {
logger.detachAppender(logs);
}
}
@Test
void rateLimitedByIp() throws Exception {
mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", "verify-me").param("hub.challenge", "1"))
.andExpect(status().isOk());
verify(limiter).limit(org.mockito.ArgumentMatchers.startsWith("wa:webhook:"), anyInt(), anyString());
}
// public access through the real AppAccessAspect: no api-key, no JWT
private <T> T guarded(T controller) {
AuthAppKeyConfig keys = new AuthAppKeyConfig();
keys.setList(List.of("a-key:APP"));
AppAccessAspect aspect = new AppAccessAspect(mock(MemberService.class), mock(UserService.class), mock(PubSubConfig.class),
mock(PubSubTemplate.class), mock(PubSubUtil.class), keys, mock(AuthenticationService.class), mock(JwtTokenUtil.class), null, null);
AspectJProxyFactory factory = new AspectJProxyFactory(controller);
factory.setProxyTargetClass(true);
factory.addAspect(aspect);
return factory.getProxy();
}
@Test
void webhookIsReachableWithoutApiKeyOrJwt() throws Exception {
MockMvc guarded = MockMvcBuilders.standaloneSetup(guarded(new PublicWhatsAppWebhookController(new WhatsAppWebhookService(env, rest, limiter)))).build();
guarded.perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", "verify-me").param("hub.challenge", "77"))
.andExpect(status().isOk()).andExpect(content().string("77"));
byte[] body = BODY.getBytes(StandardCharsets.UTF_8);
guarded.perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)
.header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isOk());
}
@Test
void neighbouringPublicRouteStillNeedsAnApiKey() throws Exception {
MockMvc guarded = MockMvcBuilders.standaloneSetup(guarded(new PublicRegistrationController(mock(PublicRegistrationService.class)))).build();
guarded.perform(get("/api/public/registration/abc")).andExpect(status().isUnauthorized());
}
private static int anyInt() {
return org.mockito.ArgumentMatchers.anyInt();
}
}