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

@@ -1,6 +1,10 @@
package com.solvway.mobile.api.constant.api;
/**
* Webhook ingest: POST /whatsapp/webhook/ingest carries WebhookIngestRequest {"rawBody": Base64 of the exact bytes Meta
* sent, "signature": the X-Hub-Signature-256 header as received}. The service re-verifies the HMAC under every
* configured company app secret (the companies that verify are the matched ones) and answers 401 ProblemDetail detail
* INVALID_SIGNATURE when none does; it never trusts the caller.
* Caller context and access (the SERVICE enforces it; mobile-api only supplies trusted values):
* - per-conversation calls (thread, send, read, media, assign, start) and the list carry query params
* companyId (null ONLY for a super admin = all companies), userId (the acting staff user) and
@@ -0,0 +1,41 @@
package com.solvway.mobile.api.controller;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.whatsapp.WhatsAppWebhookService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import java.io.IOException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/** Meta calls this with no api-key and no sign-in; AppAccessAspect exempts exactly this route (see isWhatsAppWebhook). */
@RestController
@RequestMapping("/api/public/whatsapp/webhook")
@RequiredArgsConstructor
public class PublicWhatsAppWebhookController {
private final WhatsAppWebhookService webhook;
@AppAuth(skipValidate = true)
@GetMapping(produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> verify(@RequestParam(name = "hub.mode", required = false) String mode,
@RequestParam(name = "hub.verify_token", required = false) String token,
@RequestParam(name = "hub.challenge", required = false) String challenge) {
String echo = webhook.verify(mode, token, challenge);
return echo == null ? ResponseEntity.status(HttpStatus.FORBIDDEN).build() : ResponseEntity.ok(echo);
}
@AppAuth(skipValidate = true)
@PostMapping
public ResponseEntity<Void> receive(HttpServletRequest request,
@RequestHeader(name = "X-Hub-Signature-256", required = false) String signature) throws IOException {
webhook.receive(request, signature);
return ResponseEntity.ok().build();
}
}
@@ -1,7 +1,7 @@
package com.solvway.mobile.api.dto.whatsapp;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
/** mobile-api to service, POST /whatsapp/webhook/ingest: the signature-matched company codes and the raw Meta payload. */
public record WebhookIngestRequest(List<String> matchedCompanyCodes, JsonNode payload) {}
/**
* mobile-api to service, POST /whatsapp/webhook/ingest. rawBody is the exact request bytes Meta sent, Base64-encoded;
* signature is the X-Hub-Signature-256 header as received. The service re-verifies it and never trusts the caller.
*/
public record WebhookIngestRequest(String rawBody, String signature) {}
@@ -213,7 +213,7 @@ public class PublicRegistrationService {
limit(key, max, "Too many registrations from this device. Try again later.");
}
void limit(String key, int max, String message) {
public void limit(String key, int max, String message) {
Long n = redis.opsForValue().increment(key);
if (n != null && n == 1) redis.expire(key, WINDOW_MINUTES, TimeUnit.MINUTES);
if (n != null && n > max) throw error(HttpStatus.TOO_MANY_REQUESTS, message, "TOO_MANY", null);
@@ -97,15 +97,18 @@ public class AppAccessAspect {
long start = System.currentTimeMillis();
String methodSig = joinPoint.getSignature().toShortString();
String apiKey = HttpReqRespUtils.getHeaderValues("api-key");
if(!StringUtils.hasLength(apiKey)){
log.warn("[AppAccessAspect] REJECT: missing 'api-key' header for method={}", methodSig);
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing header 'api-key'");
}
if(!authAppKey.contains(apiKey)) {
// Never log the allowed keys, even masked: a short key plus its ":PLATFORM" suffix outlives the mask.
log.warn("[AppAccessAspect] REJECT: api-key not in allowed list. received={} allowedKeyCount={}",
maskKey(apiKey), authAppKey.getList().size());
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid header 'api-key'");
// Meta sends no api-key; the webhook authenticates by body signature instead.
if (!isWhatsAppWebhook()) {
if(!StringUtils.hasLength(apiKey)){
log.warn("[AppAccessAspect] REJECT: missing 'api-key' header for method={}", methodSig);
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing header 'api-key'");
}
if(!authAppKey.contains(apiKey)) {
// Never log the allowed keys, even masked: a short key plus its ":PLATFORM" suffix outlives the mask.
log.warn("[AppAccessAspect] REJECT: api-key not in allowed list. received={} allowedKeyCount={}",
maskKey(apiKey), authAppKey.getList().size());
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid header 'api-key'");
}
}
User[] admin = new User[1];
Object result = null;
@@ -409,6 +412,16 @@ public class AppAccessAspect {
}
}
/** Exact: the handler mapping resolved to the webhook pattern itself, with GET or POST. Anything else (other paths, other methods) still needs the key. */
private static boolean isWhatsAppWebhook() {
if (!(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs)) {
return false;
}
HttpServletRequest request = attrs.getRequest();
return "/api/public/whatsapp/webhook".equals(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))
&& ("GET".equals(request.getMethod()) || "POST".equals(request.getMethod()));
}
private static boolean isAdminPath() {
if (!(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs)) {
return false;
@@ -0,0 +1,171 @@
package com.solvway.mobile.api.whatsapp;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.constant.api.RestApiWhatsappServiceConstants;
import com.solvway.mobile.api.dto.whatsapp.WebhookIngestRequest;
import com.solvway.mobile.api.service.PublicRegistrationService;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.server.ResponseStatusException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Meta's public webhook: subscription handshake and signed events. Settings come straight from the Environment like
* the WhatsApp service does (WHATSAPP_COMPANIES, WHATSAPP_&lt;CODE&gt;_APP_SECRET, WHATSAPP_VERIFY_TOKEN), read per
* request so a rotated secret needs no restart. Nothing here logs message content, numbers, signatures or secrets.
*/
@Slf4j
@Service
public class WhatsAppWebhookService {
private static final String PREFIX = "sha256=";
private static final ObjectMapper JSON = new ObjectMapper();
// ponytail: the shared limiter counts per 10-minute window, so this is 600/min on average; a per-minute window needs its own counter
private static final int IP_LIMIT = 6000;
private static final int MAX_BODY = 1024 * 1024;
private final Set<String> warned = ConcurrentHashMap.newKeySet();
private final Environment env;
private final RestTemplateCustomUtil rest;
private final PublicRegistrationService limiter;
public WhatsAppWebhookService(Environment env, RestTemplateCustomUtil rest, PublicRegistrationService limiter) {
this.env = env;
this.rest = rest;
this.limiter = limiter;
}
/** The challenge to echo, or null when the mode or verify token is wrong. A blank configured token never matches. */
public String verify(String mode, String token, String challenge) {
limit();
String configured = env.getProperty("WHATSAPP_VERIFY_TOKEN", "");
if (!"subscribe".equals(mode) || !StringUtils.hasText(configured) || token == null
|| !MessageDigest.isEqual(configured.getBytes(StandardCharsets.UTF_8), token.getBytes(StandardCharsets.UTF_8))) {
return null;
}
return challenge;
}
/** 401 unless the body is signed by at least one company's app secret; then forwards with every matching code. */
public void receive(HttpServletRequest request, String signature) throws IOException {
limit();
byte[] raw = readCapped(request);
List<String> matched = matchedCompanies(raw, signature);
if (matched.isEmpty()) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
}
JsonNode payload;
try {
payload = JSON.readTree(raw);
} catch (IOException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
}
if (payload == null || !payload.isObject()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
}
try {
rest.postForEntity(rest.getURLforApiService(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_WEBHOOK_INGEST),
Void.class, new WebhookIngestRequest(Base64.getEncoder().encodeToString(raw), signature));
} catch (RestClientException e) {
// Still 200: Meta retries on anything else and the service is idempotent. Status code only, never the message.
log.warn("WhatsApp webhook forward failed: {}", e instanceof RestClientResponseException r ? r.getStatusCode().value() : e.getClass().getSimpleName());
}
log.info("WhatsApp webhook forwarded for {} company(ies)", matched.size());
}
/** Never buffers more than MAX_BODY: 413 on a declared length over the cap, or when the stream runs past it. */
private static byte[] readCapped(HttpServletRequest request) throws IOException {
if (request.getContentLengthLong() > MAX_BODY) {
throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE);
}
byte[] body = request.getInputStream().readNBytes(MAX_BODY + 1);
if (body.length > MAX_BODY) {
throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE);
}
return body;
}
private List<String> matchedCompanies(byte[] body, String signature) {
List<String> matched = new ArrayList<>();
byte[] given = decode(signature);
if (given == null) {
return matched;
}
// Every company is checked, with no early exit, so timing does not reveal which one matched.
for (Map.Entry<String, String> company : secrets().entrySet()) {
if (MessageDigest.isEqual(given, hmac(company.getValue(), body))) {
matched.add(company.getKey());
}
}
return matched;
}
/** code -> app secret, in WHATSAPP_COMPANIES order; a company without a secret is skipped with a WARN naming only the code. */
private Map<String, String> secrets() {
Map<String, String> secrets = new LinkedHashMap<>();
for (String raw : env.getProperty("WHATSAPP_COMPANIES", "").split(",")) {
String code = raw.trim().toUpperCase();
if (code.isEmpty()) {
continue;
}
String secret = env.getProperty("WHATSAPP_" + code + "_APP_SECRET");
if (StringUtils.hasText(secret)) {
secrets.put(code, secret);
} else {
if (warned.add(code)) { // settings are read per request; say it once per code
log.warn("WhatsApp company {} skipped: no app secret configured", code);
}
}
}
return secrets;
}
/** "sha256=" plus 64 hex chars, as bytes; null for a missing or malformed header. */
private static byte[] decode(String header) {
if (header == null || !header.startsWith(PREFIX) || header.length() != PREFIX.length() + 64) {
return null;
}
try {
return HexFormat.of().parseHex(header.substring(PREFIX.length()));
} catch (IllegalArgumentException e) {
return null;
}
}
private static byte[] hmac(String secret, byte[] body) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
return mac.doFinal(body);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("HmacSHA256 unavailable", e);
}
}
private void limit() {
limiter.limit("wa:webhook:" + HttpReqRespUtils.getClientIpAddressIfServletRequestExist(), IP_LIMIT,
"Too many requests. Try again later.");
}
}
@@ -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();
}
}