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.");
}
}