Coverage for api/webhooks_email.py: 46.56%

107 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 20:17 +0000

1""" 

2Inbound email webhook (Resend Inbound → support@missingtable.com). 

3 

4Verifies the provider's Svix signature, fetches the full ReceivedEmail 

5via the Resend API, runs the threading resolver, sanitizes any HTML, 

6and persists the message. Idempotent on RFC 5322 Message-ID so 

7provider retries are safe. 

8 

9SB-35 Phase 1. The admin API (Phase 2) and admin UI (Phase 3) consume 

10the rows we land here. 

11 

12The same Resend webhook (one endpoint, one signing secret) also carries the 

13delivery events for outbound mail. Those go to services.email_delivery, which 

14records invitation email delivery status (SB-1814). 

15""" 

16 

17from __future__ import annotations 

18 

19import json 

20import os 

21import sys 

22from typing import Any 

23 

24import resend 

25import structlog 

26from fastapi import APIRouter, HTTPException, Request 

27 

28sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 

29 

30from dao.email_messages_dao import EmailMessagesDAO 

31from dao.email_threads_dao import EmailThreadsDAO 

32from dao.match_dao import SupabaseConnection as DbConnectionHolder 

33from services.email_delivery import record_delivery_event, status_for_event 

34from services.email_inbound import ( 

35 WebhookVerificationError, 

36 resolve_thread, 

37 sanitize_html, 

38 verify_webhook, 

39) 

40from services.email_service import ensure_resend_api_key 

41 

42logger = structlog.get_logger(__name__) 

43 

44# Inbound writes bypass RLS via the service-role connection — the webhook 

45# can't authenticate as a user, and HMAC verification is the trust gate. 

46_db_conn = DbConnectionHolder() 

47_threads_dao = EmailThreadsDAO(_db_conn) 

48_messages_dao = EmailMessagesDAO(_db_conn) 

49 

50router = APIRouter(prefix="/api/webhooks", tags=["webhooks"]) 

51 

52_INBOUND_EVENT_TYPE = "email.received" 

53 

54 

55def _strip_angle_brackets(value: str | None) -> str | None: 

56 """RFC 5322 Message-IDs are wrapped in `<>`. Strip them for storage so 

57 our equality lookups don't have to care about the wrapping.""" 

58 if not value: 58 ↛ 60line 58 didn't jump to line 60 because the condition on line 58 was always true

59 return value 

60 stripped = value.strip() 

61 if stripped.startswith("<") and stripped.endswith(">"): 

62 return stripped[1:-1] 

63 return stripped 

64 

65 

66def _header_lookup(headers: dict[str, str] | None, *names: str) -> str | None: 

67 """Case-insensitive header lookup. Returns the first match.""" 

68 if not headers: 

69 return None 

70 lower = {k.lower(): v for k, v in headers.items()} 

71 for name in names: 

72 value = lower.get(name.lower()) 

73 if value: 

74 return value 

75 return None 

76 

77 

78def _extract_display_name(from_header: str) -> tuple[str, str | None]: 

79 """Parse a `"Jane Doe" <jane@example.com>` style From header into 

80 (address, display_name). Falls back to (raw, None) on anything weird.""" 

81 raw = from_header.strip() 

82 if "<" in raw and raw.endswith(">"): 

83 name_part, _, addr_part = raw.rpartition("<") 

84 name = name_part.strip().strip('"').strip() or None 

85 return addr_part[:-1].strip(), name 

86 return raw, None 

87 

88 

89@router.post("/email/inbound") 

90async def email_inbound(request: Request) -> dict[str, Any]: 

91 """Receive an `email.received` event from Resend Inbound, or a delivery 

92 event (email.sent, email.delivered, …) for an invitation email. 

93 

94 Returns 200 on: 

95 - Successful ingest 

96 - Delivery event, recorded or ignored (unknown email id) — SB-1814 

97 - Unknown event type (we ignore quietly so Resend doesn't retry) 

98 - Already-seen Message-ID (idempotent retry) 

99 

100 Returns 401 on signature mismatch. 

101 Returns 500 on internal failure — Resend will retry. 

102 """ 

103 raw_body = await request.body() 

104 payload_str = raw_body.decode("utf-8") 

105 

106 # Forward only the headers the verifier needs — keeps logs cleaner. 

107 svix_headers = { 

108 k: v 

109 for k, v in request.headers.items() 

110 if k.lower().startswith("svix-") 

111 } 

112 

113 try: 

114 verify_webhook(payload=payload_str, headers=svix_headers) 

115 except WebhookVerificationError as e: 

116 logger.warning("email_webhook_unauthorized", error=str(e)) 

117 raise HTTPException(status_code=401, detail="invalid webhook signature") from e 

118 

119 try: 

120 event = json.loads(payload_str) 

121 except json.JSONDecodeError as e: 

122 logger.warning("email_webhook_bad_json", error=str(e)) 

123 raise HTTPException(status_code=400, detail="invalid JSON payload") from e 

124 

125 event_type = event.get("type") 

126 if status_for_event(event_type): 

127 return record_delivery_event(_db_conn.client, event) 

128 if event_type != _INBOUND_EVENT_TYPE: 

129 logger.info("email_webhook_ignored_event", event_type=event_type) 

130 return {"status": "ignored", "event_type": event_type} 

131 

132 data = event.get("data") or {} 

133 email_id = data.get("email_id") or data.get("id") 

134 if not email_id: 134 ↛ 136line 134 didn't jump to line 136 because the condition on line 134 was never true

135 # `event` is reserved by structlog — use a different key. 

136 logger.warning("email_webhook_missing_email_id", payload=event) 

137 raise HTTPException(status_code=400, detail="event.data.email_id missing") 

138 

139 received = _fetch_received_email(email_id) 

140 

141 raw_message_id = received.get("message_id") 

142 message_id = _strip_angle_brackets(raw_message_id) 

143 if not message_id: 143 ↛ 148line 143 didn't jump to line 148 because the condition on line 143 was always true

144 logger.warning("email_webhook_missing_message_id", email_id=email_id) 

145 raise HTTPException(status_code=400, detail="received email has no message_id") 

146 

147 # Idempotency: if we've seen this message_id already, Resend retried. 

148 existing = _messages_dao.find_by_message_id(message_id) 

149 if existing: 

150 logger.info( 

151 "email_webhook_duplicate", 

152 message_id=message_id, 

153 thread_id=existing["thread_id"], 

154 ) 

155 return { 

156 "status": "duplicate", 

157 "message_id": message_id, 

158 "thread_id": existing["thread_id"], 

159 } 

160 

161 # ── Extract envelope fields ───────────────────────────────────────────── 

162 headers = received.get("headers") or received.get("http_headers") or {} 

163 in_reply_to = _strip_angle_brackets(_header_lookup(headers, "In-Reply-To")) 

164 references = _header_lookup(headers, "References") 

165 

166 from_raw = received.get("from") or "" 

167 from_email, from_name = _extract_display_name(from_raw) 

168 to_list = received.get("to") or [] 

169 to_email = to_list[0] if to_list else "" 

170 

171 subject = received.get("subject") or "(no subject)" 

172 body_text = received.get("text") 

173 body_html_raw = received.get("html") 

174 had_attachments = bool(received.get("attachments")) 

175 

176 # ── Resolve / create thread ───────────────────────────────────────────── 

177 last_message_at_iso = received.get("created_at") 

178 thread, created = resolve_thread( 

179 _threads_dao, 

180 _messages_dao, 

181 subject=subject, 

182 from_email=from_email, 

183 from_name=from_name, 

184 in_reply_to=in_reply_to, 

185 last_message_at_iso=last_message_at_iso, 

186 ) 

187 

188 # ── Insert inbound message ────────────────────────────────────────────── 

189 sanitized_html = sanitize_html(body_html_raw) 

190 # raw_payload omits attachments — we don't want the base64 bodies in pg. 

191 raw_for_storage = {k: v for k, v in received.items() if k != "attachments"} 

192 

193 _messages_dao.insert_inbound( 

194 thread_id=thread["id"], 

195 message_id=message_id, 

196 from_email=from_email, 

197 from_name=from_name, 

198 to_email=to_email, 

199 subject=subject, 

200 in_reply_to=in_reply_to, 

201 references=references, 

202 body_text=body_text, 

203 body_html=sanitized_html, 

204 had_attachments=had_attachments, 

205 raw_payload=raw_for_storage, 

206 ) 

207 

208 # ── Status transition for existing threads ────────────────────────────── 

209 # New threads start at status='new' with unread_count=1 (create_for_inbound 

210 # already set both), so only transition existing threads. 

211 if not created: 

212 _threads_dao.transition_on_inbound( 

213 thread["id"], last_message_at=last_message_at_iso 

214 ) 

215 

216 logger.info( 

217 "email_webhook_ingested", 

218 thread_id=thread["id"], 

219 case_number=thread["case_number"], 

220 message_id=message_id, 

221 created_new_thread=created, 

222 had_attachments=had_attachments, 

223 ) 

224 return { 

225 "status": "accepted", 

226 "thread_id": thread["id"], 

227 "case_number": thread["case_number"], 

228 "created_new_thread": created, 

229 } 

230 

231 

232def _fetch_received_email(email_id: str) -> dict[str, Any]: 

233 """Fetch the full ReceivedEmail from the Resend API. 

234 

235 Returns the underlying dict (ReceivedEmail is a TypedDict). Raised 

236 exceptions become 502 from the caller's perspective — Resend will 

237 retry, which is the right behavior for transient upstream failures. 

238 """ 

239 ensure_resend_api_key() 

240 try: 

241 return resend.Emails.Receiving.get(email_id) 

242 except Exception as e: 

243 logger.exception("email_webhook_fetch_failed", email_id=email_id) 

244 raise HTTPException(status_code=502, detail=f"failed to fetch email {email_id}") from e