Coverage for services/email_inbound.py: 19.44%
78 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
1"""
2Inbound-email primitives for the Support Inbox (SB-35 Phase 1).
4Pure-ish helpers consumed by the inbound webhook handler:
5- verify_webhook — wraps resend.Webhooks.verify with env-driven secret + typed errors
6- sanitize_html — bleach allowlist; never store raw provider HTML
7- parse_case_number_from_subject — `[MT-{n}]` extractor for threading fallback
8- normalize_subject — strips Re:/Fwd: + case-number tokens for fuzzy match
9- resolve_thread — 4-tier threading resolver (creates a new thread if no match)
10"""
12from __future__ import annotations
14import os
15import re
16from datetime import UTC, datetime, timedelta
17from typing import TYPE_CHECKING, Any
19import bleach
20import resend
21import structlog
23if TYPE_CHECKING:
24 from dao.email_messages_dao import EmailMessagesDAO
25 from dao.email_threads_dao import EmailThreadsDAO
27logger = structlog.get_logger()
30class WebhookVerificationError(Exception):
31 """Raised when the inbound webhook signature can't be verified."""
34# ── HMAC verification ────────────────────────────────────────────────────────
37def verify_webhook(*, payload: str, headers: dict[str, str]) -> None:
38 """Verify a Resend inbound webhook using its Svix-based signature.
40 Loads the secret from EMAIL_INBOUND_WEBHOOK_SECRET. The payload must be
41 the raw request body string (not parsed JSON) — Svix is sensitive to
42 even whitespace differences.
44 Raises WebhookVerificationError on any failure (missing secret,
45 missing headers, bad signature). The webhook handler should catch
46 this and return 401.
47 """
48 secret = os.getenv("EMAIL_INBOUND_WEBHOOK_SECRET")
49 if not secret:
50 raise WebhookVerificationError(
51 "EMAIL_INBOUND_WEBHOOK_SECRET is not configured"
52 )
54 required = {"svix-id", "svix-timestamp", "svix-signature"}
55 lowered = {k.lower(): v for k, v in headers.items()}
56 missing = required - lowered.keys()
57 if missing:
58 raise WebhookVerificationError(
59 f"Missing required webhook header(s): {sorted(missing)}"
60 )
62 # Resend's WebhookHeaders TypedDict uses the short keys `id`/`timestamp`/
63 # `signature` (the `svix-` prefix is stripped). The field-level docstring
64 # says "The svix-id header value" but the field is named just `id`, so
65 # we must remap before calling verify — passing the prefixed HTTP-header
66 # names through results in "svix-id header is required" failures.
67 try:
68 resend.Webhooks.verify(
69 resend.VerifyWebhookOptions(
70 payload=payload,
71 headers={
72 "id": lowered["svix-id"],
73 "timestamp": lowered["svix-timestamp"],
74 "signature": lowered["svix-signature"],
75 },
76 webhook_secret=secret,
77 )
78 )
79 except Exception as e:
80 raise WebhookVerificationError(f"Signature verification failed: {e}") from e
83# ── HTML sanitization ────────────────────────────────────────────────────────
85# Conservative allowlist for displayed email content. We don't trust the
86# inbound payload, so we strip everything not in this set. Bleach also
87# rejects javascript: hrefs by default given the protocol allowlist below.
88_ALLOWED_TAGS = frozenset({
89 "a", "b", "blockquote", "br", "code", "div", "em", "hr",
90 "i", "li", "ol", "p", "pre", "span", "strong", "u", "ul",
91})
92_ALLOWED_ATTRIBUTES = {
93 "a": ["href", "title"],
94 "span": ["class"],
95 "div": ["class"],
96}
97_ALLOWED_PROTOCOLS = frozenset({"http", "https", "mailto"})
100def sanitize_html(raw: str | None) -> str | None:
101 """Sanitize untrusted inbound HTML with a conservative allowlist.
103 Returns None for None input (so we can pass it through). Strips
104 disallowed tags rather than escaping them — we never want raw HTML
105 rendered into the admin UI.
106 """
107 if raw is None:
108 return None
109 return bleach.clean(
110 raw,
111 tags=_ALLOWED_TAGS,
112 attributes=_ALLOWED_ATTRIBUTES,
113 protocols=_ALLOWED_PROTOCOLS,
114 strip=True,
115 )
118# ── Case-number / subject parsing ────────────────────────────────────────────
120# Matches `[MT-1234]` (any leading/trailing space) and captures the digits.
121# Case-insensitive on "MT". Doesn't match `MT-1234` without brackets — we
122# always render the case number bracketed in outbound subjects, and we
123# don't want to false-match other patterns in subjects.
124_CASE_RE = re.compile(r"\[\s*MT-(\d+)\s*\]", re.IGNORECASE)
126# Strips Re:/Fwd:/Fw: prefixes, possibly chained ("Re: Re: Re:"). Match
127# at the start, repeat. Case-insensitive, optional surrounding whitespace.
128_REPLY_PREFIX_RE = re.compile(r"^\s*(?:re|fwd?|fw)\s*:\s*", re.IGNORECASE)
131def parse_case_number_from_subject(subject: str | None) -> int | None:
132 """Return the integer case number embedded as `[MT-{n}]`, or None."""
133 if not subject:
134 return None
135 m = _CASE_RE.search(subject)
136 if not m:
137 return None
138 try:
139 return int(m.group(1))
140 except (TypeError, ValueError):
141 return None
144def normalize_subject(subject: str | None) -> str:
145 """Subject form used for fuzzy thread matching.
147 - strips chained Re:/Fwd: prefixes
148 - removes any [MT-{n}] token
149 - collapses internal whitespace
150 - lowercases
151 """
152 if not subject:
153 return ""
154 s = _CASE_RE.sub("", subject)
155 while True:
156 new = _REPLY_PREFIX_RE.sub("", s)
157 if new == s:
158 break
159 s = new
160 return " ".join(s.split()).lower()
163# ── Threading resolver ───────────────────────────────────────────────────────
165# Window for the fuzzy fallback. Anything older and we'd rather start a
166# new thread than risk merging unrelated conversations.
167_FALLBACK_WINDOW = timedelta(days=30)
170def resolve_thread(
171 threads_dao: EmailThreadsDAO,
172 messages_dao: EmailMessagesDAO,
173 *,
174 subject: str,
175 from_email: str,
176 from_name: str | None,
177 in_reply_to: str | None,
178 last_message_at_iso: str | None = None,
179 now: datetime | None = None,
180) -> tuple[dict[str, Any], bool]:
181 """Resolve the email_threads row this inbound message belongs to.
183 Returns (thread_row, created), where `created` is True if a new thread
184 was inserted.
186 Fallback chain (in order):
187 1. `In-Reply-To` matches a known message_id → reuse its thread
188 2. `[MT-{n}]` in subject → reuse the matching thread by case_number
189 3. Same participant + same normalized subject within the last 30 days
190 → reuse the most recent matching thread
191 4. Nothing matched → create a new thread (assigns a fresh case number)
192 """
193 # 1) In-Reply-To
194 if in_reply_to:
195 thread_id = messages_dao.find_thread_id_by_in_reply_to(in_reply_to)
196 if thread_id:
197 existing = threads_dao.get_thread_by_id(thread_id)
198 if existing:
199 logger.info(
200 "email_thread_resolved",
201 via="in_reply_to",
202 thread_id=existing["id"],
203 case_number=existing["case_number"],
204 )
205 return existing, False
207 # 2) [MT-{n}] in subject
208 case_number = parse_case_number_from_subject(subject)
209 if case_number is not None:
210 existing = threads_dao.get_by_case_number(case_number)
211 if existing:
212 logger.info(
213 "email_thread_resolved",
214 via="case_number",
215 thread_id=existing["id"],
216 case_number=existing["case_number"],
217 )
218 return existing, False
220 # 3) Recent participant + same normalized subject
221 normalized = normalize_subject(subject)
222 if normalized:
223 since = (now or datetime.now(UTC)) - _FALLBACK_WINDOW
224 candidates = threads_dao.find_recent_by_participant(
225 from_email,
226 since_iso=since.isoformat(),
227 )
228 for candidate in candidates:
229 if normalize_subject(candidate.get("subject")) == normalized:
230 logger.info(
231 "email_thread_resolved",
232 via="participant_subject",
233 thread_id=candidate["id"],
234 case_number=candidate["case_number"],
235 )
236 return candidate, False
238 # 4) New thread
239 created = threads_dao.create_for_inbound(
240 subject=subject or "(no subject)",
241 participant_email=from_email,
242 participant_name=from_name,
243 last_message_at=last_message_at_iso,
244 )
245 logger.info(
246 "email_thread_resolved",
247 via="new",
248 thread_id=created["id"],
249 case_number=created["case_number"],
250 )
251 return created, True