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): implement zapsign import source (#72653)

Tom Owersaeb001f43295
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 b6a6d00e4e40..ceb55ad4f5fa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -597,6 +597,7 @@ the row lists both.
| xmatters | HTTP | requests | ✅ |
| yousign | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| zapier_supported_storage | HTTP | requests | ✅ |
+| zapsign | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |
| zendesk_sell | HTTP | requests | ✅ |
| zendesk_sunshine | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -1006,7 +1007,6 @@ doesn't conflict with concurrent PRs.
- younium
- youtube_analytics
- youtube_data
-- zapsign
- zellify
- zenefits
- zenloop
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zapsign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zapsign.py
index a7cb35a5f700..8d4925391d01 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zapsign.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zapsign.py
@@ -1,9 +1,12 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@config.config
class ZapSignSourceConfig(config.Config):
- pass
+ api_token: str
+ environment: Literal["production", "sandbox"] = config.value(default="production")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/canonical_descriptions.py
new file mode 100644
index 000000000000..b48f0204a01d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/canonical_descriptions.py
@@ -0,0 +1,65 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "documents": {
+ "description": "A document sent for electronic signature, with its signing status and signer list.",
+ "docs_url": "https://docs.zapsign.com.br/english/documentos/listar-documentos",
+ "columns": {
+ "token": "Unique identifier (UUID) for the document.",
+ "open_id": "Sequential numeric identifier of the document within the account.",
+ "external_id": "Custom identifier assigned by your application when the document was created.",
+ "name": "Name of the document.",
+ "status": "Signing status of the document: pending, signed, or refused.",
+ "folder_path": "Folder the document is stored in; '/' is the root folder.",
+ "original_file": "Temporary download link (expires in ~60 minutes) for the original file.",
+ "signed_file": "Temporary download link (expires in ~60 minutes) for the signed file.",
+ "created_at": "When the document was created.",
+ "last_update_at": "When the document was last updated.",
+ "deleted": "Whether the document has been deleted.",
+ "deleted_at": "When the document was deleted, if it was.",
+ "lang": "Language of the signing experience (e.g. pt-br, en, es).",
+ "created_through": "How the document was created (e.g. web, api).",
+ "signers": "Signers of the document, with each signer's status and details.",
+ },
+ },
+ "templates": {
+ "description": "A reusable document template ('model') used to generate documents for signature.",
+ "docs_url": "https://docs.zapsign.com.br/english/templates/list-templates",
+ "columns": {
+ "token": "Unique identifier (UUID) for the template.",
+ "name": "Name of the template.",
+ "template_type": "File type the template was built from (e.g. docx).",
+ "active": "Whether the template is active.",
+ "template_file": "Link to the template's source file.",
+ "folder_path": "Folder the template is stored in.",
+ "redirect_link": "URL signers are redirected to after signing, if configured.",
+ "lang": "Language of the signing experience for documents created from this template.",
+ "created_at": "When the template was created.",
+ "last_update_at": "When the template was last updated.",
+ },
+ },
+ "signers": {
+ "description": "A person who is asked to sign a document, with their signing status and authentication details.",
+ "docs_url": "https://docs.zapsign.com.br/english/signatarios/detalhar-signatario",
+ "columns": {
+ "token": "Unique identifier (UUID) for the signer.",
+ "_documents_token": "Token of the document this signer belongs to.",
+ "external_id": "Custom identifier assigned by your application to the signer.",
+ "name": "Signer's name.",
+ "email": "Signer's email address.",
+ "status": "Signer status: new, link-opened, signed, or refused.",
+ "phone_country": "Country code of the signer's phone number.",
+ "phone_number": "Signer's phone number.",
+ "auth_mode": "Authentication method required to sign (e.g. assinaturaTela, tokenEmail).",
+ "sign_url": "Link the signer uses to sign the document.",
+ "times_viewed": "How many times the signer opened the document.",
+ "last_view_at": "When the signer last viewed the document.",
+ "signed_at": "When the signer signed the document.",
+ "qualification": "Signer's role on the document (e.g. witness, party).",
+ "geo_latitude": "Latitude captured at signature time, when geolocation is required.",
+ "geo_longitude": "Longitude captured at signature time, when geolocation is required.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/settings.py
new file mode 100644
index 000000000000..addfe8b6e7f5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/settings.py
@@ -0,0 +1,53 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+ZAPSIGN_BASE_URL = "https://api.zapsign.com.br"
+ZAPSIGN_SANDBOX_BASE_URL = "https://sandbox.api.zapsign.com.br"
+
+DOCUMENTS_RESOURCE = "documents"
+TEMPLATES_RESOURCE = "templates"
+SIGNERS_RESOURCE = "signers"
+
+ENDPOINTS = (
+ DOCUMENTS_RESOURCE,
+ TEMPLATES_RESOURCE,
+ SIGNERS_RESOURCE,
+)
+
+# Only the documents list exposes a server-side time filter (`created_from`/`created_to`, on the
+# creation date). ZapSign has no `updated_at` filter anywhere, so `created_at` is the sole
+# incremental cursor; templates and signers are full refresh only.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ DOCUMENTS_RESOURCE: [incremental_field("created_at", IncrementalFieldType.DateTime)],
+ TEMPLATES_RESOURCE: [],
+ SIGNERS_RESOURCE: [],
+}
+
+ENDPOINT_PATHS: dict[str, str] = {
+ DOCUMENTS_RESOURCE: "/api/v1/docs/",
+ TEMPLATES_RESOURCE: "/api/v1/templates/",
+}
+
+# Signers have no list endpoint of their own — they're read from each document's detail response.
+DOCUMENT_DETAIL_PATH = "/api/v1/docs/{token}/"
+
+PRIMARY_KEYS: dict[str, list[str]] = {
+ DOCUMENTS_RESOURCE: ["token"],
+ TEMPLATES_RESOURCE: ["token"],
+ # Signer tokens look globally unique, but ZapSign doesn't document that guarantee, so the
+ # parent document token stays in the key (`_documents_token` is injected by the fan-out).
+ SIGNERS_RESOURCE: ["_documents_token", "token"],
+}
+
+# `created_at` never changes after creation, unlike `last_update_at`, so partitions stay stable.
+PARTITION_KEYS: dict[str, list[str]] = {
+ DOCUMENTS_RESOURCE: ["created_at"],
+ TEMPLATES_RESOURCE: ["created_at"],
+}
+
+# String timestamp columns coerced to datetimes by the framework's `convert_types`.
+TIMESTAMP_COLUMNS: dict[str, tuple[str, ...]] = {
+ DOCUMENTS_RESOURCE: ("created_at", "last_update_at"),
+ TEMPLATES_RESOURCE: ("created_at", "last_update_at"),
+ SIGNERS_RESOURCE: ("last_view_at", "signed_at"),
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/source.py
index cd907f9ead2b..259b4eed074a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/source.py
@@ -1,32 +1,221 @@
-from typing import cast
+from typing import TYPE_CHECKING, Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-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.common.base import (
+ FieldType,
+ ResumableSource,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSource,
+)
+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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zapsign import (
ZapSignSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.zapsign import zapsign as api_client
+from products.warehouse_sources.backend.temporal.data_imports.sources.zapsign.settings import (
+ DOCUMENTS_RESOURCE,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.zapsign.zapsign import ZapSignResumeConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+if TYPE_CHECKING:
+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
@SourceRegistry.register
-class ZapSignSource(SimpleSource[ZapSignSourceConfig]):
+class ZapSignSource(
+ ResumableSource[ZapSignSourceConfig, ZapSignResumeConfig],
+ WebhookSource[ZapSignSourceConfig],
+):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://docs.zapsign.com.br"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ZAPSIGN
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # ZapSign answers 403 (not 401) for a missing/invalid API token.
+ return {
+ "403 Client Error: Forbidden": (
+ "ZapSign rejected the API token. Copy a valid token from "
+ "Settings > Integrations > ZapSign API and reconnect."
+ ),
+ "401 Client Error: Unauthorized": (
+ "ZapSign rejected the API token. Copy a valid token from "
+ "Settings > Integrations > ZapSign API and reconnect."
+ ),
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.zapsign.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ @property
+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.zapsign.webhook_template import template
+
+ return template
+
+ @property
+ def webhook_resource_map(self) -> dict[str, str]:
+ # Every ZapSign document event routes to the single documents table, so the mapping is
+ # keyed by the wildcard the Hog template looks up.
+ return {DOCUMENTS_RESOURCE: "*"}
+
+ def get_schemas(
+ self,
+ config: ZapSignSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Documents are merge-only: the created_from filter re-fetches the watermark's whole day,
+ # so append mode would write duplicate rows.
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ merge_only=(DOCUMENTS_RESOURCE,),
+ supports_webhooks=(DOCUMENTS_RESOURCE,),
+ )
+
+ def validate_credentials(
+ self, config: ZapSignSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return api_client.validate_credentials(config.api_token, config.environment)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZapSignResumeConfig]:
+ return ResumableSourceManager[ZapSignResumeConfig](inputs, ZapSignResumeConfig)
+
+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
+ return WebhookSourceManager(inputs, inputs.logger)
+
+ def create_webhook(self, config: ZapSignSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:
+ return api_client.create_webhook(config.api_token, config.environment, webhook_url)
+
+ def delete_webhook(self, config: ZapSignSourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:
+ return api_client.delete_webhook()
+
+ def source_for_pipeline(
+ self,
+ config: ZapSignSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ZapSignResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return api_client.zapsign_source(
+ api_token=config.api_token,
+ environment=config.environment,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ webhook_source_manager=self.get_webhook_source_manager(inputs),
+ 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,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.ZAP_SIGN,
category=DataWarehouseSourceCategory.SALES,
label="ZapSign",
+ caption=(
+ "Connect your ZapSign account using an API token to sync documents, signers, and "
+ "templates. Find the token in ZapSign under **Settings** > **Integrations** > "
+ "**ZapSign API**."
+ ),
+ keywords=["e-signature", "esignature", "digital signature"],
iconPath="/static/services/zapsign.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/zapsign",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="environment",
+ label="Environment",
+ required=True,
+ defaultValue="production",
+ options=[
+ SourceFieldSelectConfigOption(label="Production (api.zapsign.com.br)", value="production"),
+ SourceFieldSelectConfigOption(
+ label="Sandbox (sandbox.api.zapsign.com.br)", value="sandbox"
+ ),
+ ],
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ webhookSetupCaption=(
+ "PostHog tries to register a webhook in ZapSign using your API token, subscribed "
+ "to all document events (created, signed, refused, deleted). The webhook "
+ "authenticates itself with an **Authorization** header PostHog generates and "
+ "verifies on every delivery.\n\n"
+ "**Manual setup** (only needed if auto-registration failed):\n\n"
+ "1. In ZapSign, go to **Settings** > **Integrations** > **ZapSign API** > **Webhooks**\n"
+ "2. Paste the webhook URL shown below\n"
+ "3. Add an **Authorization** header with a secret value you generate — paste the "
+ "same value into the field below so PostHog can verify deliveries\n"
+ "4. Subscribe to all document events\n\n"
+ "ZapSign has no API to look up webhooks later, so if you disconnect this source, "
+ "remove the webhook in ZapSign manually."
+ ),
+ webhookFields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="authorization_header",
+ label="Authorization header value",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Bearer my-secret",
+ caption=(
+ "The exact value ZapSign will send in the Authorization header. "
+ "Must match what's configured on the ZapSign webhook."
+ ),
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/tests/test_zapsign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/tests/test_zapsign.py
new file mode 100644
index 000000000000..6c2af12a585d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/tests/test_zapsign.py
@@ -0,0 +1,446 @@
+import json
+import datetime
+from typing import Any, cast
+from urllib.parse import parse_qs, urlsplit
+
+from unittest import mock
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+from requests import Response
+
+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.zapsign.settings import (
+ DOCUMENTS_RESOURCE,
+ SIGNERS_RESOURCE,
+ TEMPLATES_RESOURCE,
+ ZAPSIGN_BASE_URL,
+ ZAPSIGN_SANDBOX_BASE_URL,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.zapsign.zapsign import (
+ ZapSignResumeConfig,
+ _to_created_from,
+ _webhook_table_transformer,
+ base_url_for_environment,
+ create_webhook,
+ delete_webhook,
+ validate_credentials,
+ zapsign_source,
+)
+
+# 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"
+)
+# Direct-session calls (credential validation, webhook management) build theirs in the zapsign module.
+ZAPSIGN_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zapsign.zapsign.make_tracked_session"
+)
+
+
+def _json_response(payload: dict | list, url: str = f"{ZAPSIGN_BASE_URL}/api/v1/docs/") -> Response:
+ response = Response()
+ response.status_code = 200
+ response.url = url
+ response._content = json.dumps(payload).encode()
+ return response
+
+
+def _page(results: list[dict[str, Any]], next_url: str | None = None) -> Response:
+ return _json_response({"count": len(results), "next": next_url, "previous": None, "results": results})
+
+
+def _manager(resume: ZapSignResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+def _webhook_manager(enabled: bool = False) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.webhook_enabled = mock.AsyncMock(return_value=enabled)
+ return manager
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[requests.PreparedRequest]:
+ """Wire a mock session; capture each request AT PREPARE TIME as a real PreparedRequest.
+
+ Preparing with a real session applies the framework auth and encodes params exactly as they'd
+ go on the wire, so tests can assert the outgoing URL and Authorization header.
+ """
+ session.headers = {}
+ real = requests.Session()
+ prepared: list[requests.PreparedRequest] = []
+
+ def _prepare(request: Any) -> requests.PreparedRequest:
+ p = real.prepare_request(request)
+ prepared.append(p)
+ return p
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return prepared
+
+
+def _rows(source_response: Any) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+def _run(
+ endpoint: str,
+ responses: list[Response],
+ manager: mock.MagicMock,
+ *,
+ environment: str | None = "production",
+ webhook_manager: mock.MagicMock | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> tuple[Any, list[dict[str, Any]], list[requests.PreparedRequest]]:
+ with mock.patch(CLIENT_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ prepared = _wire(session, responses)
+ source_response = zapsign_source(
+ api_token="token-123",
+ environment=environment,
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ webhook_source_manager=webhook_manager or _webhook_manager(),
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ )
+ rows = _rows(source_response)
+ return source_response, rows, prepared
+
+
+def _query(prepared: requests.PreparedRequest) -> dict[str, list[str]]:
+ return parse_qs(urlsplit(cast("str", prepared.url)).query)
+
+
+class TestBaseUrlForEnvironment:
+ @parameterized.expand(
+ [
+ ("production", "production", ZAPSIGN_BASE_URL),
+ ("sandbox", "sandbox", ZAPSIGN_SANDBOX_BASE_URL),
+ ("unset", None, ZAPSIGN_BASE_URL),
+ ]
+ )
+ def test_maps_environment_to_host(self, _name: str, environment: str | None, expected: str) -> None:
+ assert base_url_for_environment(environment) == expected
+
+
+class TestToCreatedFrom:
+ @parameterized.expand(
+ [
+ ("datetime", datetime.datetime(2026, 5, 1, 12, 30, 45), "2026-05-01"),
+ ("date", datetime.date(2026, 5, 1), "2026-05-01"),
+ ("iso_string", "2026-05-01T12:30:45Z", "2026-05-01"),
+ ("none", None, None),
+ ]
+ )
+ def test_formats_watermark_as_date(self, _name: str, value: Any, expected: str | None) -> None:
+ assert _to_created_from(value) == expected
+
+
+class TestDocumentsSource:
+ def test_paginates_via_next_link_and_yields_rows(self) -> None:
+ page2_url = f"{ZAPSIGN_BASE_URL}/api/v1/docs/?page=2"
+ responses = [
+ _page([{"token": "d1", "created_at": "2026-01-01T00:00:00Z"}], next_url=page2_url),
+ _page([{"token": "d2", "created_at": "2026-01-02T00:00:00Z"}]),
+ ]
+ _, rows, prepared = _run(DOCUMENTS_RESOURCE, responses, _manager())
+
+ assert [row["token"] for row in rows] == ["d1", "d2"]
+ assert len(prepared) == 2
+ first_url = cast("str", prepared[0].url)
+ assert first_url.startswith(f"{ZAPSIGN_BASE_URL}/api/v1/docs/")
+ assert cast("str", prepared[1].url) == page2_url
+
+ def test_first_request_sends_stable_sort_and_signers_and_bearer_auth(self) -> None:
+ _, _, prepared = _run(DOCUMENTS_RESOURCE, [_page([])], _manager())
+
+ query = _query(prepared[0])
+ assert query["sort_order"] == ["asc"]
+ assert query["include_signers"] == ["true"]
+ assert prepared[0].headers["Authorization"] == "Bearer token-123"
+
+ def test_incremental_sends_created_from_date(self) -> None:
+ _, _, prepared = _run(
+ DOCUMENTS_RESOURCE,
+ [_page([])],
+ _manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.datetime(2026, 5, 1, 12, 30),
+ )
+
+ assert _query(prepared[0])["created_from"] == ["2026-05-01"]
+
+ def test_full_refresh_omits_created_from(self) -> None:
+ _, _, prepared = _run(DOCUMENTS_RESOURCE, [_page([])], _manager())
+
+ assert "created_from" not in _query(prepared[0])
+
+ def test_sandbox_environment_targets_sandbox_host(self) -> None:
+ _, _, prepared = _run(
+ DOCUMENTS_RESOURCE,
+ [_json_response({"count": 0, "next": None, "previous": None, "results": []})],
+ _manager(),
+ environment="sandbox",
+ )
+
+ assert cast("str", prepared[0].url).startswith(f"{ZAPSIGN_SANDBOX_BASE_URL}/api/v1/docs/")
+
+ def test_source_response_metadata(self) -> None:
+ source_response, _, _ = _run(DOCUMENTS_RESOURCE, [_page([])], _manager())
+
+ assert source_response.name == DOCUMENTS_RESOURCE
+ assert source_response.primary_keys == ["token"]
+ assert source_response.sort_mode == "asc"
+ assert source_response.partition_keys == ["created_at"]
+ assert source_response.partition_mode == "datetime"
+
+ def test_saves_resume_state_after_page_and_not_on_terminal_page(self) -> None:
+ page2_url = f"{ZAPSIGN_BASE_URL}/api/v1/docs/?page=2"
+ manager = _manager()
+ _run(DOCUMENTS_RESOURCE, [_page([{"token": "d1"}], next_url=page2_url), _page([{"token": "d2"}])], manager)
+
+ # One save (after the first page, pointing at page 2); the terminal page saves nothing.
+ assert manager.save_state.call_count == 1
+ saved = manager.save_state.call_args.args[0]
+ assert saved == ZapSignResumeConfig(endpoint=DOCUMENTS_RESOURCE, paginator_state={"next_url": page2_url})
+
+ def test_resumes_from_saved_next_url(self) -> None:
+ page2_url = f"{ZAPSIGN_BASE_URL}/api/v1/docs/?page=2"
+ resume = ZapSignResumeConfig(endpoint=DOCUMENTS_RESOURCE, paginator_state={"next_url": page2_url})
+ _, rows, prepared = _run(DOCUMENTS_RESOURCE, [_page([{"token": "d2"}])], _manager(resume))
+
+ assert [row["token"] for row in rows] == ["d2"]
+ assert cast("str", prepared[0].url) == page2_url
+
+ def test_ignores_resume_state_saved_by_a_different_endpoint(self) -> None:
+ resume = ZapSignResumeConfig(
+ endpoint=TEMPLATES_RESOURCE, paginator_state={"next_url": f"{ZAPSIGN_BASE_URL}/api/v1/templates/?page=9"}
+ )
+ _, _, prepared = _run(DOCUMENTS_RESOURCE, [_page([])], _manager(resume))
+
+ assert cast("str", prepared[0].url).startswith(f"{ZAPSIGN_BASE_URL}/api/v1/docs/")
+
+ def test_webhook_mode_reads_buffered_deliveries_instead_of_polling(self) -> None:
+ webhook_manager = _webhook_manager(enabled=True)
+ sentinel = object()
+ webhook_manager.get_items.return_value = sentinel
+
+ with mock.patch(CLIENT_SESSION_PATCH) as MockSession:
+ _wire(MockSession.return_value, [])
+ source_response = zapsign_source(
+ api_token="token-123",
+ environment="production",
+ endpoint=DOCUMENTS_RESOURCE,
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_manager(),
+ webhook_source_manager=webhook_manager,
+ db_incremental_field_last_value=None,
+ )
+
+ assert source_response.items() is sentinel
+ webhook_manager.get_items.assert_called_once_with(table_transformer=_webhook_table_transformer)
+
+
+class TestTemplatesSource:
+ def test_yields_rows_and_metadata(self) -> None:
+ responses = [_page([{"token": "t1", "name": "NDA", "created_at": "2026-01-01T00:00:00Z"}])]
+ source_response, rows, prepared = _run(TEMPLATES_RESOURCE, responses, _manager())
+
+ assert [row["token"] for row in rows] == ["t1"]
+ assert cast("str", prepared[0].url).startswith(f"{ZAPSIGN_BASE_URL}/api/v1/templates/")
+ assert source_response.primary_keys == ["token"]
+ assert source_response.partition_keys == ["created_at"]
+
+
+class TestSignersSource:
+ def test_fans_out_to_document_detail_and_injects_parent_token(self) -> None:
+ responses = [
+ _page([{"token": "d1"}, {"token": "d2"}]),
+ _json_response({"token": "d1", "signers": [{"token": "s1", "status": "signed"}]}),
+ _json_response({"token": "d2", "signers": [{"token": "s2", "status": "new"}, {"token": "s3"}]}),
+ ]
+ source_response, rows, prepared = _run(SIGNERS_RESOURCE, responses, _manager())
+
+ assert [(row["_documents_token"], row["token"]) for row in rows] == [
+ ("d1", "s1"),
+ ("d2", "s2"),
+ ("d2", "s3"),
+ ]
+ assert cast("str", prepared[1].url).startswith(f"{ZAPSIGN_BASE_URL}/api/v1/docs/d1/")
+ assert cast("str", prepared[2].url).startswith(f"{ZAPSIGN_BASE_URL}/api/v1/docs/d2/")
+ # Composite key: signer tokens aren't documented as globally unique.
+ assert source_response.primary_keys == ["_documents_token", "token"]
+ assert source_response.partition_keys is None
+
+
+class TestWebhookTableTransformer:
+ def test_keeps_latest_row_per_document_and_drops_event_fields(self) -> None:
+ table = table_from_py_list(
+ [
+ {
+ "token": "d1",
+ "status": "pending",
+ "event_type": "doc_created",
+ "signer_who_signed": {"token": "s1"},
+ "created_at": "2026-01-01T00:00:00Z",
+ "last_update_at": "2026-01-01T00:00:00Z",
+ },
+ {
+ "token": "d1",
+ "status": "signed",
+ "event_type": "doc_signed",
+ "signer_who_signed": {"token": "s1"},
+ "created_at": "2026-01-01T00:00:00Z",
+ "last_update_at": "2026-01-02T00:00:00Z",
+ },
+ {
+ "token": "d2",
+ "status": "pending",
+ "event_type": "doc_created",
+ "signer_who_signed": None,
+ "created_at": "2026-01-03T00:00:00Z",
+ "last_update_at": "2026-01-03T00:00:00Z",
+ },
+ ]
+ )
+
+ result = _webhook_table_transformer(table)
+ rows = {row["token"]: row for row in result.to_pylist()}
+
+ assert rows["d1"]["status"] == "signed"
+ assert rows["d2"]["status"] == "pending"
+ assert "event_type" not in result.column_names
+ assert "signer_who_signed" not in result.column_names
+
+ def test_parses_timestamps_and_skips_rows_without_token(self) -> None:
+ table = table_from_py_list(
+ [
+ {"token": "d1", "created_at": "2026-01-01T00:00:00Z", "last_update_at": "not-a-date"},
+ {"token": None, "created_at": "2026-01-01T00:00:00Z"},
+ ]
+ )
+
+ result = _webhook_table_transformer(table)
+ rows = result.to_pylist()
+
+ assert len(rows) == 1
+ assert rows[0]["created_at"] == datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)
+ assert rows[0]["last_update_at"] is None
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("forbidden", 403, False, "rejected the API token"),
+ ("unauthorized", 401, False, "rejected the API token"),
+ ("server_error", 500, False, "unexpected status (500)"),
+ ]
+ )
+ @patch(ZAPSIGN_SESSION_PATCH)
+ def test_maps_status_codes(
+ self, _name: str, status_code: int, expected_ok: bool, expected_error: str | None, mock_session: MagicMock
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ ok, error = validate_credentials("token-123", "production")
+
+ assert ok is expected_ok
+ if expected_error is None:
+ assert error is None
+ else:
+ assert expected_error in cast("str", error)
+
+ @patch(ZAPSIGN_SESSION_PATCH)
+ def test_returns_false_on_network_error(self, mock_session: MagicMock) -> None:
+ mock_session.return_value.get.side_effect = requests.ConnectionError("dns fail")
+
+ ok, error = validate_credentials("token-123", "production")
+
+ assert ok is False
+ assert "Could not reach ZapSign" in cast("str", error)
+
+ @patch(ZAPSIGN_SESSION_PATCH)
+ def test_probes_the_documents_list_on_the_selected_host(self, mock_session: MagicMock) -> None:
+ response = MagicMock()
+ response.status_code = 200
+ mock_session.return_value.get.return_value = response
+
+ validate_credentials("token-123", "sandbox")
+
+ called_url = mock_session.return_value.get.call_args.args[0]
+ assert called_url == f"{ZAPSIGN_SANDBOX_BASE_URL}/api/v1/docs/"
+
+
+class TestCreateWebhook:
+ @patch(ZAPSIGN_SESSION_PATCH)
+ def test_registers_all_document_events_with_generated_auth_header(self, mock_session: MagicMock) -> None:
+ response = MagicMock()
+ response.status_code = 200
+ response.raise_for_status = MagicMock()
+ mock_session.return_value.post.return_value = response
+
+ result = create_webhook("token-123", "production", "https://webhooks.posthog.com/dwh/abc")
+
+ assert result.success is True
+ called = mock_session.return_value.post.call_args
+ assert called.args[0] == f"{ZAPSIGN_BASE_URL}/api/v1/user/company/webhook/"
+ body = called.kwargs["json"]
+ assert body["url"] == "https://webhooks.posthog.com/dwh/abc"
+ assert body["type"] == ""
+ header = body["headers"][0]
+ assert header["name"] == "Authorization"
+ assert header["value"].startswith("Bearer ")
+ # The generated header value is handed back so the Hog template can verify deliveries.
+ assert result.extra_inputs == {"authorization_header": header["value"]}
+
+ @parameterized.expand(
+ [
+ ("forbidden", 403, "rejected the API token"),
+ ("server_error", 500, "ZapSign API error (500)"),
+ ]
+ )
+ @patch(ZAPSIGN_SESSION_PATCH)
+ def test_reports_http_errors(
+ self, _name: str, status_code: int, expected_error: str, mock_session: MagicMock
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ http_error = requests.HTTPError(response=response)
+ response.raise_for_status.side_effect = http_error
+ mock_session.return_value.post.return_value = response
+
+ result = create_webhook("token-123", "production", "https://webhooks.posthog.com/dwh/abc")
+
+ assert result.success is False
+ assert expected_error in cast("str", result.error)
+
+ @patch(ZAPSIGN_SESSION_PATCH)
+ def test_reports_network_errors(self, mock_session: MagicMock) -> None:
+ mock_session.return_value.post.side_effect = requests.ConnectionError("dns fail")
+
+ result = create_webhook("token-123", "production", "https://webhooks.posthog.com/dwh/abc")
+
+ assert result.success is False
+ assert "Could not reach ZapSign" in cast("str", result.error)
+
+
+class TestDeleteWebhook:
+ def test_reports_manual_deletion_required(self) -> None:
+ result = delete_webhook()
+
+ assert result.success is False
+ assert "Delete it in ZapSign" in cast("str", result.error)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/tests/test_zapsign_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/tests/test_zapsign_source.py
new file mode 100644
index 000000000000..c9cdc6e59ff8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/tests/test_zapsign_source.py
@@ -0,0 +1,196 @@
+import datetime
+from typing import Any
+
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.zapsign.settings import (
+ DOCUMENTS_RESOURCE,
+ SIGNERS_RESOURCE,
+ TEMPLATES_RESOURCE,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.zapsign.source import ZapSignSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.zapsign.zapsign import ZapSignResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+API_CLIENT_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.zapsign.zapsign"
+
+
+def _source_inputs(
+ schema_name: str = DOCUMENTS_RESOURCE,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=1,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ db_incremental_field_earliest_value=None,
+ incremental_field="created_at" if should_use_incremental_field else None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=mock.MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestZapSignSource:
+ def setup_method(self) -> None:
+ self.source = ZapSignSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.ZAPSIGN
+
+ def test_source_config_ships_released_as_alpha(self) -> None:
+ config = self.source.get_source_config
+
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.category == DataWarehouseSourceCategory.SALES
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/zapsign"
+
+ def test_source_config_fields(self) -> None:
+ fields = {field.name: field for field in self.source.get_source_config.fields}
+
+ assert set(fields.keys()) == {"api_token", "environment"}
+ api_token = fields["api_token"]
+ assert isinstance(api_token, SourceFieldInputConfig)
+ assert api_token.type == SourceFieldInputConfigType.PASSWORD
+ assert api_token.secret is True
+ environment = fields["environment"]
+ assert isinstance(environment, SourceFieldSelectConfig)
+ assert [option.value for option in environment.options] == ["production", "sandbox"]
+ assert environment.defaultValue == "production"
+
+ def test_webhook_fields_collect_the_authorization_header(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.webhookFields is not None
+ assert [field.name for field in config.webhookFields] == ["authorization_header"]
+ assert config.webhookSetupCaption is not None
+
+ @parameterized.expand(
+ [
+ (DOCUMENTS_RESOURCE, True, False, True),
+ (TEMPLATES_RESOURCE, False, False, False),
+ (SIGNERS_RESOURCE, False, False, False),
+ ]
+ )
+ def test_get_schemas_flags(
+ self, name: str, supports_incremental: bool, supports_append: bool, supports_webhooks: bool
+ ) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(mock.MagicMock(), team_id=1)}
+
+ schema = schemas[name]
+ assert schema.supports_incremental is supports_incremental
+ assert schema.supports_append is supports_append
+ assert schema.supports_webhooks is supports_webhooks
+
+ def test_get_schemas_documents_incremental_field_is_created_at(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(mock.MagicMock(), team_id=1)}
+
+ fields = schemas[DOCUMENTS_RESOURCE].incremental_fields
+ assert [field["field"] for field in fields] == ["created_at"]
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(mock.MagicMock(), team_id=1, names=[TEMPLATES_RESOURCE])
+
+ assert [schema.name for schema in schemas] == [TEMPLATES_RESOURCE]
+
+ def test_validate_credentials_delegates_to_api_client(self) -> None:
+ config = mock.MagicMock(api_token="token-123", environment="sandbox")
+ with mock.patch(f"{API_CLIENT_PATCH}.validate_credentials", return_value=(True, None)) as validate:
+ ok, error = self.source.validate_credentials(config, team_id=1)
+
+ assert (ok, error) == (True, None)
+ validate.assert_called_once_with("token-123", "sandbox")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_source_inputs())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ZapSignResumeConfig
+
+ def test_webhook_resource_map_routes_documents_to_wildcard(self) -> None:
+ assert self.source.webhook_resource_map == {DOCUMENTS_RESOURCE: "*"}
+
+ def test_webhook_template_is_registered(self) -> None:
+ template = self.source.webhook_template
+
+ assert template is not None
+ assert template.id == "template-warehouse-source-zapsign"
+ assert template.type == "warehouse_source_webhook"
+
+ def test_create_webhook_delegates_to_api_client(self) -> None:
+ config = mock.MagicMock(api_token="token-123", environment="production")
+ with mock.patch(f"{API_CLIENT_PATCH}.create_webhook") as create:
+ self.source.create_webhook(config, "https://webhooks.posthog.com/dwh/abc", team_id=1)
+
+ create.assert_called_once_with("token-123", "production", "https://webhooks.posthog.com/dwh/abc")
+
+ def test_delete_webhook_reports_manual_removal(self) -> None:
+ result = self.source.delete_webhook(mock.MagicMock(), "https://webhooks.posthog.com/dwh/abc", team_id=1)
+
+ assert result.success is False
+ assert "Delete it in ZapSign" in str(result.error)
+
+ def test_non_retryable_errors_cover_auth_failures(self) -> None:
+ errors = self.source.get_non_retryable_errors()
+
+ # ZapSign answers 403 for a bad token, so both auth statuses must permanently fail.
+ assert "403 Client Error: Forbidden" in errors
+ assert "401 Client Error: Unauthorized" in errors
+
+ @parameterized.expand(
+ [
+ ("incremental", True, datetime.datetime(2026, 5, 1)),
+ ("full_refresh", False, None),
+ ]
+ )
+ def test_source_for_pipeline_plumbs_arguments(
+ self, _name: str, should_use_incremental_field: bool, last_value: Any
+ ) -> None:
+ config = mock.MagicMock(api_token="token-123", environment="production")
+ inputs = _source_inputs(
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
+ resumable_manager = mock.MagicMock()
+ webhook_manager = mock.MagicMock()
+ expected = mock.MagicMock(spec=SourceResponse)
+
+ with (
+ mock.patch(f"{API_CLIENT_PATCH}.zapsign_source", return_value=expected) as zapsign_source,
+ mock.patch.object(self.source, "get_webhook_source_manager", return_value=webhook_manager),
+ ):
+ response = self.source.source_for_pipeline(config, resumable_manager, inputs)
+
+ assert response is expected
+ zapsign_source.assert_called_once_with(
+ api_token="token-123",
+ environment="production",
+ endpoint=DOCUMENTS_RESOURCE,
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=resumable_manager,
+ webhook_source_manager=webhook_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/webhook_template.py
new file mode 100644
index 000000000000..fc067c0f53c7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/webhook_template.py
@@ -0,0 +1,131 @@
+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+template: HogFunctionTemplateDC = HogFunctionTemplateDC(
+ status="alpha",
+ free=False,
+ type="warehouse_source_webhook",
+ id="template-warehouse-source-zapsign",
+ name="ZapSign warehouse source webhook",
+ description="Receive ZapSign webhook events for data warehouse ingestion",
+ icon_url="/static/services/zapsign.png",
+ category=["Data warehouse"],
+ code_language="hog",
+ code="""\
+if (request.method != 'POST') {
+ return {
+ 'httpResponse': {
+ 'status': 405,
+ 'body': 'Method not allowed'
+ }
+ }
+}
+
+if (not inputs.bypass_authorization_check) {
+ if (empty(inputs.authorization_header)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Authorization header value not configured',
+ }
+ }
+ }
+
+ let providedHeader := request.headers['authorization']
+
+ if (empty(providedHeader)) {
+ return {
+ 'httpResponse': {
+ 'status': 401,
+ 'body': 'Missing authorization header',
+ }
+ }
+ }
+
+ if (providedHeader != inputs.authorization_header) {
+ return {
+ 'httpResponse': {
+ 'status': 401,
+ 'body': 'Bad authorization header',
+ }
+ }
+ }
+}
+
+let eventType := request.body.event_type
+
+if (empty(eventType)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': 'No event type found, skipping'
+ }
+ }
+}
+
+// Document events carry the full document object; anything without a document
+// token (e.g. email-bounce or signer-level events) can't merge into the table.
+if (empty(request.body.token)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': f'No document token on event: {eventType}, skipping'
+ }
+ }
+}
+
+// Every ZapSign document event lands in the single `documents` warehouse table
+// — the schema_mapping is keyed by a wildcard ("*") which we look up here.
+let schemaId := inputs.schema_mapping?.['*']
+
+if (empty(schemaId)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': f'No schema mapping for event type: {eventType}, skipping'
+ }
+ }
+}
+
+produceToWarehouseWebhooks(request.body, schemaId)""",
+ inputs_schema=[
+ {
+ "type": "string",
+ "key": "authorization_header",
+ "label": "Authorization header value",
+ "required": False,
+ "secret": True,
+ "hidden": False,
+ "description": (
+ "The exact value ZapSign will send in the Authorization header on each delivery "
+ "(e.g. `Bearer my-secret`). PostHog rejects deliveries whose header does not match."
+ ),
+ },
+ {
+ "type": "boolean",
+ "key": "bypass_authorization_check",
+ "label": "Bypass authorization header check",
+ "description": ("If set, the Authorization header will not be checked. This is not recommended."),
+ "default": False,
+ "required": False,
+ "secret": False,
+ },
+ {
+ "type": "json",
+ "key": "schema_mapping",
+ "label": "Schema mapping",
+ "description": "Maps ZapSign resource names 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/zapsign/zapsign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/zapsign.py
new file mode 100644
index 000000000000..9cf4092014ff
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zapsign/zapsign.py
@@ -0,0 +1,388 @@
+"""Thin ZapSign API client used by the data warehouse source.
+
+Spec: https://docs.zapsign.com.br
+
+Everything in this module routes through the shared ``rest_source`` framework (tracked, retrying
+transport) or ``make_tracked_session`` directly, so outbound calls show up in our HTTP logs, OTel
+metrics, and sample-capture pipeline.
+"""
+
+import secrets
+import datetime
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import pyarrow as pa
+import structlog
+from asgiref.sync import async_to_sync
+from dateutil import parser as dateutil_parser
+from requests.exceptions import HTTPError, RequestException
+
+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.common.base import (
+ WebhookCreationResult,
+ WebhookDeletionResult,
+)
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+)
+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
+from products.warehouse_sources.backend.temporal.data_imports.sources.zapsign.settings import (
+ DOCUMENT_DETAIL_PATH,
+ DOCUMENTS_RESOURCE,
+ ENDPOINT_PATHS,
+ PARTITION_KEYS,
+ PRIMARY_KEYS,
+ SIGNERS_RESOURCE,
+ TEMPLATES_RESOURCE,
+ TIMESTAMP_COLUMNS,
+ ZAPSIGN_BASE_URL,
+ ZAPSIGN_SANDBOX_BASE_URL,
+)
+
+LOGGER = structlog.get_logger(__name__)
+
+REQUEST_TIMEOUT_SECONDS = 30
+
+WEBHOOK_CREATE_PATH = "/api/v1/user/company/webhook/"
+
+
+class ZapSignResumeConfig:
+ """Resume state for one endpoint's pagination.
+
+ ``paginator_state`` holds whatever the framework paginator checkpoints: ``{"next_url": ...}``
+ for the top-level list endpoints, or the fan-out state dict
+ (``{"completed": [...], "current": ..., "child_state": ...}``) for signers.
+ """
+
+ endpoint: str
+ paginator_state: dict[str, Any] | None = None
+
+
+def base_url_for_environment(environment: str | None) -> str:
+ return ZAPSIGN_SANDBOX_BASE_URL if environment == "sandbox" else ZAPSIGN_BASE_URL
+
+
+def _to_created_from(value: Any) -> str | None:
+ """Format the incremental watermark as ZapSign's ``created_from`` date (``YYYY-MM-DD``).
+
+ The filter is date-granular and inclusive, so the watermark's own day is re-fetched on every
+ incremental run — the merge on ``token`` dedupes those rows.
+ """
+ if value is None:
+ return None
+ if isinstance(value, datetime.datetime | datetime.date):
+ return value.strftime("%Y-%m-%d")
+ parsed = dateutil_parser.parse(str(value))
+ return parsed.strftime("%Y-%m-%d")
+
+
+def _timestamp_columns(endpoint: str) -> dict[str, dict[str, Any]]:
+ return {column: {"data_type": "timestamp"} for column in TIMESTAMP_COLUMNS.get(endpoint, ())}
+
+
+def _documents_resource(should_use_incremental_field: bool) -> EndpointResource:
+ return {
+ "name": DOCUMENTS_RESOURCE,
+ "table_name": DOCUMENTS_RESOURCE,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field
+ else "replace",
+ "endpoint": {
+ "path": ENDPOINT_PATHS[DOCUMENTS_RESOURCE],
+ "params": {
+ # Ascending creation order so the pipeline's incremental watermark advances safely.
+ "sort_order": "asc",
+ # Embeds each document's signer array — and guarantees the documented
+ # `{count, next, previous, results}` envelope shape.
+ "include_signers": "true",
+ "created_from": {
+ "type": "incremental",
+ "cursor_path": "created_at",
+ "initial_value": None,
+ "convert": _to_created_from,
+ }
+ if should_use_incremental_field
+ else None,
+ },
+ "data_selector": "results",
+ # A missing `results` key means the response shape changed — fail loud instead of
+ # silently syncing zero rows.
+ "data_selector_required": True,
+ },
+ "columns": _timestamp_columns(DOCUMENTS_RESOURCE),
+ "table_format": "delta",
+ }
+
+
+def _templates_resource() -> EndpointResource:
+ # Templates expose no filter or sort params — full refresh only.
+ return {
+ "name": TEMPLATES_RESOURCE,
+ "table_name": TEMPLATES_RESOURCE,
+ "write_disposition": "replace",
+ "endpoint": {
+ "path": ENDPOINT_PATHS[TEMPLATES_RESOURCE],
+ "data_selector": "results",
+ "data_selector_required": True,
+ },
+ "columns": _timestamp_columns(TEMPLATES_RESOURCE),
+ "table_format": "delta",
+ }
+
+
+def _signers_resources() -> list[EndpointResource]:
+ """Parent documents list + per-document detail fan-out that extracts the signer arrays."""
+ parent: EndpointResource = {
+ "name": DOCUMENTS_RESOURCE,
+ "table_name": DOCUMENTS_RESOURCE,
+ "write_disposition": "replace",
+ "endpoint": {
+ "path": ENDPOINT_PATHS[DOCUMENTS_RESOURCE],
+ "params": {"sort_order": "asc"},
+ "data_selector": "results",
+ "data_selector_required": True,
+ },
+ "table_format": "delta",
+ }
+ child: EndpointResource = {
+ "name": SIGNERS_RESOURCE,
+ "table_name": SIGNERS_RESOURCE,
+ "write_disposition": "replace",
+ "include_from_parent": ["token"],
+ "endpoint": {
+ "path": DOCUMENT_DETAIL_PATH,
+ "params": {
+ "token": {
+ "type": "resolve",
+ "resource": DOCUMENTS_RESOURCE,
+ "field": "token",
+ },
+ },
+ "data_selector": "signers",
+ },
+ "columns": _timestamp_columns(SIGNERS_RESOURCE),
+ "table_format": "delta",
+ }
+ return [parent, child]
+
+
+def _webhook_table_transformer(table: pa.Table) -> pa.Table:
+ """Reshape buffered webhook deliveries into document rows ready to merge on ``token``.
+
+ ZapSign's document webhooks (``doc_created``/``doc_signed``/``doc_refused``/``doc_deleted``)
+ carry the full document object plus event metadata. Delta merge only de-dupes across syncs, so
+ one batch holding several events for the same document must be collapsed here — we keep the
+ row with the greatest ``last_update_at``. Event-only fields are dropped so the row shape
+ matches the pull API, and the timestamp columns are parsed to real datetimes to line up with
+ the pull path's column types.
+ """
+ rows = table.to_pylist()
+ best_by_token: dict[str, tuple[float, dict[str, Any]]] = {}
+
+ for row in rows:
+ token = row.get("token")
+ if not token:
+ continue
+
+ row = dict(row)
+ row.pop("event_type", None)
+ row.pop("signer_who_signed", None)
+
+ for column in TIMESTAMP_COLUMNS[DOCUMENTS_RESOURCE]:
+ value = row.get(column)
+ if isinstance(value, str):
+ try:
+ row[column] = dateutil_parser.parse(value)
+ except (ValueError, OverflowError):
+ row[column] = None
+
+ updated = row.get("last_update_at") or row.get("created_at")
+ sort_key = updated.timestamp() if isinstance(updated, datetime.datetime) else 0.0
+
+ existing = best_by_token.get(token)
+ if existing is None or sort_key >= existing[0]:
+ best_by_token[token] = (sort_key, row)
+
+ return table_from_py_list([row for _, row in best_by_token.values()])
+
+
+def zapsign_source(
+ api_token: str,
+ environment: str | None,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ZapSignResumeConfig],
+ webhook_source_manager: WebhookSourceManager,
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+) -> SourceResponse:
+ base_url = base_url_for_environment(environment)
+
+ client_config: ClientConfig = {
+ "base_url": base_url,
+ "auth": {"type": "bearer", "token": api_token},
+ # ZapSign paginates DRF-style: the envelope's `next` field carries the full next-page URL.
+ "paginator": {"type": "json_response", "next_url_path": "next"},
+ # Pin pagination/resume URLs to the API host so a tampered `next` link can't exfiltrate
+ # the bearer token.
+ "allowed_hosts": [],
+ }
+
+ resources: list[str | EndpointResource]
+ if endpoint == SIGNERS_RESOURCE:
+ resources = [*_signers_resources()]
+ elif endpoint == DOCUMENTS_RESOURCE:
+ resources = [_documents_resource(should_use_incremental_field)]
+ elif endpoint == TEMPLATES_RESOURCE:
+ resources = [_templates_resource()]
+ else:
+ raise ValueError(f"Unknown ZapSign endpoint: {endpoint}")
+
+ config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": {},
+ "resources": resources,
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ # Only honor state written by this endpoint — replaying a documents cursor against
+ # templates would skip rows.
+ if resume is not None and resume.endpoint == endpoint and resume.paginator_state:
+ initial_paginator_state = resume.paginator_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Save AFTER a page is yielded so a crash re-yields the last page (merge dedupes on the
+ # primary key) rather than skipping it. The Redis TTL handles cleanup on completion.
+ if state:
+ resumable_source_manager.save_state(ZapSignResumeConfig(endpoint=endpoint, paginator_state=state))
+
+ framework_resources = rest_api_resources(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value if should_use_incremental_field else None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ resource = next(r for r in framework_resources if r.name == endpoint)
+
+ webhook_enabled = False
+ if endpoint == DOCUMENTS_RESOURCE:
+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)()
+
+ def items() -> Any:
+ if webhook_enabled:
+ return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)
+
+ def pages() -> Iterator[list[dict[str, Any]]]:
+ for page in resource:
+ yield [row for row in page if isinstance(row, dict)]
+
+ return pages()
+
+ partition_keys = PARTITION_KEYS.get(endpoint)
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=PRIMARY_KEYS[endpoint],
+ column_hints=resource.column_hints,
+ sort_mode="asc",
+ partition_keys=partition_keys,
+ partition_mode="datetime" if partition_keys else None,
+ partition_format="month" if partition_keys else None,
+ partition_count=1 if partition_keys else None,
+ partition_size=1 if partition_keys else None,
+ )
+
+
+def validate_credentials(api_token: str, environment: str | None) -> tuple[bool, str | None]:
+ """One cheap probe against the documents list to confirm the token is genuine.
+
+ ZapSign responds 403 (not 401) with a ``detail`` message when the token is missing or invalid.
+ """
+ base_url = base_url_for_environment(environment)
+ session = make_tracked_session(redact_values=(api_token,))
+ try:
+ response = session.get(
+ f"{base_url}/api/v1/docs/",
+ params={"page": 1},
+ headers={"Authorization": f"Bearer {api_token}"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ except RequestException as e:
+ return False, f"Could not reach ZapSign: {e}"
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, (
+ "ZapSign rejected the API token. Copy a valid token from "
+ "Settings > Integrations > ZapSign API and try again."
+ )
+ return False, f"ZapSign API returned an unexpected status ({response.status_code})."
+
+
+def create_webhook(api_token: str, environment: str | None, webhook_url: str) -> WebhookCreationResult:
+ """Register a ZapSign webhook pointing at ``webhook_url`` for all document events.
+
+ ``type: ""`` subscribes to every document event (created, signed, refused, deleted) — it
+ deliberately excludes email-bounce events, which aren't document-shaped. ZapSign echoes any
+ custom headers on each delivery, so we generate a secret ``Authorization`` header value and
+ return it via ``extra_inputs`` for the Hog template to verify.
+ """
+ base_url = base_url_for_environment(environment)
+ header_value = f"Bearer {secrets.token_urlsafe(32)}"
+ session = make_tracked_session(redact_values=(api_token, header_value))
+
+ try:
+ response = session.post(
+ f"{base_url}{WEBHOOK_CREATE_PATH}",
+ json={
+ "url": webhook_url,
+ "type": "",
+ "headers": [{"name": "Authorization", "value": header_value}],
+ },
+ headers={"Authorization": f"Bearer {api_token}"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ except HTTPError as e:
+ LOGGER.warning("Failed to register ZapSign webhook", error=str(e))
+ status_code = e.response.status_code if e.response is not None else None
+ if status_code in (401, 403):
+ return WebhookCreationResult(
+ success=False,
+ error="ZapSign rejected the API token while registering the webhook.",
+ )
+ return WebhookCreationResult(success=False, error=f"ZapSign API error ({status_code}).")
+ except RequestException as e:
+ LOGGER.warning("Could not reach ZapSign to register webhook", error=str(e))
+ return WebhookCreationResult(success=False, error=f"Could not reach ZapSign: {e}")
+
+ return WebhookCreationResult(success=True, extra_inputs={"authorization_header": header_value})
+
+
+def delete_webhook() -> WebhookDeletionResult:
+ # ZapSign's delete endpoint needs the webhook id returned at creation, and there is no list
+ # endpoint to rediscover it — so automatic deletion isn't possible.
+ return WebhookDeletionResult(
+ success=False,
+ error=(
+ "ZapSign doesn't support looking up webhooks via its API, so PostHog can't remove it "
+ "automatically. Delete it in ZapSign under Settings > Integrations > ZapSign API."
+ ),
+ )