diff --git a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java index 95946f1..24d8f9c 100644 --- a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java +++ b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java @@ -57,7 +57,9 @@ public class JWTAuthFilter implements GlobalFilter, Ordered { publicPath(HttpMethod.POST, "/counter/checkin/lookup"), publicPath(HttpMethod.POST, "/counter/checkin/byGuest"), // Password hint on public password screens: switched-on rule names and numbers only, no user data - publicPath(HttpMethod.GET, "/passwordRule/adminActive")); + publicPath(HttpMethod.GET, "/passwordRule/adminActive"), + // WhatsApp webhook forward from mobile-api: no user token; the service re-verifies Meta's signature itself + publicPath(HttpMethod.POST, "/whatsapp/webhook/ingest")); private static Map.Entry publicPath(HttpMethod method, String regex) { return Map.entry(method, Pattern.compile(regex)); diff --git a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java index 84c21ef..0d01b52 100644 --- a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java +++ b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java @@ -37,6 +37,30 @@ final class LogRedactor { return sb.toString(); } + /** Query params whose values never reach a log: Meta's webhook handshake sends the verify token and challenge in the URL. */ + private static final List SENSITIVE_PARAMS = List.of("hub.verify_token=", "hub.challenge="); + + /** The raw query string with the values of the sensitive params masked. */ + static String query(String rawQuery) { + if (rawQuery == null || rawQuery.isEmpty()) { + return rawQuery; + } + StringBuilder sb = new StringBuilder(rawQuery.length()); + int start = 0; + while (start <= rawQuery.length()) { + int amp = rawQuery.indexOf('&', start); + String pair = rawQuery.substring(start, amp < 0 ? rawQuery.length() : amp); + String name = SENSITIVE_PARAMS.stream().filter(pair::startsWith).findFirst().orElse(null); + sb.append(name == null ? pair : name + MASK); + if (amp < 0) { + break; + } + sb.append('&'); + start = amp + 1; + } + return sb.toString(); + } + /** Path prefixes followed by a bearer-style invite, check-in or registration-link token. */ private static final List TOKEN_PREFIXES = List.of("/counter/eventGuest/findByToken/", "/counter/checkin/findEvent/", "/counter/registrationLink/findByToken/"); diff --git a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java index bea7a77..6524a4a 100644 --- a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java +++ b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java @@ -92,4 +92,19 @@ class JWTAuthFilterPublicRegistrationPathTest { assertThat(ex.getResponse().getStatusCode()).as(c[0] + " " + c[1]).isEqualTo(HttpStatus.UNAUTHORIZED); } } + + @Test + void whatsAppIngestIsPublicButOnlyThatExactPostPath() { + assertThat(passes(call(HttpMethod.POST, "/whatsapp/webhook/ingest"))).isTrue(); + for (String[] c : new String[][] { + {"GET", "/whatsapp/webhook/ingest"}, + {"POST", "/whatsapp/webhook/ingest/x"}, + {"POST", "/x/whatsapp/webhook/ingest"}, + {"POST", "/whatsapp/ownership/userChanged"}, + {"GET", "/whatsapp/conversations"} }) { + MockServerWebExchange ex = call(HttpMethod.valueOf(c[0]), c[1]); + assertThat(passes(ex)).as(c[0] + " " + c[1]).isFalse(); + assertThat(ex.getResponse().getStatusCode()).as(c[0] + " " + c[1]).isEqualTo(HttpStatus.UNAUTHORIZED); + } + } } diff --git a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java index 3878211..1743473 100644 --- a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java +++ b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java @@ -61,4 +61,15 @@ class LogRedactorTest { .isEqualTo("/locationHierarchy/findParentByIdAndType/28/C"); assertTimeoutPreemptively(Duration.ofSeconds(1), () -> LogRedactor.path("/" + "eyJ.".repeat(20_000))); } + + @Test + @DisplayName("query: WhatsApp webhook verify token and challenge values are masked, other params kept") + void queryWebhookParamsMasked() { + assertThat(LogRedactor.query("hub.mode=subscribe&hub.verify_token=S3cretTok&hub.challenge=998877")) + .isEqualTo("hub.mode=subscribe&hub.verify_token=***&hub.challenge=***"); + assertThat(LogRedactor.query("hub.challenge=1&x=y&hub.verify_token=")).isEqualTo("hub.challenge=***&x=y&hub.verify_token=***"); + assertThat(LogRedactor.query("page=2&size=10")).isEqualTo("page=2&size=10"); + assertThat(LogRedactor.query(null)).isNull(); + assertThat(LogRedactor.query("")).isEmpty(); + } } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java index cb5b54d..0734a80 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java @@ -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 diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PublicWhatsAppWebhookController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PublicWhatsAppWebhookController.java new file mode 100644 index 0000000..5ed626a --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PublicWhatsAppWebhookController.java @@ -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 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 receive(HttpServletRequest request, + @RequestHeader(name = "X-Hub-Signature-256", required = false) String signature) throws IOException { + webhook.receive(request, signature); + return ResponseEntity.ok().build(); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java index 8f67809..c085513 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java @@ -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 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) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java index 0056058..30c4857 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java @@ -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); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java index 8902947..54bc60a 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java @@ -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; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookService.java new file mode 100644 index 0000000..54b7a03 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookService.java @@ -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_<CODE>_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 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 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 matchedCompanies(byte[] body, String signature) { + List 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 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 secrets() { + Map 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."); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java index 77b2184..b340d59 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java @@ -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)); } } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookTest.java new file mode 100644 index 0000000..2e62074 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookTest.java @@ -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 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 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 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 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(); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java index a3a4dc0..cb50fc6 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java @@ -1,7 +1,7 @@ package com.solvway.services.whatsapp.dto; -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 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) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java index f57a028..3e3dbc9 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java @@ -1,4 +1,8 @@ /** + * 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 diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java index 0319c3d..eb9bae2 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java @@ -1,6 +1,8 @@ package com.solvway.services.whatsapp.service; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.services.whatsapp.config.WhatsAppSettings; import com.solvway.services.whatsapp.dto.WebhookIngestRequest; import com.solvway.services.whatsapp.model.WaConversation; import com.solvway.services.whatsapp.model.WaMessage; @@ -14,13 +16,20 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; +import java.util.Base64; +import java.util.HexFormat; import java.util.List; import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; /** * Stores Meta webhook messages and delivery statuses. Deliberately not transactional: each repository call is its own @@ -36,6 +45,8 @@ public class WebhookIngestService { private static final Set MEDIA = Set.of("image", "document", "audio", "video", "sticker"); private static final List STATUS_RANK = List.of("pending", "sent", "delivered", "read"); private static final int PREVIEW_MAX = 80; + private static final String SIG_PREFIX = "sha256="; + private static final ObjectMapper JSON = new ObjectMapper(); private static final class Counts { int accepted, duplicates, dropped, applied, ignored; @@ -45,22 +56,39 @@ public class WebhookIngestService { private final WaConversationRepository conversations; private final WaMessageRepository messages; private final OwnershipService ownership; + private final WhatsAppSettings settings; public WebhookIngestService(CompanyDirectory companies, WaConversationRepository conversations, WaMessageRepository messages, - OwnershipService ownership) { + OwnershipService ownership, WhatsAppSettings settings) { + this.settings = settings; this.companies = companies; this.conversations = conversations; this.messages = messages; this.ownership = ownership; } + /** Re-verifies Meta's signature itself (the caller is not trusted); the companies that verify are the matched ones. */ public IngestResult ingest(WebhookIngestRequest request) { - JsonNode entries = request.payload() == null ? null : request.payload().get("entry"); + byte[] raw; + try { + raw = request.rawBody() == null ? null : Base64.getDecoder().decode(request.rawBody()); + } catch (IllegalArgumentException e) { + raw = null; + } + Set matched = raw == null ? Set.of() : matchedCompanies(raw, request.signature()); + if (matched.isEmpty()) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "INVALID_SIGNATURE"); + } + JsonNode payload; + try { + payload = JSON.readTree(raw); + } catch (IOException e) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + } + JsonNode entries = payload == null ? null : payload.get("entry"); if (entries == null || !entries.isArray()) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); } - Set matched = request.matchedCompanyCodes() == null ? Set.of() - : request.matchedCompanyCodes().stream().map(String::toUpperCase).collect(Collectors.toSet()); Counts c = new Counts(); for (JsonNode entry : entries) { for (JsonNode change : entry.path("changes")) { @@ -84,6 +112,32 @@ public class WebhookIngestService { return new IngestResult(c.accepted, c.duplicates, c.dropped, c.applied, c.ignored); } + /** Every company is checked, no early exit, constant-time compare. */ + private Set matchedCompanies(byte[] raw, String signature) { + if (signature == null || !signature.startsWith(SIG_PREFIX) || signature.length() != SIG_PREFIX.length() + 64) { + return Set.of(); + } + byte[] given; + try { + given = HexFormat.of().parseHex(signature.substring(SIG_PREFIX.length())); + } catch (IllegalArgumentException e) { + return Set.of(); + } + Set matched = new java.util.HashSet<>(); + for (WhatsAppSettings.CompanyConfig company : settings.companies()) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(company.appSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + if (MessageDigest.isEqual(given, mac.doFinal(raw))) { + matched.add(company.code().toUpperCase()); + } + } catch (GeneralSecurityException e) { + throw new IllegalStateException("HmacSHA256 unavailable", e); + } + } + return matched; + } + private void message(CompanyDirectory.Company company, String phoneNumberId, JsonNode value, JsonNode m, Counts c) { String wamid = text(m, "id"); String from = text(m, "from"); diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java index 2f3f997..6bbdb84 100644 --- a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java @@ -34,7 +34,7 @@ class WebhookControllerTest { when(service.ingest(any(WebhookIngestRequest.class))).thenReturn(new IngestResult(2, 1, 3, 0, 0)); mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON) - .content("{\"matchedCompanyCodes\":[\"INS\"],\"payload\":{\"entry\":[]}}")) + .content("{\"rawBody\":\"e30=\",\"signature\":\"sha256=00\"}")) .andExpect(status().isOk()) .andExpect(jsonPath("$.accepted").value(2)) .andExpect(jsonPath("$.duplicates").value(1)) @@ -48,12 +48,23 @@ class WebhookControllerTest { .andExpect(jsonPath("$.detail").value("INVALID_PAYLOAD")); } + @Test + void aBadSignatureIs401WithInvalidSignature() throws Exception { + when(service.ingest(any(WebhookIngestRequest.class))) + .thenThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, "INVALID_SIGNATURE")); + + mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON) + .content("{\"rawBody\":\"e30=\",\"signature\":\"sha256=00\"}")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.detail").value("INVALID_SIGNATURE")); + } + @Test void aPayloadTheServiceRejectsIsInvalidPayload() throws Exception { when(service.ingest(any(WebhookIngestRequest.class))) .thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD")); - mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON).content("{\"payload\":{}}")) + mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON).content("{\"rawBody\":\"e30=\"}")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.detail").value("INVALID_PAYLOAD")); } diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java index ea3248f..236c8d6 100644 --- a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java @@ -53,8 +53,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)); } } diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java index 037ecf5..50a06ec 100644 --- a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java @@ -2,6 +2,7 @@ package com.solvway.services.whatsapp.service; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.services.whatsapp.config.WhatsAppSettings; import com.solvway.services.whatsapp.dto.WebhookIngestRequest; import com.solvway.services.whatsapp.model.WaConversation; import com.solvway.services.whatsapp.model.WaMessage; @@ -20,6 +21,8 @@ import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.*; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -35,6 +38,7 @@ class WebhookIngestServiceTest { private static final ObjectMapper JSON = new ObjectMapper(); private static final String INS_PHONE = "111"; private static final String CV_PHONE = "222"; + private static final Map SECRETS = Map.of("INS", "ins-secret", "CV", "cv-secret"); private final Map conversations = new LinkedHashMap<>(); private final List messages = new ArrayList<>(); @@ -95,7 +99,11 @@ class WebhookIngestServiceTest { return m; }); ownership = mock(OwnershipService.class); - service = new WebhookIngestService(companies, convRepo, msgRepo, ownership); + WhatsAppSettings settings = mock(WhatsAppSettings.class); + when(settings.companies()).thenReturn(List.of( + new WhatsAppSettings.CompanyConfig("INS", INS_PHONE, "w1", "t1", SECRETS.get("INS")), + new WhatsAppSettings.CompanyConfig("CV", CV_PHONE, "w2", "t2", SECRETS.get("CV")))); + service = new WebhookIngestService(companies, convRepo, msgRepo, ownership, settings); } private Optional byWamid(String wamid) { @@ -116,8 +124,20 @@ class WebhookIngestServiceTest { return JSON.readTree(text); } - private IngestResult ingest(JsonNode payload, String... codes) { - return service.ingest(new WebhookIngestRequest(List.of(codes), payload)); + /** The request mobile-api forwards: the raw bytes plus Meta's signature header, signed with the given company's secret. */ + private static WebhookIngestRequest signed(byte[] raw, String secret) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + return new WebhookIngestRequest(Base64.getEncoder().encodeToString(raw), "sha256=" + HexFormat.of().formatHex(mac.doFinal(raw))); + } catch (java.security.GeneralSecurityException e) { + throw new IllegalStateException(e); + } + } + + /** Signs the payload with each named company's secret (first code only matters for single-signer tests). */ + private IngestResult ingest(JsonNode payload, String signer) { + return service.ingest(signed(payload.toString().getBytes(StandardCharsets.UTF_8), SECRETS.get(signer))); } private WaMessage seedOut(String wamid, String status) { @@ -197,7 +217,7 @@ class WebhookIngestServiceTest { @Test void dropsAnUnknownNumber() throws Exception { - IngestResult r = ingest(payload("text.json", "PHONE_ID", "999"), "INS", "CV"); + IngestResult r = ingest(payload("text.json", "PHONE_ID", "999"), "INS"); assertThat(r.dropped()).isEqualTo(1); assertThat(conversations).isEmpty(); @@ -206,8 +226,8 @@ class WebhookIngestServiceTest { @Test void keepsInsAndCvApart() throws Exception { - ingest(payload("text.json"), "INS", "CV"); - ingest(payload("text.json", "PHONE_ID", CV_PHONE, "WAMID", "wamid.2"), "INS", "CV"); + ingest(payload("text.json"), "INS"); + ingest(payload("text.json", "PHONE_ID", CV_PHONE, "WAMID", "wamid.2"), "CV"); assertThat(conversations).containsOnlyKeys("1/60111222333", "2/60111222333"); assertThat(conversations.get("1/60111222333").phoneNumberId).isEqualTo(INS_PHONE); @@ -372,12 +392,47 @@ class WebhookIngestServiceTest { @Test void rejectsAMalformedPayload() { - assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(List.of("INS"), null))) + assertThatThrownBy(() -> service.ingest(signed("not json".getBytes(StandardCharsets.UTF_8), SECRETS.get("INS")))) .isInstanceOfSatisfying(ResponseStatusException.class, e -> { assertThat(e.getStatusCode().value()).isEqualTo(400); assertThat(e.getReason()).isEqualTo("INVALID_PAYLOAD"); }); - assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(List.of("INS"), JSON.createObjectNode()))) + assertThatThrownBy(() -> ingest(JSON.createObjectNode(), "INS")) .isInstanceOf(ResponseStatusException.class); } + + @Test + void aForgedSignatureIsRejectedAndNothingIsStored() throws Exception { + byte[] raw = payload("text.json").toString().getBytes(StandardCharsets.UTF_8); + WebhookIngestRequest forged = new WebhookIngestRequest(signed(raw, "x").rawBody(), signed(raw, "wrong-secret").signature()); + + assertThatThrownBy(() -> service.ingest(forged)).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode().value()).isEqualTo(401); + assertThat(e.getReason()).isEqualTo("INVALID_SIGNATURE"); + }); + assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(signed(raw, "x").rawBody(), null))) + .isInstanceOf(ResponseStatusException.class); + assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(signed(raw, "x").rawBody(), "sha256=zz"))) + .isInstanceOf(ResponseStatusException.class); + assertThat(messages).isEmpty(); + assertThat(conversations).isEmpty(); + } + + @Test + void anAlteredBodyFailsTheSignature() throws Exception { + WebhookIngestRequest ok = signed(payload("text.json").toString().getBytes(StandardCharsets.UTF_8), SECRETS.get("INS")); + byte[] altered = payload("text.json", "BODY", "other").toString().getBytes(StandardCharsets.UTF_8); + + assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(Base64.getEncoder().encodeToString(altered), ok.signature()))) + .isInstanceOf(ResponseStatusException.class); + assertThat(messages).isEmpty(); + } + + @Test + void anInsPayloadSignedWithCvSecretDropsTheInsNumber() throws Exception { + IngestResult r = ingest(payload("text.json"), "CV"); + + assertThat(r.dropped()).isEqualTo(1); + assertThat(messages).isEmpty(); + } }