From 3e610e0f88127ac99ddbeb1461df28b56bb212e7 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 11:49:17 +0800 Subject: [PATCH] fix(whatsapp): answer 503 when the inbox cannot take an event, so Meta redelivers The webhook answered 200 whatever happened downstream, and Meta only redelivers on a non-2xx answer, so an event that reached a stopped service, or a just-started one that had not resolved its companies yet, was lost. mobile-api now answers 503 on an unreachable service or a 5xx (a 4xx refusal still gets 200), and the service answers 503 for a configured number whose company is not resolved yet. wamid uniqueness makes the redelivery safe. Owner decision 2026-12-02; design D3 and the spec updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- openspec/changes/add-whatsapp-inbox/design.md | 4 ++-- .../specs/whatsapp-inbox/spec.md | 9 ++++++- .../api/whatsapp/WhatsAppWebhookService.java | 7 +++++- .../api/whatsapp/WhatsAppWebhookTest.java | 24 +++++++++++++++++-- .../whatsapp/service/CompanyDirectory.java | 5 ++++ .../service/WebhookIngestService.java | 4 ++++ .../service/CompanyDirectoryTest.java | 18 ++++++++++++++ .../service/WebhookIngestServiceTest.java | 16 ++++++++++++- 8 files changed, 80 insertions(+), 7 deletions(-) diff --git a/openspec/changes/add-whatsapp-inbox/design.md b/openspec/changes/add-whatsapp-inbox/design.md index 32603b4..bea6b2f 100644 --- a/openspec/changes/add-whatsapp-inbox/design.md +++ b/openspec/changes/add-whatsapp-inbox/design.md @@ -38,8 +38,8 @@ The product design is `docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.m - computes the HMAC-SHA256 under each configured app secret and compares it in constant time (`MessageDigest.isEqual`); - collects the matching company codes, answering 401 when none match; - parses the body and forwards `{ matchedCompanyCodes, payload }` to the service at `/whatsapp/webhook/ingest`; - - answers 200 even if the service errors, logging only counts, because Meta retries and the service is idempotent. - 2. The service accepts each `entry.changes[].value` only when its `metadata.phone_number_id` belongs to one of the matched companies. + - answers 503 when the service cannot take the event (unreachable or 5xx), so Meta redelivers it (for up to 7 days); the service ignores a `wamid` it already holds, so a redelivery is safe. A refusal from the service (4xx) still answers 200, since a redelivery cannot succeed. It logs the status code only. (Owner decision 2026-12-02: the first version answered 200 on any service error, and that loses the event, because Meta redelivers only on a non-2xx answer.) + 2. The service accepts each `entry.changes[].value` only when its `metadata.phone_number_id` belongs to one of the matched companies. For a configured number whose company it has not resolved yet (the system service was unreachable), it answers 503 so that Meta redelivers. 3. The webhook is exempt from the API key and admin JWT, like the other public routes, and rate-limited per IP at a high ceiling. 4. **Idempotency and ordering.** `wa_message.wamid` is unique, so an insert that conflicts is ignored. Status updates follow the rank `pending 0 < sent 1 < delivered 2 < read 3`, and `failed` always applies. diff --git a/openspec/changes/add-whatsapp-inbox/specs/whatsapp-inbox/spec.md b/openspec/changes/add-whatsapp-inbox/specs/whatsapp-inbox/spec.md index 4e02500..2629a2d 100644 --- a/openspec/changes/add-whatsapp-inbox/specs/whatsapp-inbox/spec.md +++ b/openspec/changes/add-whatsapp-inbox/specs/whatsapp-inbox/spec.md @@ -36,7 +36,7 @@ The webhook SHALL accept an event only when its `X-Hub-Signature-256` header is ### Requirement: Inbound messages -An accepted inbound message SHALL be stored once, in the conversation of the company that owns the receiving number, for the sender's WhatsApp number. Meta redelivering the same message id SHALL NOT create a second message. An event for a number no company owns SHALL be dropped. Receiving a message SHALL open the 24-hour reply window. +An accepted inbound message SHALL be stored once, in the conversation of the company that owns the receiving number, for the sender's WhatsApp number. Meta redelivering the same message id SHALL NOT create a second message. An event for a number no company owns SHALL be dropped. An event the inbox cannot take yet (the service is down, or the company of a configured number is not known yet) SHALL be refused, so that Meta redelivers it. Receiving a message SHALL open the 24-hour reply window. #### Scenario: Lead writes to INS @@ -50,6 +50,13 @@ An accepted inbound message SHALL be stored once, in the conversation of the com - **WHEN** Meta delivers the same message id twice - **THEN** the conversation holds the message once +#### Scenario: Inbox not ready + +- **GIVEN** the WhatsApp service has just started and cannot reach the system service yet +- **WHEN** Meta delivers a message to INS's number +- **THEN** the webhook answers 503 and stores nothing +- **AND** when Meta redelivers after the service has resolved INS, the message is stored once + ### Requirement: Delivery status The status of a sent message SHALL move only forward, from pending to sent to delivered to read, except that failed SHALL be recorded at any point, together with Meta's error code and title. The thread SHALL show the status as ticks, or as a failure with its reason. 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 index 54b7a03..5cfcf8c 100644 --- 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 @@ -89,8 +89,13 @@ public class WhatsAppWebhookService { 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. + // Status code only, never the message. log.warn("WhatsApp webhook forward failed: {}", e instanceof RestClientResponseException r ? r.getStatusCode().value() : e.getClass().getSimpleName()); + // A refusal (4xx) cannot succeed on a retry, so Meta gets 200. Anything else (service down, 5xx) answers 503: + // Meta redelivers for up to 7 days, and the service ignores a wamid it already holds. + if (!(e instanceof RestClientResponseException r && r.getStatusCode().is4xxClientError())) { + throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE); + } } log.info("WhatsApp webhook forwarded for {} company(ies)", matched.size()); } 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 index 2e62074..13f75a2 100644 --- 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 @@ -27,6 +27,8 @@ 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.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestClientException; import javax.crypto.Mac; @@ -251,7 +253,7 @@ class WhatsAppWebhookTest { } @Test - void forwardFailureStillAnswers200AndLogsNoContent() throws Exception { + void forwardFailureAnswers503SoMetaRetriesAndLogsNoContent() throws Exception { ListAppender logs = new ListAppender<>(); logs.start(); Logger logger = (Logger) LoggerFactory.getLogger(WhatsAppWebhookService.class); @@ -261,7 +263,7 @@ class WhatsAppWebhookTest { 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()); + .header("X-Hub-Signature-256", sig)).andExpect(status().isServiceUnavailable()); assertThat(logs.list).isNotEmpty(); for (ILoggingEvent e : logs.list) { assertThat(e.getFormattedMessage()).doesNotContain("hello").doesNotContain("secret").doesNotContain(sig).doesNotContain("verify-me"); @@ -272,6 +274,24 @@ class WhatsAppWebhookTest { } } + @Test + void serviceErrorAnswers503SoMetaRetries() throws Exception { + when(rest.postForEntity(eq(INGEST), eq(Void.class), any())) + .thenThrow(HttpServerErrorException.create(HttpStatus.SERVICE_UNAVAILABLE, "x", null, null, null)); + 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().isServiceUnavailable()); + } + + @Test + void serviceRefusalStillAnswers200BecauseARetryCannotHelp() throws Exception { + when(rest.postForEntity(eq(INGEST), eq(Void.class), any())) + .thenThrow(HttpClientErrorException.create(HttpStatus.BAD_REQUEST, "x", null, null, null)); + 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()); + } + @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")) diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java index 443cd67..cb5b3d5 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java @@ -65,6 +65,11 @@ public class CompanyDirectory { return Optional.ofNullable(byPhoneNumberId.get(phoneNumberId)); } + /** True for a configured number whose company could not be looked up yet (system service unreachable). */ + public boolean pending(String phoneNumberId) { + return settings.findByPhoneNumberId(phoneNumberId).map(c -> unresolved.contains(c.code())).orElse(false); + } + /** The configured phone number id of the company; empty when WhatsApp is not configured for it (or not resolved yet). */ public Optional phoneNumberIdOf(long companyId) { if (!unresolved.isEmpty() && !coolingDown()) { 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 eb9bae2..f834832 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 @@ -99,6 +99,10 @@ public class WebhookIngestService { String phoneNumberId = value.path("metadata").path("phone_number_id").asText(""); CompanyDirectory.Company company = companies.byPhoneNumberId(phoneNumberId) .filter(co -> matched.contains(co.code().toUpperCase())).orElse(null); + if (company == null && companies.pending(phoneNumberId)) { + // Our number, but its company is not known yet: fail so Meta redelivers (wamid makes that safe). + throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "COMPANY_NOT_RESOLVED"); + } if (company == null) { c.dropped += value.path("messages").size() + value.path("statuses").size(); continue; diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/CompanyDirectoryTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/CompanyDirectoryTest.java index 7b332b5..102a709 100644 --- a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/CompanyDirectoryTest.java +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/CompanyDirectoryTest.java @@ -88,6 +88,24 @@ class CompanyDirectoryTest { assertThat(d.byPhoneNumberId("222")).contains(new CompanyDirectory.Company(2, "CV")); } + @Test + void reportsAConfiguredNumberAsPendingUntilItsCompanyResolves() throws Exception { + when(rest.getForObject(anyString(), eq(JsonNode.class), eq("INS"))) + .thenThrow(new ResourceAccessException("down")) + .thenReturn(company(1)); + when(rest.getForObject(anyString(), eq(JsonNode.class), eq("CV"))).thenReturn(null); + CompanyDirectory d = new CompanyDirectory(settings, rest, clock); + + d.resolveAtStartup(); + + assertThat(d.pending("111")).isTrue(); + assertThat(d.pending("222")).isFalse(); // resolved to "no such company": final, not pending + assertThat(d.pending("999")).isFalse(); // not configured at all + clock.advance(Duration.ofSeconds(30)); + d.byPhoneNumberId("111"); + assertThat(d.pending("111")).isFalse(); + } + @Test void waitsThirtySecondsAfterAFailedResolveBeforeTryingAgain() { when(rest.getForObject(anyString(), eq(JsonNode.class), anyString())).thenThrow(new ResourceAccessException("down")); 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 50a06ec..652f507 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 @@ -11,6 +11,7 @@ import com.solvway.services.whatsapp.ownership.OwnershipService; import com.solvway.services.whatsapp.repository.WaMessageRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.web.server.ResponseStatusException; @@ -47,10 +48,11 @@ class WebhookIngestServiceTest { private WaConversationRepository convRepo; private OwnershipService ownership; private WebhookIngestService service; + private CompanyDirectory companies; @BeforeEach void setUp() { - CompanyDirectory companies = mock(CompanyDirectory.class); + companies = mock(CompanyDirectory.class); when(companies.byPhoneNumberId(INS_PHONE)).thenReturn(Optional.of(new CompanyDirectory.Company(1, "INS"))); when(companies.byPhoneNumberId(CV_PHONE)).thenReturn(Optional.of(new CompanyDirectory.Company(2, "CV"))); when(companies.byPhoneNumberId("999")).thenReturn(Optional.empty()); @@ -151,6 +153,18 @@ class WebhookIngestServiceTest { return m; } + @Test + void answers503WhileTheNumbersCompanyIsNotResolvedYetSoMetaRedelivers() throws Exception { + when(companies.byPhoneNumberId(INS_PHONE)).thenReturn(Optional.empty()); + when(companies.pending(INS_PHONE)).thenReturn(true); + + assertThatThrownBy(() -> ingest(payload("text.json"), "INS")) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE)); + assertThat(conversations).isEmpty(); + assertThat(messages).isEmpty(); + } + @Test void recomputesOwnershipOnlyWhenTheConversationIsFirstCreated() throws Exception { ingest(payload("text.json", "WAMID", "wamid.a"), "INS");