:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement chatwoot import source (#71251)
Tom Owerse7fd18e228f6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 3764d0ebffbe..4ceb92bf1a50 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -117,6 +117,7 @@ the row lists both.| chargedesk | HTTP | requests | ✅ || chargify | HTTP | requests + `rest_source.RESTClient` | ✅ || charthop | HTTP | requests | ✅ |+| chatwoot | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || checkmarx | HTTP | requests | ✅ || checkout_com | HTTP | requests | ✅ || churnkey | HTTP | requests | ✅ |@@ -636,7 +637,6 @@ doesn't conflict with concurrent PRs.- captain_data- cart_com- castor_edc-- chatwoot- chift- chorus- cin7diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/canonical_descriptions.pynew file mode 100644index 000000000000..822b4a42cb1f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/canonical_descriptions.py@@ -0,0 +1,126 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "conversations": {+ "description": "A conversation between a contact and your team in one inbox, grouping the exchanged messages.",+ "docs_url": "https://developers.chatwoot.com/api-reference/conversations/conversations-list",+ "columns": {+ "id": "The conversation's display id, unique within the account. Also the id used in conversation URLs and API paths.",+ "uuid": "Globally unique identifier for the conversation.",+ "inbox_id": "Id of the inbox the conversation belongs to.",+ "status": "Current state of the conversation: open, resolved, pending, or snoozed.",+ "priority": "Priority assigned to the conversation (urgent, high, medium, low), if any.",+ "labels": "Labels attached to the conversation.",+ "muted": "Whether the conversation is muted.",+ "can_reply": "Whether the inbox channel still allows replying (e.g. within a messaging window).",+ "unread_count": "Number of unread messages in the conversation.",+ "custom_attributes": "Values of conversation-scoped custom attributes.",+ "additional_attributes": "Channel-specific metadata such as the browser, referer, or initiated-at details.",+ "snoozed_until": "When the conversation's snooze expires, if snoozed.",+ "waiting_since": "Unix timestamp since when the contact has been waiting for a reply.",+ "first_reply_created_at": "Unix timestamp of the first agent reply.",+ "agent_last_seen_at": "Unix timestamp when an agent last viewed the conversation.",+ "contact_last_seen_at": "Unix timestamp when the contact last viewed the conversation.",+ "last_activity_at": "Unix timestamp of the last activity in the conversation.",+ "created_at": "Unix timestamp when the conversation was created.",+ "updated_at": "Unix timestamp when the conversation was last updated.",+ },+ },+ "messages": {+ "description": "A single message within a conversation, including agent replies, contact messages, and templates.",+ "docs_url": "https://developers.chatwoot.com/api-reference/messages/messages-list",+ "columns": {+ "id": "Unique identifier for the message.",+ "conversation_id": "Display id of the conversation the message belongs to.",+ "content": "Text content of the message.",+ "content_type": "Content type of the message (text, input_select, cards, form, ...).",+ "content_attributes": "Structured attributes for rich content types.",+ "message_type": "Message direction/kind as an integer: 0 incoming, 1 outgoing, 2 activity, 3 template.",+ "private": "Whether the message is a private note visible only to agents.",+ "status": "Delivery status of the message (sent, delivered, read, failed).",+ "source_id": "Id of the message on the origin channel (e.g. the email message id).",+ "sender": "The user or contact who sent the message.",+ "attachments": "Files attached to the message.",+ "created_at": "Unix timestamp when the message was created.",+ },+ },+ "contacts": {+ "description": "A person your team talks to, identified by email, phone number, or an external identifier.",+ "docs_url": "https://developers.chatwoot.com/api-reference/contacts/contacts-list",+ "columns": {+ "id": "Unique identifier for the contact.",+ "name": "The contact's name.",+ "email": "The contact's email address.",+ "phone_number": "The contact's phone number.",+ "identifier": "External identifier you assigned to the contact.",+ "blocked": "Whether the contact is blocked.",+ "custom_attributes": "Values of contact-scoped custom attributes.",+ "additional_attributes": "Extra metadata such as company, location, or social profiles.",+ "last_activity_at": "Unix timestamp of the contact's last activity.",+ "created_at": "Unix timestamp when the contact was created.",+ },+ },+ "inboxes": {+ "description": "A channel through which conversations arrive, such as a website widget, email address, or WhatsApp number.",+ "docs_url": "https://developers.chatwoot.com/api-reference/inboxes/list-all-inboxes",+ "columns": {+ "id": "Unique identifier for the inbox.",+ "name": "Name of the inbox.",+ "channel_type": "The channel backing the inbox (Channel::WebWidget, Channel::Email, ...).",+ "greeting_enabled": "Whether the automatic greeting is enabled.",+ "working_hours_enabled": "Whether working hours are configured for the inbox.",+ "timezone": "Timezone used for the inbox's working hours.",+ },+ },+ "agents": {+ "description": "A user who is a member of the account, including their role and availability.",+ "docs_url": "https://developers.chatwoot.com/api-reference/agents/list-agents-in-account",+ "columns": {+ "id": "Unique identifier for the agent's user.",+ "name": "The agent's full name.",+ "available_name": "Display name shown to contacts.",+ "email": "The agent's email address.",+ "role": "The agent's role in the account: agent or administrator.",+ "availability_status": "Current availability: online, busy, or offline.",+ "auto_offline": "Whether the agent is automatically marked offline when away.",+ "confirmed": "Whether the agent's user account is confirmed.",+ },+ },+ "teams": {+ "description": "A group of agents used to organize and assign conversations.",+ "docs_url": "https://developers.chatwoot.com/api-reference/teams/list-all-teams",+ "columns": {+ "id": "Unique identifier for the team.",+ "name": "Name of the team.",+ "description": "Description of the team.",+ "allow_auto_assign": "Whether conversations assigned to the team are auto-assigned to its members.",+ },+ },+ "labels": {+ "description": "A label that can be attached to conversations and contacts for categorization.",+ "docs_url": "https://developers.chatwoot.com/api-reference/account-labels/list-all-labels",+ "columns": {+ "id": "Unique identifier for the label.",+ "title": "The label text.",+ "description": "Description of the label.",+ "color": "Display color of the label.",+ "show_on_sidebar": "Whether the label is pinned to the sidebar.",+ },+ },+ "custom_attribute_definitions": {+ "description": "Definition of a custom attribute that can be set on conversations, contacts, or companies.",+ "docs_url": "https://developers.chatwoot.com/api-reference/custom-attributes/list-all-custom-attributes-in-an-account",+ "columns": {+ "id": "Unique identifier for the custom attribute definition.",+ "attribute_display_name": "Human-readable name of the attribute.",+ "attribute_key": "Key under which values are stored in custom_attributes.",+ "attribute_display_type": "Input type of the attribute (text, number, date, list, checkbox, ...).",+ "attribute_model": "What the attribute applies to: 0 conversation, 1 contact, 2 company.",+ "attribute_values": "Allowed values for list-type attributes.",+ "created_at": "When the definition was created (ISO 8601 string).",+ "updated_at": "When the definition was last updated (ISO 8601 string).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/chatwoot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/chatwoot.pynew file mode 100644index 000000000000..6dfe93f83ae1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/chatwoot.py@@ -0,0 +1,748 @@+import re+import json+import time+import dataclasses+from collections.abc import Callable, Iterator+from datetime import UTC, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import orjson+import pyarrow as pa+import requests+from asgiref.sync import async_to_sync+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.settings import (+ CHATWOOT_ENDPOINTS,+ DEFAULT_HOST,+ MESSAGE_TYPE_TO_INT,+ MESSAGES_PAGE_SIZE,+ ChatwootEndpointConfig,+ all_webhook_events,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSyncResult,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+# Safety valves against a misbehaving (customer-controlled) server that keeps returning rows:+# page-number list endpoints and the per-conversation message walk are otherwise unbounded.+MAX_LIST_PAGES = 100_000+MAX_MESSAGE_PAGES_PER_CONVERSATION = 10_000+# The message walk fans out over every conversation, so the per-conversation cap alone still lets a+# hostile server multiply requests without bound (conversations × pages). This aggregate ceiling+# bounds the total message pages one sync fetches regardless of how many conversations it enumerates.+MAX_MESSAGE_PAGES_PER_SYNC = 1_000_000++# The host is customer-controlled (self-hosted Chatwoot), so a malicious or misconfigured server+# could stream an unbounded body and exhaust a shared worker (requests buffers the whole body into+# memory by default, and the read timeout only guards idle gaps, not a steady large transfer).+MAX_RESPONSE_BYTES = 256 * 1024 * 1024+RESPONSE_CHUNK_BYTES = 256 * 1024+# requests' timeout only bounds each individual socket read, so a host that dribbles the body+# slowly could hold the connection open far longer than any read timeout while staying under+# MAX_RESPONSE_BYTES. This caps total transfer time per page.+MAX_DOWNLOAD_SECONDS = 300++HOST_NOT_ALLOWED_ERROR = "Chatwoot host is not allowed"+HTTP_NOT_ALLOWED_ERROR = "Chatwoot host must use HTTPS"+RESPONSE_TOO_LARGE_ERROR = "Chatwoot response body was too large"+RESPONSE_TOO_SLOW_ERROR = "Chatwoot response download was too slow"+INVALID_ACCOUNT_ID_ERROR = "Chatwoot account ID must be a number"++# Authority chars that let `urlparse` and the HTTP client disagree on where the host ends. A userinfo+# separator or a (raw or percent-encoded) backslash in `https://169.254.169.254\@attacker.example`+# makes `urlparse` report `attacker.example` while requests/urllib3 may connect to the internal IP —+# an SSRF bypass of the host check. No legitimate Chatwoot host carries these, so reject them outright.+_UNSAFE_URL_CHARS = re.compile(r"[\\@]|%5c|%40", re.IGNORECASE)+++class ChatwootRetryableError(Exception):+ pass+++class ChatwootHostNotAllowedError(Exception):+ pass+++class ChatwootResponseTooLargeError(Exception):+ pass+++class ChatwootResponseTooSlowError(Exception):+ pass+++class ChatwootResumeConfig:+ # Next page to fetch for page-number endpoints. Stored as a bare page number (not a URL) so+ # stale state can never replay against a different host after the source's host is edited.+ page: int | None = None+ # Messages fan-out bookmark: the conversation (display id) currently being walked, and the+ # last message id already yielded within it (the next request sends `after=<message_id>`).+ conversation_id: int | None = None+ after: int | None = None+++def normalize_host(host: str | None) -> str:+ """Turn whatever the user typed into a bare Chatwoot base URL.++ Accepts ``chatwoot.example.com``, ``https://chatwoot.example.com/``, or a URL with a+ trailing ``/api/v1`` and returns ``https://chatwoot.example.com``. Defaults to https when no+ scheme is given, and to Chatwoot Cloud when empty.+ """+ host = (host or "").strip()+ if not host:+ return DEFAULT_HOST+ if not re.match(r"^https?://", host, flags=re.IGNORECASE):+ host = f"https://{host}"+ host = host.rstrip("/")+ host = re.sub(r"/api(/v[12])?$", "", host, flags=re.IGNORECASE)+ return host.rstrip("/")+++def _host_only(host: str | None) -> str:+ return (urlparse(normalize_host(host)).hostname or "").lower()+++def _has_unsafe_url_chars(host: str | None) -> bool:+ raw = (host or "").strip()+ return bool(raw) and _UNSAFE_URL_CHARS.search(raw) is not None+++def _is_https(host: str | None) -> bool:+ # The access token rides in the api_access_token header, so refuse plaintext HTTP to keep an+ # on-path attacker from capturing it.+ return urlparse(normalize_host(host)).scheme == "https"+++def _normalize_account_id(account_id: str | int | None) -> str:+ """Chatwoot account ids are numeric; anything else would be path injection into the URL."""+ account_id_str = str(account_id or "").strip()+ if not account_id_str.isdigit():+ raise ValueError(INVALID_ACCOUNT_ID_ERROR)+ return account_id_str+++def _account_base_url(host: str | None, account_id: str | int | None) -> str:+ return f"{normalize_host(host)}/api/v1/accounts/{_normalize_account_id(account_id)}"+++def _headers(api_access_token: str) -> dict[str, str]:+ return {"api_access_token": api_access_token, "Accept": "application/json"}+++def _ensure_host_allowed(host: str | None, team_id: int) -> None:+ """Run-time host checks — not just at source-create — in case the host was edited or now+ resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud."""+ if _has_unsafe_url_chars(host):+ raise ChatwootHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)++ if not _is_https(host):+ raise ChatwootHostNotAllowedError(HTTP_NOT_ALLOWED_ERROR)++ host_ok, host_err = _is_host_safe(_host_only(host), team_id)+ if not host_ok:+ raise ChatwootHostNotAllowedError(+ f"{HOST_NOT_ALLOWED_ERROR}: {host_err}" if host_err else HOST_NOT_ALLOWED_ERROR+ )+++def _make_session(api_access_token: str) -> requests.Session:+ # allow_redirects=False: a customer-controlled host could 3xx at an internal address (SSRF).+ return make_tracked_session(+ headers=_headers(api_access_token), redact_values=(api_access_token,), allow_redirects=False+ )+++def _read_capped_body(response: requests.Response) -> bytes:+ """Stream the body into memory, aborting past MAX_RESPONSE_BYTES or MAX_DOWNLOAD_SECONDS.++ Both are non-retryable: re-fetching the same page yields the same oversized/slow body.+ """+ chunks: list[bytes] = []+ total = 0+ deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS+ try:+ for chunk in response.iter_content(chunk_size=RESPONSE_CHUNK_BYTES):+ if time.monotonic() > deadline:+ raise ChatwootResponseTooSlowError(+ f"{RESPONSE_TOO_SLOW_ERROR}: exceeded {MAX_DOWNLOAD_SECONDS}s download budget"+ )+ if not chunk:+ continue+ total += len(chunk)+ if total > MAX_RESPONSE_BYTES:+ raise ChatwootResponseTooLargeError(f"{RESPONSE_TOO_LARGE_ERROR}: exceeded {MAX_RESPONSE_BYTES} bytes")+ chunks.append(chunk)+ finally:+ response.close()+ return b"".join(chunks)+++@retry(+ retry=retry_if_exception_type((ChatwootRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_json(session: requests.Session, url: str, logger: FilteringBoundLogger) -> Any:+ # stream=True so the body isn't buffered until we cap it — see _read_capped_body.+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False, stream=True)++ # Chatwoot rate-limits at 3000 req/min per IP (rack-attack default) and returns a plain 429.+ if response.status_code == 429 or response.status_code >= 500:+ response.close()+ raise ChatwootRetryableError(f"Chatwoot API error (retryable): status={response.status_code}, url={url}")++ if response.is_redirect or response.is_permanent_redirect:+ response.close()+ raise ChatwootHostNotAllowedError(+ f"{HOST_NOT_ALLOWED_ERROR}: Chatwoot returned an unexpected redirect "+ f"(status={response.status_code}); refusing to follow it"+ )++ body = _read_capped_body(response)++ if not response.ok:+ logger.error(+ f"Chatwoot API error: status={response.status_code}, body={body.decode(errors='replace')[:500]}, url={url}"+ )+ response.raise_for_status()++ try:+ return json.loads(body or b"null")+ except ValueError:+ raise ChatwootRetryableError(f"Chatwoot returned a non-JSON payload for {url}")+++def _extract_items(data: Any, data_path: tuple[str, ...], url: str) -> list[dict[str, Any]]:+ for key in data_path:+ if not isinstance(data, dict):+ raise ChatwootRetryableError(f"Chatwoot returned an unexpected payload shape for {url}")+ data = data.get(key)+ if data is None:+ return []+ if not isinstance(data, list):+ raise ChatwootRetryableError(f"Chatwoot returned an unexpected payload shape for {url}")+ return data+++def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:+ url = f"{base_url}{path}"+ if not params:+ return url+ return f"{url}?{urlencode(params)}"+++def validate_credentials(+ host: str | None, account_id: str | int | None, api_access_token: str, team_id: int+) -> tuple[bool, str | None]:+ """Probe the agents list — the cheapest account-scoped read any user token can perform."""+ if not api_access_token:+ return False, "Missing Chatwoot API access token"++ if _has_unsafe_url_chars(host):+ return False, HOST_NOT_ALLOWED_ERROR++ try:+ base_url = _account_base_url(host, account_id)+ except ValueError:+ return False, INVALID_ACCOUNT_ID_ERROR++ if not _is_https(host):+ return False, HTTP_NOT_ALLOWED_ERROR+ host_ok, host_err = _is_host_safe(_host_only(host), team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ session = _make_session(api_access_token)+ try:+ # stream=True so a customer-controlled host can't force us to buffer an unbounded probe+ # body: we only inspect the status line here.+ response = session.get(f"{base_url}/agents", timeout=15, allow_redirects=False, stream=True)+ except Exception as e:+ return False, f"Could not connect to Chatwoot: {e}"++ try:+ if response.is_redirect or response.is_permanent_redirect:+ return False, (+ "The Chatwoot instance URL returned an unexpected redirect. Enter just your instance URL "+ "(for example https://app.chatwoot.com or https://chatwoot.example.com) and make sure it "+ "points directly at Chatwoot rather than a login or proxy page."+ )+ if response.status_code == 401:+ return False, (+ "Chatwoot rejected the credentials. Check the API access token is correct and that the "+ "token's user is a member of the configured account."+ )+ if response.status_code == 404:+ return False, "Chatwoot account not found. Check the account ID and instance URL."+ if not response.ok:+ return False, f"Chatwoot returned HTTP {response.status_code}"+ return True, None+ finally:+ response.close()+++def _iter_conversation_ids(session: requests.Session, base_url: str, logger: FilteringBoundLogger) -> Iterator[int]:+ """Page through the conversations list (ascending creation order) yielding display ids."""+ page = 1+ while page <= MAX_LIST_PAGES:+ url = _build_url(base_url, "/conversations", {"status": "all", "sort_by": "created_at_asc", "page": page})+ items = _extract_items(_fetch_json(session, url, logger), ("data", "payload"), url)+ if not items:+ return+ for item in items:+ conversation_id = item.get("id")+ if conversation_id is not None:+ yield conversation_id+ page += 1+ logger.warning(f"Chatwoot: conversations enumeration hit the {MAX_LIST_PAGES}-page cap; stopping")+++def _get_message_rows(+ session: requests.Session,+ base_url: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChatwootResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every conversation, walking each one's messages with the id-based `after` cursor.++ `after=0` returns the oldest 100 messages ascending; we advance `after` to the max id seen.+ Pages are ordered by created_at but filtered by id — within a conversation the two orders+ coincide (both are insertion order), which Chatwoot's own clients rely on too.+ """+ conversation_ids = list(_iter_conversation_ids(session, base_url, logger))++ # Resolve the saved conversation bookmark to the slice still to process. If the bookmarked+ # conversation no longer exists, start over from the first one — merge dedupes re-pulled rows+ # on the primary key.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = conversation_ids+ resume_after: int | None = None+ if resume is not None and resume.conversation_id is not None and resume.conversation_id in conversation_ids:+ remaining = conversation_ids[conversation_ids.index(resume.conversation_id) :]+ resume_after = resume.after+ logger.debug(f"Chatwoot: resuming messages from conversation_id={resume.conversation_id}, after={resume_after}")++ pages_this_sync = 0+ for index, conversation_id in enumerate(remaining):+ after = resume_after if resume_after is not None else 0+ resume_after = None # only the resumed-into conversation uses the saved cursor++ try:+ pages = 0+ while pages < MAX_MESSAGE_PAGES_PER_CONVERSATION:+ if pages_this_sync >= MAX_MESSAGE_PAGES_PER_SYNC:+ logger.warning(+ f"Chatwoot: messages hit the {MAX_MESSAGE_PAGES_PER_SYNC}-page aggregate cap; "+ "rows beyond it were skipped"+ )+ return+ pages += 1+ pages_this_sync += 1+ url = _build_url(base_url, f"/conversations/{conversation_id}/messages", {"after": after})+ items = _extract_items(_fetch_json(session, url, logger), ("payload",), url)+ if not items:+ break++ yield items++ page_max_id = max(item["id"] for item in items if item.get("id") is not None)+ if page_max_id <= after:+ break # server did not advance the cursor; bail rather than loop forever+ after = page_max_id+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —+ # merge dedupes on the primary key.+ resumable_source_manager.save_state(ChatwootResumeConfig(conversation_id=conversation_id, after=after))++ if len(items) < MESSAGES_PAGE_SIZE:+ break+ else:+ logger.warning(+ f"Chatwoot: conversation {conversation_id} hit the "+ f"{MAX_MESSAGE_PAGES_PER_CONVERSATION}-page message cap; rows beyond it were skipped"+ )+ except requests.HTTPError as exc:+ # A conversation deleted between enumeration and this fetch 404s. Skip it rather than+ # failing the whole sync. Any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Chatwoot: conversation {conversation_id} not found while fetching messages, skipping")+ else:+ raise++ # Advance the bookmark to the next conversation so a crash between conversations resumes+ # correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(ChatwootResumeConfig(conversation_id=remaining[index + 1], after=0))+++def get_rows(+ host: str | None,+ account_id: str | int | None,+ api_access_token: str,+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChatwootResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = CHATWOOT_ENDPOINTS[endpoint]+ _ensure_host_allowed(host, team_id)+ base_url = _account_base_url(host, account_id)+ # One session reused across every page so urllib3 keeps the connection alive instead of+ # re-handshaking per request.+ session = _make_session(api_access_token)++ if config.kind == "single":+ url = _build_url(base_url, config.path, dict(config.params))+ items = _extract_items(_fetch_json(session, url, logger), config.data_path, url)+ if items:+ yield items+ return++ if config.kind == "messages":+ yield from _get_message_rows(session, base_url, logger, resumable_source_manager)+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume is not None and resume.page is not None else 1+ if resume is not None:+ logger.debug(f"Chatwoot: resuming {endpoint} from page {page}")++ while page <= MAX_LIST_PAGES:+ url = _build_url(base_url, config.path, {**config.params, "page": page})+ items = _extract_items(_fetch_json(session, url, logger), config.data_path, url)+ # Page sizes are fixed server-side but env-configurable on self-hosted installs, so the+ # only reliable end-of-collection signal is an empty page.+ if not items:+ return+ yield items+ page += 1+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it.+ resumable_source_manager.save_state(ChatwootResumeConfig(page=page))+ logger.warning(f"Chatwoot: {endpoint} hit the {MAX_LIST_PAGES}-page cap; rows beyond it were skipped")+++def _iso_to_epoch(value: Any) -> Any:+ """Webhook message payloads carry created_at as an ISO string; the REST API returns unix ints.+ Normalize so webhook rows merge into the same column type."""+ if isinstance(value, str):+ try:+ return int(datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(UTC).timestamp())+ except ValueError:+ return value+ return value+++def _maybe_json_loads(value: Any) -> Any:+ """Nested webhook payload fields round-trip through parquet as JSON strings."""+ if isinstance(value, str):+ try:+ return orjson.loads(value)+ except orjson.JSONDecodeError:+ return value+ return value+++def _normalize_webhook_row(endpoint: str, row: dict[str, Any]) -> dict[str, Any] | None:+ """Reshape a webhook event body into the shape the pull path yields for `endpoint`.++ Webhook payloads put the object's attributes at the top level merged with an `event` key,+ plus `account`/`inbox` context objects the REST rows don't carry.+ """+ row = dict(row)+ row.pop("event", None)+ row.pop("account", None)+ row.pop("changed_attributes", None)++ if endpoint == "messages":+ row.pop("inbox", None)+ conversation = _maybe_json_loads(row.pop("conversation", None))+ if isinstance(conversation, dict) and row.get("conversation_id") is None:+ row["conversation_id"] = conversation.get("id")+ row["created_at"] = _iso_to_epoch(row.get("created_at"))+ message_type = row.get("message_type")+ if isinstance(message_type, str):+ row["message_type"] = MESSAGE_TYPE_TO_INT.get(message_type, message_type)++ if row.get("id") is None:+ return None+ return row+++def make_webhook_table_transformer(endpoint: str) -> Callable[[pa.Table], pa.Table]:+ def transform(table: pa.Table) -> pa.Table:+ # Deduplicate by object id, keeping the last event in arrival order (the manager reads S3+ # files oldest-first). Multiple events (e.g. conversation_created then conversation_updated)+ # can reference the same object, and delta merge doesn't dedupe within a source batch.+ best_by_id: dict[Any, dict[str, Any]] = {}+ for raw_row in table.to_pylist():+ row = _normalize_webhook_row(endpoint, raw_row)+ if row is not None:+ best_by_id[row["id"]] = row+ return table_from_py_list(list(best_by_id.values()))++ return transform+++def _list_webhooks(session: requests.Session, base_url: str, logger: FilteringBoundLogger) -> list[dict[str, Any]]:+ url = f"{base_url}/webhooks"+ data = _fetch_json(session, url, logger)+ if not isinstance(data, dict):+ return []+ payload = data.get("payload")+ if not isinstance(payload, dict):+ return []+ webhooks = payload.get("webhooks")+ return webhooks if isinstance(webhooks, list) else []+++def _find_webhook_by_url(+ session: requests.Session, base_url: str, webhook_url: str, logger: FilteringBoundLogger+) -> dict[str, Any] | None:+ return next((wh for wh in _list_webhooks(session, base_url, logger) if wh.get("url") == webhook_url), None)+++def _read_json_response(response: requests.Response, url: str, logger: FilteringBoundLogger) -> tuple[int, Any]:+ """Status + parsed JSON body for webhook-management calls, with the same redirect refusal and+ capped body read as _fetch_json — the host is customer-controlled on these paths too, so the+ body must never be buffered unbounded."""+ if response.is_redirect or response.is_permanent_redirect:+ response.close()+ raise ChatwootHostNotAllowedError(+ f"{HOST_NOT_ALLOWED_ERROR}: Chatwoot returned an unexpected redirect "+ f"(status={response.status_code}); refusing to follow it"+ )+ status = response.status_code+ body = _read_capped_body(response)+ if status >= 400:+ logger.error(f"Chatwoot API error: status={status}, body={body.decode(errors='replace')[:500]}, url={url}")+ try:+ return status, json.loads(body or b"null")+ except ValueError:+ return status, None+++def _parse_webhook_response(data: Any) -> dict[str, Any]:+ if isinstance(data, dict):+ payload = data.get("payload")+ if isinstance(payload, dict) and isinstance(payload.get("webhook"), dict):+ return payload["webhook"]+ return {}+++_WEBHOOK_PERMISSION_ERROR = (+ "Your Chatwoot API access token isn't allowed to manage webhooks — only administrator tokens "+ "can. Use an administrator's access token, or create the webhook manually."+)+++def _webhook_creation_result_from_webhook(webhook: dict[str, Any]) -> WebhookCreationResult:+ secret = webhook.get("secret")+ if secret:+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})+ # Older self-hosted Chatwoot versions have no per-webhook secret and deliver unsigned+ # payloads; the user can either fill the secret in later or enable the bypass toggle.+ return WebhookCreationResult(success=True, pending_inputs=["signing_secret"])+++def create_webhook(+ host: str | None,+ account_id: str | int | None,+ api_access_token: str,+ webhook_url: str,+ team_id: int,+ logger: FilteringBoundLogger,+) -> WebhookCreationResult:+ try:+ _ensure_host_allowed(host, team_id)+ base_url = _account_base_url(host, account_id)+ session = _make_session(api_access_token)++ body = {"webhook": {"url": webhook_url, "subscriptions": all_webhook_events()}}+ create_url = f"{base_url}/webhooks"+ response = session.post(+ create_url, json=body, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False, stream=True+ )+ status, data = _read_json_response(response, create_url, logger)++ if status in (401, 403):+ return WebhookCreationResult(success=False, error=_WEBHOOK_PERMISSION_ERROR)++ # Webhook URLs are unique per account, so re-registering after a partial setup 422s.+ # Reconcile the existing webhook instead of failing.+ if status == 422:+ existing = _find_webhook_by_url(session, base_url, webhook_url, logger)+ if existing is not None and existing.get("id") is not None:+ update_url = f"{base_url}/webhooks/{existing['id']}"+ update_response = session.patch(+ update_url, json=body, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False, stream=True+ )+ update_status, update_data = _read_json_response(update_response, update_url, logger)+ if update_status in (401, 403):+ return WebhookCreationResult(success=False, error=_WEBHOOK_PERMISSION_ERROR)+ if update_status >= 400:+ raise Exception(f"Chatwoot webhook update failed with HTTP {update_status}")+ return _webhook_creation_result_from_webhook(_parse_webhook_response(update_data) or existing)++ if status >= 400:+ raise Exception(f"Chatwoot webhook creation failed with HTTP {status}")+ return _webhook_creation_result_from_webhook(_parse_webhook_response(data))+ except Exception as e:+ logger.exception(f"Chatwoot: failed to create webhook: {e}")+ return WebhookCreationResult(success=False, error=f"Failed to create Chatwoot webhook automatically: {e}")+++def update_webhook_events(+ host: str | None,+ account_id: str | int | None,+ api_access_token: str,+ webhook_url: str,+ desired_events: list[str],+ team_id: int,+ logger: FilteringBoundLogger,+) -> WebhookSyncResult:+ try:+ _ensure_host_allowed(host, team_id)+ base_url = _account_base_url(host, account_id)+ session = _make_session(api_access_token)++ existing = _find_webhook_by_url(session, base_url, webhook_url, logger)+ if existing is None or existing.get("id") is None:+ return WebhookSyncResult(success=False, error="No Chatwoot webhook found for this source's webhook URL.")++ if sorted(existing.get("subscriptions") or []) == sorted(desired_events):+ return WebhookSyncResult(success=True)++ update_url = f"{base_url}/webhooks/{existing['id']}"+ response = session.patch(+ update_url,+ json={"webhook": {"url": webhook_url, "subscriptions": desired_events}},+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ stream=True,+ )+ status, _ = _read_json_response(response, update_url, logger)+ if status in (401, 403):+ return WebhookSyncResult(success=False, error=_WEBHOOK_PERMISSION_ERROR)+ if status >= 400:+ raise Exception(f"Chatwoot webhook update failed with HTTP {status}")+ return WebhookSyncResult(success=True)+ except Exception as e:+ logger.exception(f"Chatwoot: failed to sync webhook events: {e}")+ return WebhookSyncResult(success=False, error=f"Failed to update Chatwoot webhook events: {e}")+++def get_external_webhook_info(+ host: str | None,+ account_id: str | int | None,+ api_access_token: str,+ webhook_url: str,+ team_id: int,+ logger: FilteringBoundLogger,+) -> ExternalWebhookInfo:+ try:+ _ensure_host_allowed(host, team_id)+ base_url = _account_base_url(host, account_id)+ session = _make_session(api_access_token)++ existing = _find_webhook_by_url(session, base_url, webhook_url, logger)+ if existing is None:+ return ExternalWebhookInfo(exists=False)+ return ExternalWebhookInfo(+ exists=True,+ url=existing.get("url"),+ enabled_events=existing.get("subscriptions"),+ status="enabled",+ )+ except Exception as e:+ return ExternalWebhookInfo(exists=False, error=f"Failed to check Chatwoot webhook: {e}")+++def delete_webhook(+ host: str | None,+ account_id: str | int | None,+ api_access_token: str,+ webhook_url: str,+ team_id: int,+ logger: FilteringBoundLogger,+) -> WebhookDeletionResult:+ try:+ _ensure_host_allowed(host, team_id)+ base_url = _account_base_url(host, account_id)+ session = _make_session(api_access_token)++ existing = _find_webhook_by_url(session, base_url, webhook_url, logger)+ if existing is None or existing.get("id") is None:+ # Nothing to delete — the desired end state already holds.+ return WebhookDeletionResult(success=True)++ delete_url = f"{base_url}/webhooks/{existing['id']}"+ response = session.delete(delete_url, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False, stream=True)+ status, _ = _read_json_response(response, delete_url, logger)+ if status in (401, 403):+ return WebhookDeletionResult(success=False, error=_WEBHOOK_PERMISSION_ERROR)+ if status >= 400:+ raise Exception(f"Chatwoot webhook deletion failed with HTTP {status}")+ return WebhookDeletionResult(success=True)+ except Exception as e:+ logger.exception(f"Chatwoot: failed to delete webhook: {e}")+ return WebhookDeletionResult(success=False, error=f"Failed to delete Chatwoot webhook: {e}")+++def chatwoot_source(+ host: str | None,+ account_id: str | int | None,+ api_access_token: str,+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChatwootResumeConfig],+ webhook_source_manager: Optional[WebhookSourceManager] = None,+) -> SourceResponse:+ config: ChatwootEndpointConfig = CHATWOOT_ENDPOINTS[endpoint]++ webhook_enabled = (+ async_to_sync(webhook_source_manager.webhook_enabled)()+ if webhook_source_manager is not None and config.supports_webhooks+ else False+ )++ def items():+ if webhook_enabled and webhook_source_manager is not None:+ return webhook_source_manager.get_items(table_transformer=make_webhook_table_transformer(endpoint))++ return get_rows(+ host=host,+ account_id=account_id,+ api_access_token=api_access_token,+ endpoint=endpoint,+ team_id=team_id,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ )++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=config.primary_keys,+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/settings.pynew file mode 100644index 000000000000..7b3edb5a0da7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/settings.py@@ -0,0 +1,126 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++DEFAULT_HOST = "https://app.chatwoot.com"++# Server-side fixed page sizes — Chatwoot exposes no per-page override param.+CONTACTS_PAGE_SIZE = 15+# `after`-cursor pages on the messages endpoint return up to 100 rows (MessageFinder#messages_after).+MESSAGES_PAGE_SIZE = 100++# The REST API returns `message_type` as an integer enum; webhook payloads carry the string form.+MESSAGE_TYPE_TO_INT = {"incoming": 0, "outgoing": 1, "activity": 2, "template": 3}+++@dataclass+class ChatwootEndpointConfig:+ name: str+ # Path under /api/v1/accounts/{account_id}.+ path: str+ # "paged": page-number list. "single": one unpaginated response. "messages": the+ # per-conversation fan-out with an id-based `after` cursor.+ kind: Literal["paged", "single", "messages"]+ # Where the row list lives in the response body; () means the body is a bare JSON array.+ data_path: tuple[str, ...] = ()+ # Query params sent on every request.+ params: dict[str, str] = field(default_factory=dict)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field for datetime partitioning (unix epoch ints in Chatwoot list+ # responses). Never an updated_at-style field.+ partition_key: Optional[str] = None+ supports_webhooks: bool = False+ description: Optional[str] = None+++# No endpoint here declares incremental sync: Chatwoot's list endpoints expose no server-side+# timestamp filter (no updated_since/created_since), so every pull is a full walk. Webhooks are+# the delta path for conversations and messages.+CHATWOOT_ENDPOINTS: dict[str, ChatwootEndpointConfig] = {+ "conversations": ChatwootEndpointConfig(+ name="conversations",+ path="/conversations",+ kind="paged",+ data_path=("data", "payload"),+ # `status` defaults to "open" server-side; "all" disables the filter. created_at_asc keeps+ # page-number pagination stable while new conversations arrive mid-sync (new rows append+ # to the tail instead of reshuffling already-fetched pages).+ params={"status": "all", "sort_by": "created_at_asc"},+ partition_key="created_at",+ supports_webhooks=True,+ description="One row per conversation. The id column is Chatwoot's per-account display id.",+ ),+ "messages": ChatwootEndpointConfig(+ name="messages",+ path="/conversations/{conversation_id}/messages",+ kind="messages",+ data_path=("payload",),+ partition_key="created_at",+ supports_webhooks=True,+ description=(+ "Conversation messages, fetched per conversation — a full sync issues at least one "+ "request per conversation, so large accounts can take a while. Webhook sync avoids "+ "the re-walk after the initial backfill."+ ),+ ),+ "contacts": ChatwootEndpointConfig(+ name="contacts",+ path="/contacts",+ kind="paged",+ data_path=("payload",),+ # Ascending creation order keeps page-number pagination stable mid-sync.+ params={"sort": "created_at"},+ partition_key="created_at",+ description=(+ "Contacts with an email, phone number, or identifier. Chatwoot's contact list "+ "excludes anonymous web-widget visitors."+ ),+ ),+ "inboxes": ChatwootEndpointConfig(+ name="inboxes",+ path="/inboxes",+ kind="single",+ data_path=("payload",),+ ),+ "agents": ChatwootEndpointConfig(+ name="agents",+ path="/agents",+ kind="single",+ ),+ "teams": ChatwootEndpointConfig(+ name="teams",+ path="/teams",+ kind="single",+ ),+ "labels": ChatwootEndpointConfig(+ name="labels",+ path="/labels",+ kind="single",+ data_path=("payload",),+ ),+ "custom_attribute_definitions": ChatwootEndpointConfig(+ name="custom_attribute_definitions",+ path="/custom_attribute_definitions",+ kind="single",+ description="Custom attribute definitions for conversations, contacts, and companies.",+ ),+}++ENDPOINTS = tuple(CHATWOOT_ENDPOINTS.keys())++# Maps our schema names to the object type a webhook event carries. The webhook template derives+# the object type from the event name prefix (message_created -> "message").+RESOURCE_TO_WEBHOOK_OBJECT_TYPE: dict[str, str] = {+ "conversations": "conversation",+ "messages": "message",+}++RESOURCE_TO_WEBHOOK_EVENTS: dict[str, list[str]] = {+ "conversations": ["conversation_created", "conversation_updated", "conversation_status_changed"],+ "messages": ["message_created", "message_updated"],+}+++def all_webhook_events() -> list[str]:+ """Every event we can map to a schema. Re-derived on each reconcile so webhooks created+ before the map grew are auto-healed."""+ return [event for events in RESOURCE_TO_WEBHOOK_EVENTS.values() for event in events]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/source.pyindex 6a82d331c354..123641ecc31e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/source.py@@ -1,30 +1,278 @@-from typing import cast+from typing import TYPE_CHECKING, Optional, cast++import structlog++if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDCfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot import (+ HOST_NOT_ALLOWED_ERROR,+ HTTP_NOT_ALLOWED_ERROR,+ INVALID_ACCOUNT_ID_ERROR,+ RESPONSE_TOO_LARGE_ERROR,+ RESPONSE_TOO_SLOW_ERROR,+ ChatwootResumeConfig,+ chatwoot_source,+ create_webhook as create_chatwoot_webhook,+ delete_webhook as delete_chatwoot_webhook,+ get_external_webhook_info as get_chatwoot_webhook_info,+ update_webhook_events as update_chatwoot_webhook_events,+ validate_credentials as validate_chatwoot_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.settings import (+ CHATWOOT_ENDPOINTS,+ ENDPOINTS,+ RESOURCE_TO_WEBHOOK_OBJECT_TYPE,+ all_webhook_events,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ FieldType,+ ResumableSource,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSource,+ WebhookSyncResult,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ChatwootSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+# Webhook management calls run in the API request path where no job logger exists.+logger = structlog.get_logger(__name__)+@SourceRegistry.register-class ChatwootSource(SimpleSource[ChatwootSourceConfig]):+class ChatwootSource(+ ResumableSource[ChatwootSourceConfig, ChatwootResumeConfig],+ WebhookSource[ChatwootSourceConfig],+):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CHATWOOT+ @property+ def connection_host_fields(self) -> list[str]:+ # `host` determines where the stored access token is sent, and `account_id` selects which+ # Chatwoot account it reads — a single user token can belong to several accounts, so+ # retargeting either must re-require the token rather than reusing the preserved one.+ return ["host", "account_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CHATWOOT,category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="Chatwoot",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Sync conversations, messages, contacts, agents, and more from Chatwoot into the PostHog Data warehouse.++Copy your API access token from **Profile settings → Access token** in Chatwoot. Use an administrator's token: agent tokens only see their assigned inboxes, and only administrators can manage webhooks.++Your account ID is the number in your Chatwoot URL, e.g. `app.chatwoot.com/app/accounts/<account ID>`.++For self-hosted Chatwoot, set your instance URL (for example `https://chatwoot.example.com`); leave it empty for Chatwoot Cloud.""",iconPath="/static/services/chatwoot.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/chatwoot",+ keywords=["live chat", "helpdesk", "customer support"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="host",+ label="Chatwoot instance URL",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://app.chatwoot.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="account_id",+ label="Account ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="1",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_access_token",+ label="API access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ webhookSetupCaption="""To set up the webhook manually:++1. In Chatwoot, go to **Settings → Integrations → Webhooks** and click **Configure**+2. Click **Add new webhook** and paste the webhook URL shown below+3. Subscribe to the conversation and message events (`conversation_created`, `conversation_updated`, `conversation_status_changed`, `message_created`, `message_updated`)++Recent Chatwoot versions sign deliveries with a per-webhook secret — fetch it from `GET /api/v1/accounts/{account_id}/webhooks` and paste it into the signing secret field below. Older self-hosted versions do not sign deliveries; enable the bypass toggle on the webhook function instead.++If automatic creation failed, note that only Chatwoot administrators can manage webhooks — use an administrator's API access token.""",+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="signing_secret",+ label="Signing secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.webhook_template import ( # noqa: PLC0415+ template,+ )++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return RESOURCE_TO_WEBHOOK_OBJECT_TYPE++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # The base URL is installation-specific, so match on the stable status text rather than a+ # fixed host. Fan-out 404s (a conversation deleted mid-sync) are skipped in the transport,+ # so a surviving 404 means the account ID or instance URL is wrong.+ return {+ "401 Client Error": "Chatwoot rejected your API access token. Check the token is correct, has not been revoked, and belongs to a member of the configured account, then reconnect.",+ "403 Client Error": "Your Chatwoot API access token does not have permission to read this data. Use an administrator's access token, then reconnect.",+ "404 Client Error": "Chatwoot could not find the configured account. Check the account ID and instance URL, then reconnect.",+ INVALID_ACCOUNT_ID_ERROR: "The Chatwoot account ID must be a number (the number in your Chatwoot URL, e.g. app.chatwoot.com/app/accounts/1). Update the source configuration.",+ HOST_NOT_ALLOWED_ERROR: "The Chatwoot host is not allowed. Please use a publicly reachable instance URL.",+ HTTP_NOT_ALLOWED_ERROR: "The Chatwoot host must use HTTPS. Please update the instance URL to use https://.",+ RESPONSE_TOO_LARGE_ERROR: "Chatwoot returned a response that was too large to process. Please contact support if this persists.",+ RESPONSE_TOO_SLOW_ERROR: "Chatwoot took too long to send a response. Check that the instance URL points at a healthy Chatwoot server, then try again.",+ }++ def get_schemas(+ self,+ config: ChatwootSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Chatwoot's list endpoints expose no server-side timestamp filter, so every schema is+ # full refresh; conversations and messages additionally support webhook-fed deltas.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ supports_webhooks=CHATWOOT_ENDPOINTS[endpoint].supports_webhooks,+ description=CHATWOOT_ENDPOINTS[endpoint].description,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: ChatwootSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The user token grants access to the whole account, so one probe validates every schema.+ return validate_chatwoot_credentials(config.host, config.account_id, config.api_access_token, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ChatwootResumeConfig]:+ return ResumableSourceManager[ChatwootResumeConfig](inputs, ChatwootResumeConfig)++ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ def create_webhook(self, config: ChatwootSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:+ return create_chatwoot_webhook(+ config.host, config.account_id, config.api_access_token, webhook_url, team_id, logger+ )++ def get_desired_webhook_events(+ self, config: ChatwootSourceConfig, eligible_schema_names: list[str]+ ) -> list[str] | None:+ # Every mappable event, not just the selected tables — auto-heals webhooks created before+ # RESOURCE_TO_WEBHOOK_EVENTS gained new resources.+ return all_webhook_events()++ def sync_webhook_events(+ self,+ config: ChatwootSourceConfig,+ webhook_url: str,+ team_id: int,+ eligible_schema_names: list[str],+ ) -> WebhookSyncResult:+ desired_events = self.get_desired_webhook_events(config, eligible_schema_names) or []+ return update_chatwoot_webhook_events(+ config.host, config.account_id, config.api_access_token, webhook_url, desired_events, team_id, logger+ )++ def get_external_webhook_info(+ self, config: ChatwootSourceConfig, webhook_url: str, team_id: int+ ) -> ExternalWebhookInfo:+ return get_chatwoot_webhook_info(+ config.host, config.account_id, config.api_access_token, webhook_url, team_id, logger+ )++ def delete_webhook(self, config: ChatwootSourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:+ return delete_chatwoot_webhook(+ config.host, config.account_id, config.api_access_token, webhook_url, team_id, logger+ )++ def source_for_pipeline(+ self,+ config: ChatwootSourceConfig,+ resumable_source_manager: ResumableSourceManager[ChatwootResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in CHATWOOT_ENDPOINTS:+ raise ValueError(f"Unknown Chatwoot schema '{inputs.schema_name}'")++ return chatwoot_source(+ host=config.host,+ account_id=config.account_id,+ api_access_token=config.api_access_token,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ webhook_source_manager=self.get_webhook_source_manager(inputs),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot.pynew file mode 100644index 000000000000..2290e0ee177e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot.py@@ -0,0 +1,509 @@+import json+from typing import Any++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot import (+ ChatwootResumeConfig,+ _normalize_account_id,+ chatwoot_source,+ create_webhook,+ delete_webhook,+ get_rows,+ make_webhook_table_transformer,+ normalize_host,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.settings import (+ CHATWOOT_ENDPOINTS,+ ENDPOINTS,+ MESSAGES_PAGE_SIZE,+)++TEAM_ID = 1+++def _make_manager(resume_state: ChatwootResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _resp(payload: Any, status: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = status+ resp.ok = status < 400+ resp.is_redirect = False+ resp.is_permanent_redirect = False+ resp.iter_content.return_value = [json.dumps(payload).encode()]+ resp.json.return_value = payload+ if status >= 400:+ resp.raise_for_status.side_effect = requests.HTTPError(f"{status} Client Error", response=resp)+ return resp+++def _conversations_page(items: list[dict[str, Any]]) -> dict[str, Any]:+ return {"data": {"meta": {}, "payload": items}}+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ "host, expected",+ [+ (None, "https://app.chatwoot.com"),+ ("", "https://app.chatwoot.com"),+ ("chatwoot.example.com", "https://chatwoot.example.com"),+ ("https://chatwoot.example.com/", "https://chatwoot.example.com"),+ ("https://chatwoot.example.com/api/v1", "https://chatwoot.example.com"),+ ("http://chatwoot.example.com", "http://chatwoot.example.com"),+ ],+ )+ def test_normalize_host(self, host, expected):+ assert normalize_host(host) == expected+++class TestNormalizeAccountId:+ @pytest.mark.parametrize("account_id", ["1", 42, " 7 "])+ def test_accepts_numeric(self, account_id):+ assert _normalize_account_id(account_id).isdigit()++ @pytest.mark.parametrize("account_id", ["", None, "1/../2", "abc", "1?x=1"])+ def test_rejects_non_numeric(self, account_id):+ with pytest.raises(ValueError):+ _normalize_account_id(account_id)+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected_valid",+ [(200, True), (401, False), (404, False), (500, False)],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_status_mapping(self, mock_session, status_code, expected_valid):+ mock_session.return_value.get.return_value = _resp([], status=status_code)++ is_valid, _ = validate_credentials(None, "1", "token", TEAM_ID)++ assert is_valid is expected_valid++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_connection_error_is_reported_not_raised(self, mock_session):+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")++ is_valid, message = validate_credentials(None, "1", "token", TEAM_ID)++ assert is_valid is False+ assert message is not None and "Could not connect" in message++ def test_plain_http_host_is_rejected(self):+ is_valid, message = validate_credentials("http://chatwoot.internal", "1", "token", TEAM_ID)++ assert is_valid is False+ assert message is not None and "HTTPS" in message++ def test_non_numeric_account_id_is_rejected_without_a_request(self):+ is_valid, message = validate_credentials(None, "not-a-number", "token", TEAM_ID)++ assert is_valid is False+ assert message is not None and "number" in message++ @pytest.mark.parametrize(+ "host",+ [+ "https://169.254.169.254\\@attacker.example",+ "https://[email protected]",+ "https://169.254.169.254%[email protected]",+ "https://169.254.169.254%40attacker.example",+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_authority_ambiguous_host_is_rejected_without_a_request(self, mock_session, host):+ # urlparse and the HTTP client disagree on where the host ends, so these must be rejected+ # before any request — otherwise the host allowlist is an SSRF bypass.+ is_valid, message = validate_credentials(host, "1", "token", TEAM_ID)++ assert is_valid is False+ assert message is not None+ mock_session.return_value.get.assert_not_called()+++class TestGetRowsPaged:+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_conversations_walks_pages_with_status_all_until_empty(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp(_conversations_page([{"id": 1}, {"id": 2}])),+ _resp(_conversations_page([{"id": 3}])),+ _resp(_conversations_page([])),+ ]+ manager = _make_manager()++ batches = list(get_rows(None, "1", "token", "conversations", TEAM_ID, mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == [1, 2, 3]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ # status defaults to "open" server-side — dropping status=all would silently sync a subset.+ assert all("status=all" in url and "sort_by=created_at_asc" in url for url in urls)+ assert ["page=1" in urls[0], "page=2" in urls[1], "page=3" in urls[2]] == [True, True, True]+ # State is saved after each yielded page, pointing at the next page; the empty final+ # page yields nothing and saves nothing.+ assert [call.args[0].page for call in manager.save_state.call_args_list] == [2, 3]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_resumes_from_saved_page(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp({"meta": {}, "payload": [{"id": 9}]}),+ _resp({"meta": {}, "payload": []}),+ ]+ manager = _make_manager(ChatwootResumeConfig(page=5))++ list(get_rows(None, "1", "token", "contacts", TEAM_ID, mock.MagicMock(), manager))++ assert "page=5" in mock_session.return_value.get.call_args_list[0].args[0]++ @pytest.mark.parametrize(+ "endpoint, payload, expected_ids",+ [+ ("agents", [{"id": 1}, {"id": 2}], [1, 2]),+ ("teams", [{"id": 3}], [3]),+ ("custom_attribute_definitions", [{"id": 4}], [4]),+ ("labels", {"payload": [{"id": 5}]}, [5]),+ ("inboxes", {"payload": [{"id": 6}]}, [6]),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_single_endpoints_yield_once_without_pagination(self, mock_session, endpoint, payload, expected_ids):+ mock_session.return_value.get.return_value = _resp(payload)+ manager = _make_manager()++ batches = list(get_rows(None, "1", "token", endpoint, TEAM_ID, mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == expected_ids+ assert mock_session.return_value.get.call_count == 1+ manager.save_state.assert_not_called()++ def test_plain_http_host_raises(self):+ with pytest.raises(Exception, match="HTTPS"):+ list(+ get_rows("http://chatwoot.internal", "1", "token", "agents", TEAM_ID, mock.MagicMock(), _make_manager())+ )++ def test_authority_ambiguous_host_raises(self):+ with pytest.raises(Exception, match="not allowed"):+ list(+ get_rows(+ "https://169.254.169.254\\@attacker.example",+ "1",+ "token",+ "agents",+ TEAM_ID,+ mock.MagicMock(),+ _make_manager(),+ )+ )+++class TestGetRowsMessages:+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_fans_out_over_conversations_with_after_cursor(self, mock_session):+ full_page = [{"id": 100 + i} for i in range(MESSAGES_PAGE_SIZE)]+ mock_session.return_value.get.side_effect = [+ _resp(_conversations_page([{"id": 1}, {"id": 2}])),+ _resp(_conversations_page([])),+ # Conversation 1: one full page, then a short page ends it.+ _resp({"meta": {}, "payload": full_page}),+ _resp({"meta": {}, "payload": [{"id": 300}]}),+ # Conversation 2: single short page.+ _resp({"meta": {}, "payload": [{"id": 400}]}),+ ]+ manager = _make_manager()++ batches = list(get_rows(None, "1", "token", "messages", TEAM_ID, mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == [*[m["id"] for m in full_page], 300, 400]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert urls[2].endswith("/conversations/1/messages?after=0")+ assert urls[3].endswith(f"/conversations/1/messages?after={full_page[-1]['id']}")+ assert urls[4].endswith("/conversations/2/messages?after=0")+ # Cursor state saved after each yielded page; bookmark advanced to the next conversation.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert (saved[0].conversation_id, saved[0].after) == (1, full_page[-1]["id"])+ assert any(state.conversation_id == 2 and state.after == 0 for state in saved)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_deleted_conversation_404_is_skipped(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp(_conversations_page([{"id": 1}, {"id": 2}])),+ _resp(_conversations_page([])),+ _resp({"error": "Resource could not be found"}, status=404),+ _resp({"meta": {}, "payload": [{"id": 400}]}),+ ]+ manager = _make_manager()++ batches = list(get_rows(None, "1", "token", "messages", TEAM_ID, mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == [400]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.MAX_MESSAGE_PAGES_PER_SYNC",+ 2,+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_message_walk_stops_at_the_aggregate_page_cap(self, mock_session):+ # A hostile server can keep returning full, advancing pages; the per-conversation cap alone+ # would still let conversation count multiply requests without bound, so the walk must stop+ # once the aggregate page budget is spent rather than fanning out further.+ page_one = [{"id": 100 + i} for i in range(MESSAGES_PAGE_SIZE)]+ page_two = [{"id": 200 + i} for i in range(MESSAGES_PAGE_SIZE)]+ mock_session.return_value.get.side_effect = [+ _resp(_conversations_page([{"id": 1}, {"id": 2}])),+ _resp(_conversations_page([])),+ _resp({"meta": {}, "payload": page_one}),+ _resp({"meta": {}, "payload": page_two}),+ # A third message page would be fetched without the aggregate cap; it must not be.+ _resp({"meta": {}, "payload": [{"id": 999}]}),+ ]+ manager = _make_manager()++ batches = list(get_rows(None, "1", "token", "messages", TEAM_ID, mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == [+ *[m["id"] for m in page_one],+ *[m["id"] for m in page_two],+ ]+ message_urls = [+ call.args[0] for call in mock_session.return_value.get.call_args_list if "/messages" in call.args[0]+ ]+ assert len(message_urls) == 2+ assert not any("/conversations/2/messages" in url for url in message_urls)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_resumes_from_bookmarked_conversation_and_cursor(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp(_conversations_page([{"id": 1}, {"id": 2}])),+ _resp(_conversations_page([])),+ _resp({"meta": {}, "payload": [{"id": 25}]}),+ ]+ manager = _make_manager(ChatwootResumeConfig(conversation_id=2, after=20))++ batches = list(get_rows(None, "1", "token", "messages", TEAM_ID, mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == [25]+ message_urls = [+ call.args[0] for call in mock_session.return_value.get.call_args_list if "/messages" in call.args[0]+ ]+ assert message_urls == ["https://app.chatwoot.com/api/v1/accounts/1/conversations/2/messages?after=20"]+++class TestWebhookTableTransformer:+ def test_message_events_are_normalized_to_the_rest_shape(self):+ transform = make_webhook_table_transformer("messages")+ table = table_from_py_list(+ [+ {+ "event": "message_created",+ "id": 10,+ "content": "hi",+ "message_type": "incoming",+ "created_at": "2026-01-02T03:04:05.000Z",+ "conversation": {"id": 7, "status": "open"},+ "account": {"id": 1, "name": "acme"},+ "inbox": {"id": 2, "name": "support"},+ },+ {+ "event": "message_updated",+ "id": 10,+ "content": "hi (edited)",+ "message_type": "incoming",+ "created_at": "2026-01-02T03:04:05.000Z",+ "conversation": {"id": 7, "status": "open"},+ "account": {"id": 1, "name": "acme"},+ "inbox": {"id": 2, "name": "support"},+ },+ ]+ )++ rows = transform(table).to_pylist()++ # Deduped within the batch, keeping the latest event for the id.+ assert len(rows) == 1+ row = rows[0]+ assert row["content"] == "hi (edited)"+ assert row["conversation_id"] == 7+ # REST returns message_type as an int and created_at as a unix int; webhook rows must+ # merge into the same column types.+ assert row["message_type"] == 0+ assert row["created_at"] == 1767323045+ assert "event" not in row and "account" not in row and "conversation" not in row and "inbox" not in row++ def test_conversation_events_drop_event_context_keys(self):+ transform = make_webhook_table_transformer("conversations")+ table = table_from_py_list(+ [+ {+ "event": "conversation_status_changed",+ "id": 5,+ "status": "resolved",+ "created_at": 1767323045,+ "account": {"id": 1, "name": "acme"},+ "changed_attributes": [{"status": {"current_value": "resolved", "previous_value": "open"}}],+ }+ ]+ )++ rows = transform(table).to_pylist()++ assert rows == [{"id": 5, "status": "resolved", "created_at": 1767323045}]++ def test_rows_without_an_id_are_dropped(self):+ transform = make_webhook_table_transformer("conversations")+ table = table_from_py_list([{"event": "conversation_created", "status": "open", "id": None}])++ assert transform(table).num_rows == 0+++class TestWebhookManagement:+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_create_webhook_returns_signing_secret_as_extra_input(self, mock_session):+ mock_session.return_value.post.return_value = _resp(+ {"payload": {"webhook": {"id": 3, "url": "https://ph/webhook", "secret": "s3cret"}}}+ )++ result = create_webhook(None, "1", "token", "https://ph/webhook", TEAM_ID, mock.MagicMock())++ assert result.success is True+ assert result.extra_inputs == {"signing_secret": "s3cret"}+ assert result.pending_inputs == []+ body = mock_session.return_value.post.call_args.kwargs["json"]+ assert body["webhook"]["url"] == "https://ph/webhook"+ assert set(body["webhook"]["subscriptions"]) == {+ "conversation_created",+ "conversation_updated",+ "conversation_status_changed",+ "message_created",+ "message_updated",+ }++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_create_webhook_without_secret_marks_signing_secret_pending(self, mock_session):+ # Older self-hosted Chatwoot versions have no per-webhook secret.+ mock_session.return_value.post.return_value = _resp(+ {"payload": {"webhook": {"id": 3, "url": "https://ph/webhook"}}}+ )++ result = create_webhook(None, "1", "token", "https://ph/webhook", TEAM_ID, mock.MagicMock())++ assert result.success is True+ assert result.pending_inputs == ["signing_secret"]++ @pytest.mark.parametrize("status", [401, 403])+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_create_webhook_permission_error_is_actionable(self, mock_session, status):+ mock_session.return_value.post.return_value = _resp({"error": "nope"}, status=status)++ result = create_webhook(None, "1", "token", "https://ph/webhook", TEAM_ID, mock.MagicMock())++ assert result.success is False+ assert result.error is not None and "administrator" in result.error++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_create_webhook_reconciles_existing_webhook_on_422(self, mock_session):+ # Webhook URLs are unique per account: a partial earlier setup 422s on re-create.+ mock_session.return_value.post.return_value = _resp({"message": "URL has already been taken"}, status=422)+ mock_session.return_value.get.return_value = _resp(+ {"payload": {"webhooks": [{"id": 9, "url": "https://ph/webhook", "subscriptions": ["message_created"]}]}}+ )+ mock_session.return_value.patch.return_value = _resp(+ {"payload": {"webhook": {"id": 9, "url": "https://ph/webhook", "secret": "s3cret"}}}+ )++ result = create_webhook(None, "1", "token", "https://ph/webhook", TEAM_ID, mock.MagicMock())++ assert result.success is True+ assert result.extra_inputs == {"signing_secret": "s3cret"}+ assert "/webhooks/9" in mock_session.return_value.patch.call_args.args[0]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_delete_webhook_is_a_noop_success_when_absent(self, mock_session):+ mock_session.return_value.get.return_value = _resp({"payload": {"webhooks": []}})++ result = delete_webhook(None, "1", "token", "https://ph/webhook", TEAM_ID, mock.MagicMock())++ assert result.success is True+ mock_session.return_value.delete.assert_not_called()+++class TestChatwootSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = CHATWOOT_ENDPOINTS[endpoint]+ response = chatwoot_source(+ None, "1", "token", endpoint, TEAM_ID, mock.MagicMock(), _make_manager(), webhook_source_manager=None+ )++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize("config", list(CHATWOOT_ENDPOINTS.values()))+ def test_partition_keys_are_stable_creation_fields(self, config):+ if config.partition_key:+ assert config.partition_key == "created_at"++ def test_webhook_enabled_schema_reads_from_webhook_manager(self):+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=True)++ response = chatwoot_source(+ None, "1", "token", "conversations", TEAM_ID, mock.MagicMock(), _make_manager(), webhook_manager+ )+ response.items()++ webhook_manager.get_items.assert_called_once()++ def test_webhook_manager_not_consulted_for_non_webhook_schema(self):+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=True)++ chatwoot_source(None, "1", "token", "agents", TEAM_ID, mock.MagicMock(), _make_manager(), webhook_manager)++ webhook_manager.webhook_enabled.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot_source.pynew file mode 100644index 000000000000..f5fbc5b83908--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot_source.py@@ -0,0 +1,162 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot import ChatwootResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.source import ChatwootSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ChatwootSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestChatwootSource:+ def setup_method(self):+ self.source = ChatwootSource()+ self.team_id = 123+ self.config = ChatwootSourceConfig(account_id="7", api_access_token="token", host="https://chat.example.com")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CHATWOOT++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Chatwoot"+ assert config.label == "Chatwoot"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/chatwoot.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["host", "account_id", "api_access_token"]++ def test_access_token_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_access_token"+ )+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ def test_host_and_account_are_connection_host_fields(self):+ # Retargeting the host could exfiltrate the stored token to an attacker-controlled server,+ # and changing the account id alone could point a shared token at another account's data —+ # both must force re-entering the token.+ assert self.source.connection_host_fields == ["host", "account_id"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://chat.example.com/api/v1/accounts/7/contacts?page=1",+ "404 Client Error: Not Found for url: https://app.chatwoot.com/api/v1/accounts/999/agents",+ "Chatwoot host must use HTTPS",+ "Chatwoot account ID must be a number",+ ],+ )+ def test_non_retryable_errors_match_permanent_failures(self, observed_error):+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ def test_non_retryable_errors_do_not_match_transient_failures(self):+ transient = "500 Server Error for url: https://app.chatwoot.com/api/v1/accounts/1/contacts"+ assert not any(key in transient for key in self.source.get_non_retryable_errors())++ def test_get_schemas_are_full_refresh_with_webhook_deltas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # No Chatwoot list endpoint has a server-side timestamp filter, so nothing may advertise+ # incremental sync.+ assert not any(schema.supports_incremental or schema.supports_append for schema in schemas)+ assert {schema.name for schema in schemas if schema.supports_webhooks} == {"conversations", "messages"}++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["contacts"])+ assert [schema.name for schema in schemas] == ["contacts"]++ @pytest.mark.parametrize(+ "mock_return",+ [(True, None), (False, "Chatwoot account not found. Check the account ID and instance URL.")],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.source.validate_chatwoot_credentials"+ )+ def test_validate_credentials_plumbs_config(self, mock_validate, mock_return):+ mock_validate.return_value = mock_return++ assert self.source.validate_credentials(self.config, self.team_id) == mock_return+ mock_validate.assert_called_once_with(+ self.config.host, self.config.account_id, self.config.api_access_token, self.team_id+ )++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ChatwootResumeConfig++ def test_webhook_resource_map_covers_webhook_schemas(self):+ assert self.source.webhook_resource_map == {"conversations": "conversation", "messages": "message"}++ def test_webhook_template_routes_by_event_prefix(self):+ template = self.source.webhook_template++ assert template is not None+ assert template.type == "warehouse_source_webhook"+ assert template.id == "template-warehouse-source-chatwoot"+ input_keys = {schema_input["key"] for schema_input in template.inputs_schema or []}+ assert {"signing_secret", "bypass_signature_check", "schema_mapping", "source_id"} <= input_keys++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.source.create_chatwoot_webhook"+ )+ def test_create_webhook_plumbs_config(self, mock_create):+ self.source.create_webhook(self.config, "https://ph/webhook", self.team_id)++ args = mock_create.call_args.args+ assert args[:5] == (+ self.config.host,+ self.config.account_id,+ self.config.api_access_token,+ "https://ph/webhook",+ self.team_id,+ )++ def test_desired_webhook_events_cover_all_mapped_events(self):+ events = self.source.get_desired_webhook_events(self.config, ["conversations"])++ assert events is not None+ assert set(events) == {+ "conversation_created",+ "conversation_updated",+ "conversation_status_changed",+ "message_created",+ "message_updated",+ }++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.source.chatwoot_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_chatwoot_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "conversations"+ inputs.team_id = self.team_id+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_chatwoot_source.call_args.kwargs+ assert kwargs["host"] == self.config.host+ assert kwargs["account_id"] == "7"+ assert kwargs["api_access_token"] == "token"+ assert kwargs["endpoint"] == "conversations"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["webhook_source_manager"] is not None++ def test_source_for_pipeline_rejects_unknown_schema(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "not-a-schema"++ with pytest.raises(ValueError, match="Unknown Chatwoot schema"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/webhook_template.pynew file mode 100644index 000000000000..7f5be8147cdc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/webhook_template.py@@ -0,0 +1,150 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++# Chatwoot signs deliveries (recent versions) with X-Chatwoot-Signature: sha256=<hex hmac-sha256 of+# "<X-Chatwoot-Timestamp>.<raw body>">. Older self-hosted installs have no per-webhook secret and+# deliver unsigned — those users must enable bypass_signature_check explicitly.+template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-chatwoot",+ name="Chatwoot warehouse source webhook",+ description="Receive Chatwoot webhook events for data warehouse ingestion",+ icon_url="/static/services/chatwoot.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""\+if (request.method != 'POST') {+ return {+ 'httpResponse': {+ 'status': 405,+ 'body': 'Method not allowed'+ }+ }+}++if (not inputs.bypass_signature_check) {+ if (empty(inputs.signing_secret)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Signing secret not configured',+ }+ }+ }++ let body := request.stringBody+ let signatureHeader := request.headers['x-chatwoot-signature']+ let timestamp := request.headers['x-chatwoot-timestamp']++ if (empty(signatureHeader) or empty(timestamp)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Missing signature',+ }+ }+ }++ if (not (signatureHeader like 'sha256=%')) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Could not parse signature',+ }+ }+ }++ let sigParts := splitByString('sha256=', signatureHeader, 2)+ let providedSignature := sigParts[2]++ let signedPayload := concat(timestamp, '.', body)+ let computedSignature := sha256HmacChainHex([inputs.signing_secret, signedPayload])++ if (computedSignature != providedSignature) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Bad signature',+ }+ }+ }++ let currentTime := toInt(toUnixTimestamp(now()))+ let timestampDelta := currentTime - toInt(timestamp)+ if (timestampDelta > 300 or timestampDelta < -300) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Timestamp outside tolerance',+ }+ }+ }+}++let event := request.body.event++if (empty(event)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No event found, skipping'+ }+ }+}++// The event name prefix is the object type: message_created -> message,+// conversation_status_changed -> conversation.+let objectType := splitByString('_', event)[1]++let schemaId := inputs.schema_mapping?.[objectType]++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'No schema mapping for object type: {objectType}, skipping'+ }+ }+}++produceToWarehouseWebhooks(request.body, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "signing_secret",+ "label": "Signing secret",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": "Used to validate the webhook came from Chatwoot",+ },+ {+ "type": "boolean",+ "key": "bypass_signature_check",+ "label": "Bypass signature check",+ "description": "If set, the x-chatwoot-signature header will not be checked. Only use this for older self-hosted Chatwoot versions that do not sign webhook deliveries.",+ "default": False,+ "required": False,+ "secret": False,+ },+ {+ "type": "json",+ "key": "schema_mapping",+ "label": "Schema mapping",+ "description": "Maps Chatwoot object types to ExternalDataSchema IDs",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ {+ "type": "string",+ "key": "source_id",+ "label": "Source ID",+ "description": "The ExternalDataSource ID this webhook is associated with",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ ],+)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex baa07a299282..10cb30471925 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -814,7 +814,9 @@ class ChartMogulSourceConfig(config.Config):@config.configclass ChatwootSourceConfig(config.Config):- pass+ account_id: str+ api_access_token: str+ host: str | None = None@config.config