Skip to content

: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.

feat(data-warehouse): add Twenty CRM source (#78842)

Tom Owersee8f9bfda553
diff --git a/frontend/public/services/twenty.svg b/frontend/public/services/twenty.svg
new file mode 100644
index 000000000000..bad18fab3241
--- /dev/null
+++ b/frontend/public/services/twenty.svg
@@ -0,0 +1,12 @@
+<svg width="136" height="136" viewBox="0 0 136 136" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_2343_96406)">
+<path d="M136 2.28882e-05H0L0.000144482 136H136V2.28882e-05ZM27.27 50.6401C27.27 43.2101 33.3 37.1801 40.73 37.1801H66.64C67.02 37.1801 67.37 37.4101 67.53 37.7601C67.69 38.1101 67.62 38.5201 67.36 38.8101L61.68 44.9801C60.69 46.0501 59.3 46.6701 57.84 46.6701H40.8C38.57 46.6701 36.76 48.4801 36.76 50.7101V60.8901C36.76 62.2001 35.7 63.2601 34.39 63.2601H29.65C28.34 63.2601 27.28 62.2001 27.28 60.8901V50.6401H27.27ZM107.88 85.3601C107.88 92.7901 101.85 98.82 94.42 98.82H83.41C75.98 98.82 69.95 92.7901 69.95 85.3601V66.0901C69.95 64.7801 70.44 63.5201 71.33 62.5501L77.75 55.5801C78.02 55.2901 78.44 55.1901 78.82 55.3301C79.19 55.4801 79.44 55.83 79.44 56.23V85.3001C79.44 87.5301 81.25 89.3401 83.48 89.3401H94.36C96.59 89.3401 98.4 87.5301 98.4 85.3001V50.7101C98.4 48.4801 96.59 46.6701 94.36 46.6701H81.71C80.26 46.6701 78.88 47.2801 77.89 48.3401L40.16 89.3401H62.83C64.14 89.3401 65.2 90.4001 65.2 91.7101V96.4501C65.2 97.7601 64.14 98.82 62.83 98.82H32.28C29.51 98.82 27.26 96.5701 27.26 93.8001V91.29C27.26 90.03 27.73 88.8201 28.59 87.8901L70.89 41.9401C73.69 38.9001 77.62 37.1801 81.75 37.1801H94.41C101.84 37.1801 107.87 43.2101 107.87 50.6401V85.3601H107.88Z" fill="black"/>
+<path d="M27.27 50.6401C27.27 43.2101 33.3 37.1801 40.73 37.1801H66.64C67.02 37.1801 67.37 37.4101 67.53 37.7601C67.69 38.1101 67.62 38.5201 67.36 38.8101L61.68 44.9801C60.69 46.0501 59.3 46.6701 57.84 46.6701H40.8C38.57 46.6701 36.76 48.4801 36.76 50.7101V60.8901C36.76 62.2001 35.7 63.2601 34.39 63.2601H29.65C28.34 63.2601 27.28 62.2001 27.28 60.8901V50.6401H27.27Z" fill="white"/>
+<path d="M107.88 85.3601C107.88 92.7901 101.85 98.82 94.42 98.82H83.41C75.98 98.82 69.95 92.7901 69.95 85.3601V66.0901C69.95 64.7801 70.44 63.5201 71.33 62.5501L77.75 55.5801C78.02 55.2901 78.44 55.1901 78.82 55.3301C79.19 55.4801 79.44 55.83 79.44 56.23V85.3001C79.44 87.5301 81.25 89.3401 83.48 89.3401H94.36C96.59 89.3401 98.4 87.5301 98.4 85.3001V50.7101C98.4 48.4801 96.59 46.6701 94.36 46.6701H81.71C80.26 46.6701 78.88 47.2801 77.89 48.3401L40.16 89.3401H62.83C64.14 89.3401 65.2 90.4001 65.2 91.7101V96.4501C65.2 97.7601 64.14 98.82 62.83 98.82H32.28C29.51 98.82 27.26 96.5701 27.26 93.8001V91.29C27.26 90.03 27.73 88.8201 28.59 87.8901L70.89 41.9401C73.69 38.9001 77.62 37.1801 81.75 37.1801H94.41C101.84 37.1801 107.87 43.2101 107.87 50.6401V85.3601H107.88Z" fill="white"/>
+</g>
+<defs>
+<clipPath id="clip0_2343_96406">
+<rect width="136" height="136" rx="16" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 1c3c3b9a4bb8..79838c6ba410 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -656,6 +656,7 @@ the row lists both.
| tvmaze | HTTP | requests + `rest_source.RESTClient` | ✅ |
| twelve_data | HTTP | requests | ✅ |
| twelve_labs | HTTP | requests | ✅ |
+| twenty | HTTP | requests + `rest_source.RESTClient` | ✅ |
| twilio | HTTP | requests | ✅ |
| tyntec_sms | HTTP | requests + `rest_source.RESTClient` | ✅ |
| typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -1400,7 +1401,6 @@ doesn't conflict with concurrent PRs.
- triple_whale
- trustradius
- turso
-- twenty
- twitch
- twitter
- twitter_ads
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twenty.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twenty.py
index 627803ceab96..dc78e8f396e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twenty.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twenty.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class TwentySourceConfig(config.Config):
- pass
+ api_key: str
+ base_url: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/canonical_descriptions.py
new file mode 100644
index 000000000000..f7bd2615942a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/canonical_descriptions.py
@@ -0,0 +1,101 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://docs.twenty.com/developers/extend/api"
+
+# Curated, docs-sourced descriptions for Twenty's standard CRM objects. Columns not covered here
+# fall back to LLM enrichment. Every object also carries `id` / `createdAt` / `updatedAt` /
+# `deletedAt`, listed once per table below since Twenty applies them uniformly.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "companies": {
+ "description": "An organization tracked in the CRM, with people, opportunities, and notes attached.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the company.",
+ "name": "The company's name.",
+ "domainName": "The company's primary website domain.",
+ "employees": "Approximate number of employees.",
+ "linkedinLink": "Link to the company's LinkedIn page.",
+ "address": "The company's postal address.",
+ "annualRevenue": "The company's annual revenue.",
+ "createdAt": "When the company was created.",
+ "updatedAt": "When the company was last updated.",
+ "deletedAt": "When the company was soft-deleted, if it has been.",
+ },
+ },
+ "people": {
+ "description": "A person tracked in the CRM, optionally linked to a company.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the person.",
+ "name": "The person's first and last name.",
+ "emails": "The person's email addresses.",
+ "phones": "The person's phone numbers.",
+ "jobTitle": "The person's job title.",
+ "companyId": "Identifier of the company this person belongs to, if any.",
+ "linkedinLink": "Link to the person's LinkedIn profile.",
+ "createdAt": "When the person was created.",
+ "updatedAt": "When the person was last updated.",
+ "deletedAt": "When the person was soft-deleted, if it has been.",
+ },
+ },
+ "opportunities": {
+ "description": "A sales opportunity (deal) tracked through a pipeline stage.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the opportunity.",
+ "name": "The opportunity's name.",
+ "amount": "The opportunity's monetary value.",
+ "closeDate": "Expected or actual close date.",
+ "stage": "Pipeline stage the opportunity is currently in.",
+ "companyId": "Identifier of the company this opportunity belongs to, if any.",
+ "pointOfContactId": "Identifier of the person who is the point of contact, if any.",
+ "createdAt": "When the opportunity was created.",
+ "updatedAt": "When the opportunity was last updated.",
+ "deletedAt": "When the opportunity was soft-deleted, if it has been.",
+ },
+ },
+ "notes": {
+ "description": "A free-text note, optionally attached to companies, people, or opportunities.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the note.",
+ "title": "The note's title.",
+ "bodyV2": "The note's rich-text body.",
+ "createdAt": "When the note was created.",
+ "updatedAt": "When the note was last updated.",
+ "deletedAt": "When the note was soft-deleted, if it has been.",
+ },
+ },
+ "tasks": {
+ "description": "A to-do item, optionally attached to companies, people, or opportunities.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the task.",
+ "title": "The task's title.",
+ "bodyV2": "The task's rich-text body.",
+ "status": "The task's status (e.g. todo, in progress, done).",
+ "dueAt": "When the task is due.",
+ "assigneeId": "Identifier of the workspace member assigned to the task, if any.",
+ "createdAt": "When the task was created.",
+ "updatedAt": "When the task was last updated.",
+ "deletedAt": "When the task was soft-deleted, if it has been.",
+ },
+ },
+ "activities": {
+ "description": "An entry on a record's timeline (Twenty's `timelineActivities` object) — the audit trail of events such as record creation, updates, and relationship changes.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the timeline activity.",
+ "name": "The type of event that happened (e.g. record created, updated).",
+ "happensAt": "When the event happened.",
+ "linkedRecordId": "Identifier of the record the event happened on.",
+ "linkedObjectMetadataId": "Identifier of the object type the linked record belongs to.",
+ "workspaceMemberId": "Identifier of the workspace member who triggered the event, if any.",
+ "createdAt": "When the timeline activity was created.",
+ "updatedAt": "When the timeline activity was last updated.",
+ "deletedAt": "When the timeline activity was soft-deleted, if it has been.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/settings.py
new file mode 100644
index 000000000000..15a5dbd0c761
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/settings.py
@@ -0,0 +1,54 @@
+from dataclasses import field
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Twenty's core REST list endpoints cap `limit` at 200 (`QUERY_MAX_RECORDS` server-side, verified
+# against the REST request parser source); the documented default is 60. Requesting the max keeps
+# request counts low.
+PAGE_SIZE = 200
+
+# (connect, read) timeout in seconds. The base URL is customer-controlled, so an unbounded read
+# lets a host that stalls mid-response hold an import worker until the week-long activity timeout.
+REQUEST_TIMEOUT: tuple[float, float] = (10.0, 60.0)
+
+# Every Twenty workspace entity carries `createdAt` / `updatedAt`, so both are offered as
+# incremental candidates on every endpoint; `updatedAt` also catches later edits.
+_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ incremental_field("updatedAt"),
+ incremental_field("createdAt"),
+]
+
+
+@frozen
+class TwentyEndpointConfig:
+ name: str
+ # REST path segment (the object's `namePlural`), appended to the configured base URL.
+ path: str
+ primary_key: str = "id"
+ partition_key: str = "createdAt"
+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_INCREMENTAL_FIELDS))
+
+
+# Twenty's REST API is schema-per-workspace and lets users add custom objects, but every
+# workspace ships these standard CRM objects, so they're the safe, verified sync targets rather
+# than a metadata-driven discovery of custom objects (whose REST list response shape varies by an
+# internal, unverifiable feature flag — see the module docstring in twenty.py). `activities` maps
+# to Twenty's `timelineActivities` object, the audit trail of record events shown on a record's
+# timeline.
+TWENTY_ENDPOINTS: dict[str, TwentyEndpointConfig] = {
+ "companies": TwentyEndpointConfig(name="companies", path="/companies"),
+ "people": TwentyEndpointConfig(name="people", path="/people"),
+ "opportunities": TwentyEndpointConfig(name="opportunities", path="/opportunities"),
+ "notes": TwentyEndpointConfig(name="notes", path="/notes"),
+ "tasks": TwentyEndpointConfig(name="tasks", path="/tasks"),
+ "activities": TwentyEndpointConfig(name="activities", path="/timelineActivities"),
+}
+
+ENDPOINTS = tuple(TWENTY_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in TWENTY_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/source.py
index 868a509d1985..cd04e93f464e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/source.py
@@ -1,31 +1,146 @@
-from typing import cast
+from typing import Optional, cast
from 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.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.errors import auth_non_retryable_errors
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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.twenty import TwentySourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.twenty.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.twenty.twenty import (
+ HOST_NOT_ALLOWED_ERROR,
+ HTTP_NOT_ALLOWED_ERROR,
+ TwentyResumeConfig,
+ twenty_source,
+ validate_credentials as validate_twenty_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TwentySource(SimpleSource[TwentySourceConfig]):
+class TwentySource(ResumableSource[TwentySourceConfig, TwentyResumeConfig]):
+ api_docs_url = "https://docs.twenty.com/developers/extend/api"
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TWENTY
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `base_url` is where the stored API key is sent; retargeting it must re-require the key.
+ return ["base_url"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ **auth_non_retryable_errors(service="Twenty"),
+ HOST_NOT_ALLOWED_ERROR: "The Twenty instance URL is not allowed. Please use a publicly reachable host.",
+ HTTP_NOT_ALLOWED_ERROR: "The Twenty instance URL must use HTTPS. Please update the instance URL to use https://.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.twenty.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: TwentySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: TwentySourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_twenty_credentials(config.base_url, config.api_key, team_id, schema_name)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TwentyResumeConfig]:
+ return ResumableSourceManager[TwentyResumeConfig](inputs, TwentyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TwentySourceConfig,
+ resumable_source_manager: ResumableSourceManager[TwentyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return twenty_source(
+ base_url=config.base_url,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.TWENTY,
category=DataWarehouseSourceCategory.CRM,
label="Twenty",
- iconPath="/static/services/twenty.png",
+ releaseStatus=ReleaseStatus.ALPHA,
keywords=["crm", "sales", "open source", "salesforce"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ caption="""Enter your Twenty API key to pull your CRM data into the PostHog Data warehouse.
+
+Generate an API key in Twenty under **Settings > API & Webhooks > + Create key**. Copy it immediately, it's only shown once.
+
+Self-hosted users should set the instance URL to their own Twenty host (for example `https://twenty.example.com`). Leave it blank to use Twenty Cloud (`https://api.twenty.com`).""",
+ iconPath="/static/services/twenty.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/twenty",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="base_url",
+ label="Instance URL (self-hosted only)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="https://api.twenty.com",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/tests/test_twenty.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/tests/test_twenty.py
new file mode 100644
index 000000000000..97ecd36b81cb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/tests/test_twenty.py
@@ -0,0 +1,444 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.twenty import twenty as twenty_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.twenty.settings import TWENTY_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.twenty.twenty import (
+ TwentyHostNotAllowedError,
+ TwentyResumeConfig,
+ _format_filter_value,
+ normalize_base_url,
+ twenty_source,
+ validate_credentials,
+)
+
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+
+
+def _response(*, status_code: int = 200, body: Any = None) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode() if body is not None else b""
+ return resp
+
+
+def _page(
+ rows: list[dict[str, Any]],
+ *,
+ object_name: str = "companies",
+ has_next_page: bool = False,
+ end_cursor: str | None = None,
+) -> Response:
+ body: dict[str, Any] = {
+ "data": {object_name: rows},
+ "totalCount": len(rows),
+ "pageInfo": {"hasNextPage": has_next_page, "startCursor": None, "endCursor": end_cursor},
+ }
+ return _response(body=body)
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[requests.PreparedRequest]:
+ """Wire a mock session; delegate prepare_request to a real session so auth + params are applied.
+
+ The framework mutates a single request/params dict in place across pages, so we snapshot each
+ prepared request (its URL carries the limit/starting_after query and its headers carry the
+ auth) as the client prepares it, then return canned responses from ``send``.
+ """
+ session.headers = {}
+ real = requests.Session()
+ prepared: list[requests.PreparedRequest] = []
+
+ def _prepare(request: Any) -> requests.PreparedRequest:
+ real.headers.clear()
+ real.headers.update(session.headers)
+ p = real.prepare_request(request)
+ prepared.append(p)
+ return p
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return prepared
+
+
+def _make_manager(resume_state: TwentyResumeConfig | 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 _source(
+ manager: mock.MagicMock,
+ *,
+ base_url: str | None = None,
+ endpoint: str = "companies",
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Any:
+ return twenty_source(
+ base_url=base_url,
+ api_key="tok",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ )
+
+
+def _rows(source_response: Any) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+def _query(prepared: requests.PreparedRequest) -> dict[str, list[str]]:
+ assert prepared.url is not None
+ return parse_qs(urlparse(prepared.url).query)
+
+
+class TestNormalizeBaseUrl:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ (None, "https://api.twenty.com"),
+ ("", "https://api.twenty.com"),
+ (" ", "https://api.twenty.com"),
+ ("https://api.twenty.com", "https://api.twenty.com"),
+ ("https://api.twenty.com/", "https://api.twenty.com"),
+ ("https://api.twenty.com/rest", "https://api.twenty.com"),
+ ("twenty.example.com", "https://twenty.example.com"),
+ ("http://twenty.example.com/", "http://twenty.example.com"),
+ ],
+ )
+ def test_normalize(self, raw, expected):
+ assert normalize_base_url(raw) == expected
+
+
+class TestHostOf:
+ @pytest.mark.parametrize(
+ "url, expected_host",
+ [
+ ("https://twenty.example.com", "twenty.example.com"),
+ # A backslash — literal or `%5c`-encoded — is an SSRF vector: `urlparse` and
+ # requests/urllib3 disagree on the host, so the check could validate a decoy host while
+ # the request reaches an internal address. No legitimate URL contains one, so `_host_of`
+ # fails closed and returns "" (rejected upstream).
+ ("https://safe.com\\@169.254.169.254", ""),
+ ("https://safe.com%[email protected]", ""),
+ ("https://safe.com%[email protected]", ""),
+ ],
+ )
+ def test_host_rejects_backslash_ssrf_bypass(self, url, expected_host):
+ assert twenty_module._host_of(url) == expected_host
+
+
+class TestFormatFilterValue:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (datetime(2024, 1, 1, 12, 30, 0, tzinfo=UTC), "2024-01-01T12:30:00.000Z"),
+ (datetime(2024, 1, 1, 12, 30, 0), "2024-01-01T12:30:00.000Z"),
+ (date(2024, 1, 1), "2024-01-01"),
+ ("2024-01-01T00:00:00.000Z", "2024-01-01T00:00:00.000Z"),
+ ],
+ )
+ def test_format(self, value, expected):
+ assert _format_filter_value(value) == expected
+
+
+class TestValidateCredentials:
+ def _patch_session(self, response=None, raises=None):
+ session = mock.MagicMock()
+ if raises is not None:
+ session.get.side_effect = raises
+ else:
+ session.get.return_value = response
+ return mock.patch.object(twenty_module, "make_tracked_session", return_value=session)
+
+ def _resp(self, *, status_code=200):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ return response
+
+ def test_success(self):
+ with self._patch_session(self._resp(status_code=200)):
+ assert validate_credentials(None, "tok", team_id=1) == (True, None)
+
+ def test_invalid_key_401(self):
+ with self._patch_session(self._resp(status_code=401)):
+ valid, msg = validate_credentials(None, "tok", team_id=1)
+ assert valid is False
+ assert "Invalid Twenty API key" in (msg or "")
+
+ def test_permission_403_at_source_create_is_accepted(self):
+ with self._patch_session(self._resp(status_code=403)):
+ assert validate_credentials(None, "tok", team_id=1, schema_name=None) == (True, None)
+
+ def test_permission_403_for_scoped_probe_fails(self):
+ with self._patch_session(self._resp(status_code=403)):
+ valid, msg = validate_credentials(None, "tok", team_id=1, schema_name="companies")
+ assert valid is False
+ assert msg is not None
+
+ def test_unexpected_status(self):
+ with self._patch_session(self._resp(status_code=500)):
+ valid, msg = validate_credentials(None, "tok", team_id=1)
+ assert valid is False
+ assert "500" in (msg or "")
+
+ def test_request_exception_returns_failure(self):
+ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):
+ valid, msg = validate_credentials(None, "tok", team_id=1)
+ assert valid is False
+ assert "Could not reach" in (msg or "")
+
+ def test_blocks_unsafe_host(self):
+ with (
+ mock.patch.object(twenty_module, "_is_host_safe", return_value=(False, "internal address")),
+ self._patch_session(self._resp(status_code=200)) as patched,
+ ):
+ valid, msg = validate_credentials("http://10.0.0.1", "tok", team_id=99)
+ assert valid is False
+ assert msg == "internal address"
+ patched.return_value.get.assert_not_called()
+
+ def test_rejects_plaintext_http_before_sending_token(self):
+ with self._patch_session(self._resp(status_code=200)) as patched:
+ valid, msg = validate_credentials("http://twenty.example.com", "tok", team_id=1)
+ assert valid is False
+ assert msg == twenty_module.HTTP_NOT_ALLOWED_ERROR
+ patched.return_value.get.assert_not_called()
+
+ def test_probe_hits_configured_host_with_bearer_token(self):
+ with self._patch_session(self._resp(status_code=200)) as patched:
+ validate_credentials("https://twenty.example.com", "tok", team_id=1)
+ call = patched.return_value.get.call_args
+ assert call.args[0] == "https://twenty.example.com/rest/companies?limit=1"
+ assert call.kwargs["headers"]["Authorization"] == "Bearer tok"
+ assert call.kwargs["allow_redirects"] is False
+
+ def test_redacts_token_in_telemetry(self):
+ with self._patch_session(self._resp(status_code=200)) as patched:
+ validate_credentials(None, "tok", team_id=1)
+ assert patched.call_args.kwargs["redact_values"] == ("tok",)
+
+
+class TestTwentySourceResponse:
+ @pytest.mark.parametrize("endpoint", list(TWENTY_ENDPOINTS.keys()))
+ def test_response_shape(self, endpoint):
+ response = _source(_make_manager(), endpoint=endpoint)
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+ assert response.partition_keys == ["createdAt"]
+ assert response.partition_mode == "datetime"
+
+
+class TestPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paginates_via_cursor(self, MockSession):
+ session = MockSession.return_value
+ prepared = _wire(
+ session,
+ [
+ _page([{"id": "1"}, {"id": "2"}], has_next_page=True, end_cursor="cursor-a"),
+ _page([{"id": "3"}], has_next_page=False, end_cursor="cursor-b"),
+ ],
+ )
+ rows = _rows(_source(_make_manager()))
+
+ assert [r["id"] for r in rows] == ["1", "2", "3"]
+ assert "starting_after" not in _query(prepared[0])
+ assert _query(prepared[1])["starting_after"] == ["cursor-a"]
+ assert _query(prepared[0])["limit"] == ["200"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stops_when_has_next_page_false_despite_end_cursor(self, MockSession):
+ # Twenty's final page can still carry a non-null endCursor pointing at its own last row;
+ # hasNextPage is the real termination signal and must win over cursor presence.
+ session = MockSession.return_value
+ _wire(session, [_page([{"id": "1"}], has_next_page=False, end_cursor="cursor-last")])
+ rows = _rows(_source(_make_manager()))
+
+ assert [r["id"] for r in rows] == ["1"]
+ assert session.send.call_count == 1
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stops_when_cursor_does_not_advance(self, MockSession):
+ # A broken or hostile host can return hasNextPage=true with the same endCursor forever;
+ # the sync must stop rather than loop until the week-long activity timeout. Only two
+ # responses are wired, so a third request would raise instead of looping silently.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _page([{"id": "1"}], has_next_page=True, end_cursor="cursor-a"),
+ _page([{"id": "2"}], has_next_page=True, end_cursor="cursor-a"),
+ ],
+ )
+ rows = _rows(_source(_make_manager()))
+
+ assert [r["id"] for r in rows] == ["1", "2"]
+ assert session.send.call_count == 2
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_saves_next_page_after_yielding(self, MockSession):
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _page([{"id": "1"}], has_next_page=True, end_cursor="cursor-a"),
+ _page([{"id": "2"}], has_next_page=False, end_cursor="cursor-b"),
+ ],
+ )
+ manager = _make_manager()
+ _rows(_source(manager))
+
+ assert manager.save_state.call_count == 1
+ saved = manager.save_state.call_args.args[0]
+ assert isinstance(saved, TwentyResumeConfig)
+ assert saved.starting_after == "cursor-a"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_state(self, MockSession):
+ session = MockSession.return_value
+ prepared = _wire(session, [_page([{"id": "9"}], has_next_page=False)])
+ manager = _make_manager(TwentyResumeConfig(starting_after="cursor-a"))
+ rows = _rows(_source(manager))
+
+ assert _query(prepared[0])["starting_after"] == ["cursor-a"]
+ assert [r["id"] for r in rows] == ["9"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_page_terminates(self, MockSession):
+ session = MockSession.return_value
+ _wire(session, [_page([], has_next_page=False)])
+ manager = _make_manager()
+ rows = _rows(_source(manager))
+
+ assert rows == []
+ assert session.send.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_passes_allow_redirects_false(self, MockSession):
+ session = MockSession.return_value
+ _wire(session, [_page([{"id": "1"}])])
+ _rows(_source(_make_manager()))
+ assert session.send.call_args.kwargs["allow_redirects"] is False
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_sends_bearer_token(self, MockSession):
+ session = MockSession.return_value
+ prepared = _wire(session, [_page([{"id": "1"}])])
+ _rows(_source(_make_manager()))
+ assert prepared[0].headers["Authorization"] == "Bearer tok"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_redacts_token_in_telemetry(self, MockSession):
+ session = MockSession.return_value
+ _wire(session, [_page([{"id": "1"}])])
+ _rows(_source(_make_manager()))
+ assert MockSession.call_args.kwargs["redact_values"] == ("tok",)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_raises_when_host_not_allowed(self, MockSession):
+ session = MockSession.return_value
+ _wire(session, [_page([{"id": "1"}])])
+ with mock.patch.object(twenty_module, "_is_host_safe", return_value=(False, "internal address")):
+ with pytest.raises(TwentyHostNotAllowedError):
+ _rows(_source(_make_manager()))
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_raises_on_plaintext_http(self, MockSession):
+ session = MockSession.return_value
+ _wire(session, [_page([{"id": "1"}])])
+ with pytest.raises(TwentyHostNotAllowedError):
+ _rows(_source(_make_manager(), base_url="http://twenty.example.com"))
+
+ @pytest.mark.parametrize("status_code", [429, 503])
+ @mock.patch("tenacity.nap.time.sleep", return_value=None)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_retries_retryable_status_then_succeeds(self, MockSession, _sleep, status_code):
+ session = MockSession.return_value
+ _wire(session, [_response(status_code=status_code), _page([{"id": "r1"}])])
+ rows = _rows(_source(_make_manager()))
+ assert [r["id"] for r in rows] == ["r1"]
+ assert session.send.call_count == 2
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_sorts_by_id(self, MockSession):
+ session = MockSession.return_value
+ prepared = _wire(session, [_page([{"id": "1"}])])
+ _rows(_source(_make_manager(), should_use_incremental_field=False))
+ assert _query(prepared[0])["order_by"] == ["id[AscNullsFirst]"]
+ assert "filter" not in _query(prepared[0])
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_sorts_and_filters_by_chosen_field(self, MockSession):
+ session = MockSession.return_value
+ prepared = _wire(session, [_page([{"id": "1"}])])
+ _rows(
+ _source(
+ _make_manager(),
+ should_use_incremental_field=True,
+ incremental_field="createdAt",
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+ )
+ query = _query(prepared[0])
+ assert query["order_by"] == ["createdAt[AscNullsFirst]"]
+ assert query["filter"] == ['createdAt[gte]:"2024-01-01T00:00:00.000Z"']
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_first_sync_omits_filter(self, MockSession):
+ # No watermark yet (first incremental sync): the filter param is dropped entirely rather
+ # than sending a malformed value, so the full history is pulled.
+ session = MockSession.return_value
+ prepared = _wire(session, [_page([{"id": "1"}])])
+ _rows(
+ _source(
+ _make_manager(),
+ should_use_incremental_field=True,
+ incremental_field="updatedAt",
+ db_incremental_field_last_value=None,
+ )
+ )
+ query = _query(prepared[0])
+ assert query["order_by"] == ["updatedAt[AscNullsFirst]"]
+ assert "filter" not in query
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_defaults_to_updated_at_when_field_unset(self, MockSession):
+ session = MockSession.return_value
+ prepared = _wire(session, [_page([{"id": "1"}])])
+ _rows(
+ _source(
+ _make_manager(),
+ should_use_incremental_field=True,
+ incremental_field=None,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+ )
+ query = _query(prepared[0])
+ assert query["order_by"] == ["updatedAt[AscNullsFirst]"]
+
+ @pytest.mark.parametrize("endpoint,object_name", [("activities", "timelineActivities"), ("companies", "companies")])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_data_selector_matches_object_name_plural(self, MockSession, endpoint, object_name):
+ session = MockSession.return_value
+ _wire(session, [_page([{"id": "1"}], object_name=object_name)])
+ rows = _rows(_source(_make_manager(), endpoint=endpoint))
+ assert [r["id"] for r in rows] == ["1"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/tests/test_twenty_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/tests/test_twenty_source.py
new file mode 100644
index 000000000000..40c57b809f23
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/tests/test_twenty_source.py
@@ -0,0 +1,147 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.twenty import TwentySourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.twenty.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.twenty.source import TwentySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.twenty.twenty import TwentyResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestTwentySource:
+ def setup_method(self):
+ self.source = TwentySource()
+ self.team_id = 123
+ self.config = TwentySourceConfig(api_key="tok", base_url=None)
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.TWENTY
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Twenty"
+ assert config.label == "Twenty"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/twenty.svg"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/twenty"
+ assert config.unreleasedSource is None
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["api_key", "base_url"]
+
+ api_key_field, base_url_field = config.fields
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ assert isinstance(base_url_field, SourceFieldInputConfig)
+ assert base_url_field.type == SourceFieldInputConfigType.TEXT
+ assert base_url_field.secret is False
+ assert base_url_field.required is False
+
+ def test_connection_host_fields_force_secret_reentry(self):
+ # The API key is sent to base_url, so retargeting it must re-require the key.
+ assert self.source.connection_host_fields == ["base_url"]
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_all_schemas_support_incremental_on_updated_and_created_at(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ for schema in schemas:
+ assert schema.supports_incremental is True
+ assert schema.supports_append is True
+ assert {f["field"] for f in schema.incremental_fields} == {"updatedAt", "createdAt"}
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["companies"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "companies"
+
+ def test_get_schemas_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_lists_tables_without_credentials(self):
+ # Static endpoint catalog with no I/O, so the public docs can render the table list.
+ assert self.source.lists_tables_without_credentials is True
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected",
+ [
+ ((True, None), (True, None)),
+ ((False, "Invalid Twenty API key"), (False, "Invalid Twenty API key")),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.twenty.source.validate_twenty_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="companies")
+
+ assert result == expected
+ mock_validate.assert_called_once_with(self.config.base_url, self.config.api_key, self.team_id, "companies")
+
+ def test_get_resumable_source_manager(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is TwentyResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.twenty.source.twenty_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_twenty_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "companies"
+ inputs.team_id = 42
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00.000Z"
+ inputs.incremental_field = "updatedAt"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_twenty_source.assert_called_once()
+ kwargs = mock_twenty_source.call_args.kwargs
+ assert kwargs["base_url"] == self.config.base_url
+ assert kwargs["api_key"] == "tok"
+ assert kwargs["endpoint"] == "companies"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["team_id"] == 42
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00.000Z"
+ assert kwargs["incremental_field"] == "updatedAt"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.twenty.source.twenty_source")
+ def test_source_for_pipeline_omits_watermark_on_full_refresh(self, mock_twenty_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "companies"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00.000Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_twenty_source.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_core_tables(self):
+ descriptions = self.source.get_canonical_descriptions()
+ # Curated docs only describe endpoints we actually expose.
+ assert set(descriptions).issubset(set(ENDPOINTS))
+ assert "companies" in descriptions
+ assert "people" in descriptions
+ assert "opportunities" in descriptions
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/twenty.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/twenty.py
new file mode 100644
index 000000000000..f0629b712807
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twenty/twenty.py
@@ -0,0 +1,330 @@
+"""Twenty transport layer.
+
+Twenty is an open-source CRM offered both as hosted cloud (``https://api.twenty.com``) and
+self-hosted (a customer-supplied host), so the API base URL is a configurable field. Auth is a
+single ``Authorization: Bearer <api key>`` header; every request must be made over HTTPS.
+
+List endpoints are cursor paginated: ``limit`` caps the page size (documented default 60, server
+max 200 per ``QUERY_MAX_RECORDS``), ``starting_after`` advances to the next page, and each
+response carries ``pageInfo.hasNextPage`` / ``pageInfo.endCursor``. Records for object
+``<namePlural>`` arrive wrapped as ``{"data": {"<namePlural>": [...]}, "pageInfo": {...},
+"totalCount": ...}`` — verified against the REST controller source
+(``rest-api-find-many.handler.ts`` / ``parse-core-path.utils.ts``) rather than the vendor's own
+OpenAPI description text, which documents a ``/rest/core/...`` path that the actual routing
+(``/rest/<namePlural>``) does not implement.
+
+List endpoints accept ``filter=<field>[gte]:"<ISO 8601 value>"`` and
+``order_by=<field>[AscNullsFirst]``, both combinable with cursor pagination, so incremental sync
+on ``updatedAt`` / ``createdAt`` is a genuine server-side filter rather than a client-side skip.
+"""
+
+import re
+from collections.abc import Callable
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlparse
+
+from requests import Request, Response
+
+from posthog.dataclasses import frozen
+
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.twenty.settings import (
+ PAGE_SIZE,
+ REQUEST_TIMEOUT,
+ TWENTY_ENDPOINTS,
+)
+
+DEFAULT_BASE_URL = "https://api.twenty.com"
+DEFAULT_INCREMENTAL_FIELD = "updatedAt"
+HOST_NOT_ALLOWED_ERROR = "Twenty instance URL is not allowed"
+HTTP_NOT_ALLOWED_ERROR = "Twenty instance URL must use HTTPS"
+
+
+class TwentyHostNotAllowedError(Exception):
+ pass
+
+
+@frozen
+class TwentyResumeConfig:
+ # `starting_after` cursor for the next page. Persisted after each page is yielded, so a crash
+ # re-fetches the last page rather than skipping rows still buffered but not yet durably
+ # written (merge dedupes the re-pulled rows on `id`).
+ starting_after: Optional[str] = None
+
+
+def normalize_base_url(base_url: Optional[str]) -> str:
+ """Turn whatever the user typed into a bare Twenty base URL.
+
+ Blank -> Twenty Cloud. Accepts bare hosts (``twenty.example.com``), a URL with or without a
+ scheme, and one that already carries a trailing ``/rest``.
+ """
+ raw = (base_url or "").strip()
+ if not raw:
+ return DEFAULT_BASE_URL
+ if not re.match(r"^https?://", raw, flags=re.IGNORECASE):
+ raw = f"https://{raw}"
+ raw = raw.rstrip("/")
+ raw = re.sub(r"/rest$", "", raw, flags=re.IGNORECASE)
+ return raw.rstrip("/")
+
+
+def _host_of(base_url: str) -> str:
+ # A backslash in the authority — literal `\` or percent-encoded `%5c` — is an SSRF vector:
+ # requests/urllib3 treat a literal `\` as a path separator and do NOT percent-decode `%5c`,
+ # so `urlparse` and the HTTP client can disagree on the host. `https://safe.com%[email protected]`
+ # would validate as `safe.com` while the client connects to `169.254.169.254`. No legitimate
+ # Twenty URL contains a backslash, so fail closed rather than try to mirror the client's parsing.
+ if "\\" in base_url or "%5c" in base_url.lower():
+ return ""
+ return (urlparse(base_url).hostname or "").lower()
+
+
+def _is_https(base_url: str) -> bool:
+ # The API key rides in the Authorization header, so refuse plaintext HTTP to keep an on-path
+ # attacker from capturing it.
+ return urlparse(base_url).scheme == "https"
+
+
+def _ensure_host_allowed(base_url: str, host: str, team_id: int) -> None:
+ if not _is_https(base_url):
+ raise TwentyHostNotAllowedError(HTTP_NOT_ALLOWED_ERROR)
+ host_ok, host_err = _is_host_safe(host, team_id)
+ if not host_ok:
+ raise TwentyHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+
+def _format_filter_value(value: Any) -> Optional[str]:
+ """Render an incremental watermark as the bare ISO 8601 string Twenty's filter DSL expects.
+
+ Watermarks arrive as datetimes, dates, or already-formatted strings depending on how the
+ pipeline stored them. ``None`` (no watermark yet, i.e. the first sync) is passed through so
+ the caller can skip adding the filter param entirely.
+ """
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ moment = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return moment.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ return value.isoformat()
+ return str(value)
+
+
+def _make_filter_converter(field_name: str) -> Callable[[Any], Optional[str]]:
+ """Build the `convert` callable for the `filter` incremental param.
+
+ `requests` drops a param whose value is `None` from the query string, so returning `None`
+ on the first sync (no watermark yet) omits `filter` entirely rather than sending a malformed
+ value.
+ """
+
+ def convert(value: Any) -> Optional[str]:
+ formatted = _format_filter_value(value)
+ if formatted is None:
+ return None
+ return f'{field_name}[gte]:"{formatted}"'
+
+ return convert
+
+
+class TwentyCursorPaginator(BasePaginator):
+ """Cursor paginator for Twenty's ``pageInfo`` envelope.
+
+ Twenty's cursor is opaque (``pageInfo.endCursor``), and a bare "cursor present" check isn't
+ sufficient to detect the last page: the final page can still carry a non-null ``endCursor``
+ pointing at its own last row. ``pageInfo.hasNextPage`` is the actual termination signal, so
+ both are read together.
+ """
+
+ def __init__(self, limit: int = PAGE_SIZE) -> None:
+ super().__init__()
+ self.limit = limit
+ self._next_cursor: Optional[str] = None
+
+ def _set_params(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["limit"] = self.limit
+ if self._next_cursor is not None:
+ request.params["starting_after"] = self._next_cursor
+
+ def init_request(self, request: Request) -> None:
+ self._set_params(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ try:
+ page_info = (response.json() or {}).get("pageInfo") or {}
+ except Exception:
+ page_info = {}
+ end_cursor = page_info.get("endCursor")
+ # A cursor identical to the one we just followed means the host isn't advancing — a broken
+ # or hostile customer-controlled server could return `hasNextPage: true` with the same
+ # cursor forever, looping the sync until the week-long activity timeout. Stop instead.
+ if page_info.get("hasNextPage") and end_cursor and end_cursor != self._next_cursor:
+ self._next_cursor = end_cursor
+ self._has_next_page = True
+ else:
+ self._has_next_page = False
+
+ def update_request(self, request: Request) -> None:
+ self._set_params(request)
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"starting_after": self._next_cursor} if self._has_next_page and self._next_cursor else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ cursor = state.get("starting_after")
+ if cursor:
+ self._next_cursor = cursor
+ self._has_next_page = True
+
+ def __str__(self) -> str:
+ return f"TwentyCursorPaginator(limit={self.limit})"
+
+
+def validate_credentials(
+ base_url: Optional[str], api_key: str, team_id: int, schema_name: Optional[str] = None
+) -> tuple[bool, str | None]:
+ """Probe the companies list — the cheapest read any workspace API key can perform."""
+ resolved = normalize_base_url(base_url)
+ host = _host_of(resolved)
+ if not host:
+ return False, "Invalid Twenty instance URL"
+
+ host_ok, host_err = _is_host_safe(host, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+ if not _is_https(resolved):
+ return False, HTTP_NOT_ALLOWED_ERROR
+
+ ok, status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ f"{resolved}/rest/companies?limit=1",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ allow_redirects=False,
+ )
+ if ok:
+ return True, None
+ if status is None:
+ return False, "Could not reach the Twenty API. Check the instance URL and try again."
+ if status == 401:
+ return False, "Invalid Twenty API key. Generate a new key in Settings > API & Webhooks and reconnect."
+ if status == 403:
+ # A role can restrict an API key to a subset of objects; accept at source-create and only
+ # reject when probing a specific schema's scope.
+ if schema_name is None:
+ return True, None
+ return (
+ False,
+ "Your Twenty API key does not have permission to read this data. Check the key's role and reconnect.",
+ )
+ return False, f"Twenty API returned an unexpected status ({status}) while validating credentials."
+
+
+def twenty_source(
+ base_url: Optional[str],
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[TwentyResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ config = TWENTY_ENDPOINTS[endpoint]
+ resolved_base_url = normalize_base_url(base_url)
+ host = _host_of(resolved_base_url)
+ field_name = incremental_field or DEFAULT_INCREMENTAL_FIELD
+
+ params: dict[str, Any] = {}
+ if should_use_incremental_field:
+ params["filter"] = {
+ "type": "incremental",
+ "cursor_path": field_name,
+ "convert": _make_filter_converter(field_name),
+ }
+ params["order_by"] = f"{field_name}[AscNullsFirst]"
+ else:
+ # No incremental filter, but an explicit stable sort still keeps cursor pagination
+ # deterministic across a sync's page requests.
+ params["order_by"] = "id[AscNullsFirst]"
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": f"{resolved_base_url}/rest",
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "bearer", "token": api_key},
+ "paginator": TwentyCursorPaginator(),
+ # Don't follow redirects: a self-hosted host could 3xx to an internal address,
+ # bypassing the host validation done before the request (SSRF).
+ "allow_redirects": False,
+ # Bound each request so a customer-controlled host that stalls can't hold a worker
+ # until the week-long resumable activity timeout.
+ "request_timeout": REQUEST_TIMEOUT,
+ },
+ "resource_defaults": {
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field
+ else "replace",
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": params,
+ "data_selector": f"data.{config.path.lstrip('/')}",
+ },
+ "table_format": "delta",
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.starting_after:
+ initial_paginator_state = {"starting_after": resume.starting_after}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on
+ # completion, and `state` is None/empty on the last page.
+ next_cursor = (state or {}).get("starting_after")
+ if next_cursor:
+ resumable_source_manager.save_state(TwentyResumeConfig(starting_after=next_cursor))
+
+ def items() -> Any:
+ # Re-check at run time (not just source-create) in case the URL was edited or now
+ # resolves to an internal address (SSRF / DNS rebinding).
+ _ensure_host_allowed(resolved_base_url, host, team_id)
+ yield from rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=[config.primary_key],
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ )