:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement dropbox_sign import source (#66729)
Tom Owers38763d1f99d4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 39ae36944b9a..36a0067b9dcb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -114,6 +114,7 @@ the row lists both.| dixa | HTTP | requests | ✅ || docuseal | HTTP | requests | ✅ || doit | HTTP | requests | ✅ |+| dropbox_sign | HTTP | requests | ✅ || drip | HTTP | requests | ✅ || e_conomic | HTTP | requests | ✅ || easypost | HTTP | requests | ✅ |@@ -377,7 +378,6 @@ doesn't conflict with concurrent PRs.- dolibarr- dremio- dropbox-- dropbox_sign- dwolla- dynamics365- dynamodbdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/canonical_descriptions.pynew file mode 100644index 000000000000..403ff9093f48--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/canonical_descriptions.py@@ -0,0 +1,88 @@+"""Canonical, documentation-sourced descriptions for Dropbox Sign endpoints and columns.++Sourced from the official Dropbox Sign API reference (https://developers.hellosign.com/api/reference/).+Keyed by the endpoint names in `settings.py` `DROPBOX_SIGN_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Dropbox Sign table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "signature_requests": {+ "description": "A request sent to one or more signers to sign one or more documents.",+ "docs_url": "https://developers.hellosign.com/api/reference/operation/signatureRequestList/",+ "columns": {+ "signature_request_id": "Unique identifier for the signature request.",+ "title": "The title the signers see when reviewing the request.",+ "original_title": "The title used when the request was originally created.",+ "subject": "The subject line of the request email.",+ "message": "The message included with the request email.",+ "is_complete": "Whether all signers have signed the request.",+ "is_declined": "Whether any signer has declined the request.",+ "has_error": "Whether an error occurred during the signing process.",+ "test_mode": "Whether the request was created in test mode.",+ "requester_email_address": "Email address of the account that sent the request.",+ "signing_url": "URL where the request can be signed (embedded signing).",+ "details_url": "URL to view the request's details in Dropbox Sign.",+ "signatures": "The signers on the request and their signing status.",+ "cc_email_addresses": "Email addresses CC'd on the request.",+ "response_data": "Field values entered by signers on the documents.",+ "metadata": "Custom metadata attached to the request.",+ "created_at": "Unix timestamp at which the request was created.",+ },+ },+ "templates": {+ "description": "A reusable template that pre-defines documents, signer roles, and fields for signature requests.",+ "docs_url": "https://developers.hellosign.com/api/reference/operation/templateList/",+ "columns": {+ "template_id": "Unique identifier for the template.",+ "title": "The template's title.",+ "message": "The default message included with requests created from the template.",+ "is_creator": "Whether the connected account created the template.",+ "can_edit": "Whether the connected account can edit the template.",+ "is_locked": "Whether the template is locked from editing.",+ "is_embedded": "Whether the template is set up for embedded signing.",+ "signer_roles": "The signer roles defined on the template.",+ "cc_roles": "The CC roles defined on the template.",+ "documents": "The documents that make up the template.",+ "custom_fields": "Custom fields defined on the template.",+ "named_form_fields": "The form fields defined on the template's documents.",+ "accounts": "Accounts that have access to the template.",+ "metadata": "Custom metadata attached to the template.",+ },+ },+ "api_apps": {+ "description": "An API application registered under the account, used to embed Dropbox Sign and receive callbacks.",+ "docs_url": "https://developers.hellosign.com/api/reference/operation/apiAppList/",+ "columns": {+ "client_id": "Unique identifier (client id) for the API app.",+ "name": "The API app's name.",+ "domains": "The domains the API app is associated with.",+ "callback_url": "The URL events for this app are POSTed to.",+ "is_approved": "Whether the API app has been approved for production use.",+ "owner_account": "The account that owns the API app.",+ "options": "Configuration options for the API app.",+ "oauth": "OAuth settings for the API app.",+ "white_labeling_options": "White-labeling options applied to the API app.",+ "created_at": "Unix timestamp at which the API app was created.",+ },+ },+ "account": {+ "description": "The Dropbox Sign account connected via the API key.",+ "docs_url": "https://developers.hellosign.com/api/reference/operation/accountGet/",+ "columns": {+ "account_id": "Unique identifier for the account.",+ "email_address": "The account's email address.",+ "is_locked": "Whether the account is locked.",+ "is_paid_hs": "Whether the account has a paid Dropbox Sign subscription.",+ "is_paid_hf": "Whether the account has a paid HelloFax subscription.",+ "quotas": "The account's remaining API and signature-request quotas.",+ "callback_url": "The account-level callback URL events are POSTed to.",+ "role_code": "The account's role within its team.",+ "team_id": "Identifier of the team the account belongs to.",+ "locale": "The account's locale.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/dropbox_sign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/dropbox_sign.pynew file mode 100644index 000000000000..140f5a23443a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/dropbox_sign.py@@ -0,0 +1,167 @@+import base64+import dataclasses+from collections.abc import Iterator+from typing import Any++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.dropbox_sign.settings import (+ DROPBOX_SIGN_ENDPOINTS,+)++DROPBOX_SIGN_BASE_URL = "https://api.hellosign.com/v3"+# The API caps page_size at 100 (default 20); always request the max to minimize round-trips.+PAGE_SIZE = 100+++class DropboxSignRetryableError(Exception):+ pass+++class DropboxSignResumeConfig:+ # Next page number (1-based) to fetch. Page-number pagination is the only resume key the API+ # offers — there's no cursor token or stable time filter — so a mid-sync restart re-fetches from+ # this page and merge/replace dedupes the small overlap on the endpoint's primary key.+ page: int = 1+++def _get_headers(api_key: str) -> dict[str, str]:+ # HTTP Basic auth: the API key is the username with a blank password.+ token = base64.b64encode(f"{api_key}:".encode("ascii")).decode("ascii")+ return {"Authorization": f"Basic {token}", "Accept": "application/json"}+++def validate_credentials(api_key: str) -> bool:+ # /account is the cheapest authenticated probe — it returns the connected account with no+ # pagination and requires no special scope beyond a valid key.+ try:+ response = make_tracked_session().get(+ f"{DROPBOX_SIGN_BASE_URL}/account", headers=_get_headers(api_key), timeout=10+ )+ return response.status_code == 200+ except Exception:+ return False+++@retry(+ retry=retry_if_exception_type((DropboxSignRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ headers: dict[str, str],+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict:+ response = session.get(url, headers=headers, params=params, timeout=60)++ # Dropbox Sign returns 429 when a rate-limit window is exceeded (10-100 req/min depending on+ # tier/mode). Back off and retry; 5xx is treated the same.+ if response.status_code == 429 or response.status_code >= 500:+ raise DropboxSignRetryableError(f"Dropbox Sign API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Dropbox Sign API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _redact(item: Any, paths: list[str]) -> Any:+ """Strip sensitive nested values (dotted paths) from an upstream record in place before it is+ persisted to the warehouse, so a warehouse reader never sees them."""+ if not isinstance(item, dict):+ return item+ for path in paths:+ keys = path.split(".")+ parent: Any = item+ for key in keys[:-1]:+ if not isinstance(parent, dict):+ break+ parent = parent.get(key)+ else:+ if isinstance(parent, dict):+ parent.pop(keys[-1], None)+ return item+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DropboxSignResumeConfig],+) -> Iterator[Any]:+ config = DROPBOX_SIGN_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # One session reused across every page so urllib3 keeps the connection alive.+ session = make_tracked_session()+ url = f"{DROPBOX_SIGN_BASE_URL}{config.path}"++ if config.is_single_object:+ data = _fetch_page(session, url, headers, {}, logger)+ obj = data.get(config.data_key)+ if obj:+ batcher.batch(_redact(obj, config.redact_paths))+ while batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume is not None else 1++ while True:+ data = _fetch_page(session, url, headers, {"page": page, "page_size": PAGE_SIZE}, logger)+ items = data.get(config.data_key) or []+ num_pages = (data.get("list_info") or {}).get("num_pages") or 1++ for item in items:+ batcher.batch(_redact(item, config.redact_paths))+ while batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding so a crash re-yields (never skips) the in-flight page. Only+ # persist when a later page remains — the saved page is re-fetched on resume.+ if page < num_pages:+ resumable_source_manager.save_state(DropboxSignResumeConfig(page=page))++ if page >= num_pages or not items:+ break+ page += 1++ while batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def dropbox_sign_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DropboxSignResumeConfig],+) -> SourceResponse:+ config = DROPBOX_SIGN_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/settings.pynew file mode 100644index 000000000000..ccb1c5034320--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/settings.py@@ -0,0 +1,70 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class DropboxSignEndpointConfig:+ name: str+ # Path under the v3 base URL (https://api.hellosign.com/v3).+ path: str+ # Key in the JSON response body holding the records. For list endpoints this is the plural+ # collection (e.g. "signature_requests"); for single-object endpoints it's the singular+ # object key (e.g. "account").+ data_key: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # When True the endpoint returns a single object with no `list_info` / pagination.+ is_single_object: bool = False+ # Stable creation timestamp used for datetime partitioning. Dropbox Sign returns these as Unix+ # timestamps (ints), which the pipeline's datetime partitioner handles natively. None disables+ # partitioning for the endpoint (e.g. templates expose no creation timestamp).+ partition_key: Optional[str] = None+ should_sync_default: bool = True+ # Dotted paths to sensitive nested values stripped from every record before it is persisted to+ # the warehouse (e.g. an OAuth client secret a warehouse reader must never see).+ redact_paths: list[str] = field(default_factory=list)+++# The endpoints a user actually wants from Dropbox Sign's v3 API. All are full refresh: the API+# exposes no server-side `updated_after`/`since` cursor on any list endpoint (only a free-text+# `query` search string), so there is no reliable incremental field to advance a watermark on.+DROPBOX_SIGN_ENDPOINTS: dict[str, DropboxSignEndpointConfig] = {+ "signature_requests": DropboxSignEndpointConfig(+ name="signature_requests",+ path="/signature_request/list",+ data_key="signature_requests",+ primary_keys=["signature_request_id"],+ partition_key="created_at",+ # Incomplete requests expose a `signing_url` bearer link; never land it in the warehouse.+ redact_paths=["signing_url"],+ ),+ "templates": DropboxSignEndpointConfig(+ name="templates",+ path="/template/list",+ data_key="templates",+ primary_keys=["template_id"],+ ),+ "api_apps": DropboxSignEndpointConfig(+ name="api_apps",+ path="/api_app/list",+ data_key="api_apps",+ primary_keys=["client_id"],+ partition_key="created_at",+ # The API App object nests the OAuth client secret; never land it in the warehouse.+ redact_paths=["oauth.secret"],+ ),+ "account": DropboxSignEndpointConfig(+ name="account",+ path="/account",+ data_key="account",+ primary_keys=["account_id"],+ is_single_object=True,+ ),+}++ENDPOINTS = tuple(DROPBOX_SIGN_ENDPOINTS.keys())++# No endpoint has a server-side timestamp filter, so the advertised incremental-field menu is empty+# for every table. Kept for symmetry with the source interface and the other REST sources.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in DROPBOX_SIGN_ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/source.pyindex c473842c2f40..b46c37f1c827 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.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.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.dropbox_sign.dropbox_sign import (+ DropboxSignResumeConfig,+ dropbox_sign_source,+ validate_credentials as validate_dropbox_sign_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dropbox_sign.settings import (+ DROPBOX_SIGN_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DropboxSignSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class DropboxSignSource(SimpleSource[DropboxSignSourceConfig]):+class DropboxSignSource(ResumableSource[DropboxSignSourceConfig, DropboxSignResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DROPBOXSIGN@@ -24,7 +48,89 @@ class DropboxSignSource(SimpleSource[DropboxSignSourceConfig]):name=SchemaExternalDataSourceType.DROPBOX_SIGN,category=DataWarehouseSourceCategory.SALES,label="Dropbox Sign",- iconPath="/static/services/dropbox_sign.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Dropbox Sign API key to automatically pull your Dropbox Sign data into the PostHog Data warehouse.++You can create an API key in your [Dropbox Sign API settings](https://app.hellosign.com/home/myAccount#api). The API key is used with HTTP Basic authentication (the key as the username, with a blank password).""",+ iconPath="/static/services/dropbox_sign.png",+ docsUrl="https://posthog.com/docs/cdp/sources/dropbox-sign",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.dropbox_sign.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked API key surfaces as a requests HTTPError when `_fetch_page`+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop+ # the sync. Match the stable status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.hellosign.com": "Your Dropbox Sign API key is invalid or has been revoked. Create a new API key in your Dropbox Sign API settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.hellosign.com": "Your Dropbox Sign API key does not have permission to access this data. Check the key's permissions and your plan, then reconnect.",+ }++ def get_schemas(+ self,+ config: DropboxSignSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Dropbox Sign exposes no server-side timestamp cursor, so every table is full refresh only.+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = DROPBOX_SIGN_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: DropboxSignSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_dropbox_sign_credentials(config.api_key):+ return True, None++ return False, "Invalid Dropbox Sign API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DropboxSignResumeConfig]:+ return ResumableSourceManager[DropboxSignResumeConfig](inputs, DropboxSignResumeConfig)++ def source_for_pipeline(+ self,+ config: DropboxSignSourceConfig,+ resumable_source_manager: ResumableSourceManager[DropboxSignResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return dropbox_sign_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/test_dropbox_sign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/test_dropbox_sign.pynew file mode 100644index 000000000000..3fff819d4c17--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/test_dropbox_sign.py@@ -0,0 +1,292 @@+import base64+from typing import Any, cast++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.dropbox_sign import dropbox_sign+from products.warehouse_sources.backend.temporal.data_imports.sources.dropbox_sign.dropbox_sign import (+ DROPBOX_SIGN_BASE_URL,+ DropboxSignResumeConfig,+ _get_headers,+ dropbox_sign_source,+ get_rows,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dropbox_sign.settings import (+ DROPBOX_SIGN_ENDPOINTS,+ ENDPOINTS,+)+++class TestGetHeaders:+ def test_uses_http_basic_with_blank_password(self) -> None:+ headers = _get_headers("my-key")+ expected = base64.b64encode(b"my-key:").decode("ascii")+ assert headers["Authorization"] == f"Basic {expected}"+ assert headers["Accept"] == "application/json"+++class _FakeResumableManager:+ def __init__(self, state: DropboxSignResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[DropboxSignResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> DropboxSignResumeConfig | None:+ return self._state++ def save_state(self, data: DropboxSignResumeConfig) -> None:+ self.saved.append(data)+++def _page_body(data_key: str, items: list[dict], page: int, num_pages: int) -> dict:+ return {+ "list_info": {"page": page, "num_pages": num_pages, "num_results": 0, "page_size": 100},+ data_key: items,+ }+++class TestGetRows:+ @staticmethod+ def _collect(+ endpoint: str,+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages_by_page_number: dict[int, dict],+ ) -> tuple[list[dict], list[dict[str, Any]]]:+ """Drive ``get_rows`` with ``_fetch_page`` faked to serve responses by requested page."""+ sent_params: list[dict[str, Any]] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], params: dict[str, Any], logger: Any) -> dict:+ sent_params.append(dict(params))+ page = params.get("page", 1)+ return pages_by_page_number[page]++ monkeypatch.setattr(dropbox_sign, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for table in get_rows(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(table.to_pylist())+ return rows, sent_params++ def test_single_page_yields_all_rows(self, monkeypatch: Any) -> None:+ pages = {1: _page_body("signature_requests", [{"signature_request_id": "a"}], page=1, num_pages=1)}+ rows, sent = self._collect("signature_requests", _FakeResumableManager(), monkeypatch, pages)+ assert rows == [{"signature_request_id": "a"}]+ assert sent == [{"page": 1, "page_size": 100}]++ def test_walks_every_page(self, monkeypatch: Any) -> None:+ pages = {+ 1: _page_body("templates", [{"template_id": "t1"}], page=1, num_pages=3),+ 2: _page_body("templates", [{"template_id": "t2"}], page=2, num_pages=3),+ 3: _page_body("templates", [{"template_id": "t3"}], page=3, num_pages=3),+ }+ rows, sent = self._collect("templates", _FakeResumableManager(), monkeypatch, pages)+ assert [r["template_id"] for r in rows] == ["t1", "t2", "t3"]+ assert [p["page"] for p in sent] == [1, 2, 3]++ def test_stops_when_page_has_no_items(self, monkeypatch: Any) -> None:+ # A page claiming more pages but returning no items must still terminate (defensive).+ pages = {1: _page_body("templates", [], page=1, num_pages=5)}+ rows, sent = self._collect("templates", _FakeResumableManager(), monkeypatch, pages)+ assert rows == []+ assert [p["page"] for p in sent] == [1]++ def test_resume_starts_from_saved_page(self, monkeypatch: Any) -> None:+ pages = {+ 2: _page_body("templates", [{"template_id": "t2"}], page=2, num_pages=2),+ }+ manager = _FakeResumableManager(DropboxSignResumeConfig(page=2))+ rows, sent = self._collect("templates", manager, monkeypatch, pages)+ assert [r["template_id"] for r in rows] == ["t2"]+ assert [p["page"] for p in sent] == [2]++ def test_does_not_load_state_when_cannot_resume(self, monkeypatch: Any) -> None:+ pages = {1: _page_body("templates", [{"template_id": "t1"}], page=1, num_pages=1)}+ manager = _FakeResumableManager()+ load_spy = MagicMock(side_effect=manager.load_state)+ monkeypatch.setattr(manager, "load_state", load_spy)+ self._collect("templates", manager, monkeypatch, pages)+ load_spy.assert_not_called()++ def test_api_apps_oauth_secret_is_redacted(self, monkeypatch: Any) -> None:+ # The API App List response nests the OAuth client secret; it must never reach the warehouse.+ item = {"client_id": "c1", "oauth": {"callback_url": "https://x/cb", "secret": "sk_live_super_secret"}}+ pages = {1: _page_body("api_apps", [item], page=1, num_pages=1)}+ rows, _ = self._collect("api_apps", _FakeResumableManager(), monkeypatch, pages)+ # The pipeline JSON-serializes nested objects into a string column, so assert on the+ # serialized payload rather than a nested dict: the secret (key and value) must be gone,+ # while the rest of the record survives.+ assert rows[0]["client_id"] == "c1"+ assert "secret" not in rows[0]["oauth"]+ assert "sk_live_super_secret" not in rows[0]["oauth"]+ assert "callback_url" in rows[0]["oauth"]++ def test_signature_requests_signing_url_is_redacted(self, monkeypatch: Any) -> None:+ # Incomplete signature requests expose a `signing_url` bearer link; it must never reach the warehouse.+ item = {"signature_request_id": "sr1", "signing_url": "https://app.hellosign.com/sign/abc", "title": "Doc"}+ pages = {1: _page_body("signature_requests", [item], page=1, num_pages=1)}+ rows, _ = self._collect("signature_requests", _FakeResumableManager(), monkeypatch, pages)+ assert rows[0]["signature_request_id"] == "sr1"+ assert "signing_url" not in rows[0]+ assert rows[0]["title"] == "Doc"++ def test_single_object_endpoint_yields_one_row_without_pagination(self, monkeypatch: Any) -> None:+ captured: list[dict[str, Any]] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], params: dict[str, Any], logger: Any) -> dict:+ captured.append(dict(params))+ return {"account": {"account_id": "acc_1", "email_address": "[email protected]"}}++ monkeypatch.setattr(dropbox_sign, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for table in get_rows(+ api_key="key",+ endpoint="account",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ ):+ rows.extend(table.to_pylist())++ assert rows == [{"account_id": "acc_1", "email_address": "[email protected]"}]+ # Single-object endpoints send no pagination params.+ assert captured == [{}]+++class TestResumeStateSaving:+ """The resume page is saved AFTER a batch is yielded, and only while a later page remains."""++ def _drive_with_small_chunks(self, monkeypatch: Any, num_pages: int, items_per_page: int) -> _FakeResumableManager:+ manager = _FakeResumableManager()++ # Force a yield after every page by shrinking the batcher chunk size to the page size.+ real_batcher_cls = dropbox_sign.Batcher++ def small_batcher(*_args: Any, **kwargs: Any) -> Any:+ kwargs["chunk_size"] = items_per_page+ return real_batcher_cls(*_args, **kwargs)++ monkeypatch.setattr(dropbox_sign, "Batcher", small_batcher)++ def fake_fetch(session: Any, url: str, headers: dict[str, str], params: dict[str, Any], logger: Any) -> dict:+ page = params.get("page", 1)+ items = [{"signature_request_id": f"p{page}-{i}"} for i in range(items_per_page)]+ return _page_body("signature_requests", items, page=page, num_pages=num_pages)++ monkeypatch.setattr(dropbox_sign, "_fetch_page", fake_fetch)++ for _table in get_rows(+ api_key="key",+ endpoint="signature_requests",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ pass+ return manager++ def test_saves_each_non_terminal_page(self, monkeypatch: Any) -> None:+ manager = self._drive_with_small_chunks(monkeypatch, num_pages=3, items_per_page=2)+ # Pages 1 and 2 are non-terminal (a later page remains); page 3 is terminal and not saved.+ assert manager.saved == [DropboxSignResumeConfig(page=1), DropboxSignResumeConfig(page=2)]++ def test_single_page_saves_nothing(self, monkeypatch: Any) -> None:+ manager = self._drive_with_small_chunks(monkeypatch, num_pages=1, items_per_page=2)+ assert manager.saved == []+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code,expected",+ [(200, True), (401, False), (403, False), (500, False)],+ )+ def test_status_maps_to_bool(self, monkeypatch: Any, status_code: int, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ monkeypatch.setattr(dropbox_sign, "make_tracked_session", lambda *a, _s=session, **k: _s)++ assert dropbox_sign.validate_credentials("key") is expected, status_code++ def test_network_error_returns_false(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ monkeypatch.setattr(dropbox_sign, "make_tracked_session", lambda *a, **k: session)++ assert dropbox_sign.validate_credentials("key") is False+++class TestSourceResponse:+ @parameterized.expand(list(ENDPOINTS))+ def test_primary_keys_match_settings(self, endpoint: str) -> None:+ response = dropbox_sign_source(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == DROPBOX_SIGN_ENDPOINTS[endpoint].primary_keys++ @parameterized.expand(+ [+ ("signature_requests", True),+ ("api_apps", True),+ ("templates", False),+ ("account", False),+ ]+ )+ def test_partitioning_only_when_endpoint_has_partition_key(self, endpoint: str, partitioned: bool) -> None:+ response = dropbox_sign_source(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ if partitioned:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]+ assert response.partition_format == "month"+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_base_url_is_v3(self) -> None:+ assert DROPBOX_SIGN_BASE_URL == "https://api.hellosign.com/v3"+++class TestRetryClassification:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status_code: int) -> None:+ response = MagicMock()+ response.status_code = status_code+ response.ok = False+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(dropbox_sign.DropboxSignRetryableError):+ # Call the undecorated function body once via the public wrapper with a single attempt+ # would still retry; instead assert the classification directly.+ cast(Any, dropbox_sign._fetch_page).__wrapped__(session, "http://x", {}, {}, MagicMock())++ def test_client_error_raises_http_error(self) -> None:+ response = MagicMock()+ response.status_code = 400+ response.ok = False+ response.raise_for_status.side_effect = requests.HTTPError("400", response=cast(requests.Response, response))+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ cast(Any, dropbox_sign._fetch_page).__wrapped__(session, "http://x", {}, {}, MagicMock())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/test_dropbox_sign_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/test_dropbox_sign_source.pynew file mode 100644index 000000000000..edcefe14a72d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/test_dropbox_sign_source.py@@ -0,0 +1,163 @@+from typing import Any, cast++from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.dropbox_sign import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.dropbox_sign.dropbox_sign import (+ DropboxSignResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dropbox_sign.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.dropbox_sign.source import DropboxSignSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DropboxSignSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _inputs(schema_name: str = "templates") -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-1",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert DropboxSignSource().source_type == ExternalDataSourceType.DROPBOXSIGN++ def test_config_metadata(self) -> None:+ config = DropboxSignSource().get_source_config+ assert config.label == "Dropbox Sign"+ assert config.category == DataWarehouseSourceCategory.SALES+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Kept hidden while in alpha.+ assert config.unreleasedSource is True+ # docsUrl slug must match the posthog.com doc filename (kebab-case).+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/dropbox-sign"++ def test_single_password_api_key_field(self) -> None:+ fields = DropboxSignSource().get_source_config.fields+ assert len(fields) == 1+ field = fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.name == "api_key"+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.required is True+ assert field.secret is True+++class TestSchemas:+ def test_lists_all_endpoints_as_full_refresh(self) -> None:+ schemas = DropboxSignSource().get_schemas(MagicMock(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_names_filter(self) -> None:+ schemas = DropboxSignSource().get_schemas(MagicMock(), team_id=1, names=["templates"])+ assert [s.name for s in schemas] == ["templates"]++ def test_lists_tables_without_credentials_renders_documented_tables(self) -> None:+ # Static endpoint catalog (no I/O) opts the source into the public-docs table list.+ assert DropboxSignSource.lists_tables_without_credentials is True+ tables = DropboxSignSource().get_documented_tables()+ names = {t["name"] for t in tables}+ assert names == set(ENDPOINTS)+ sig = next(t for t in tables if t["name"] == "signature_requests")+ assert sig["sync_methods"] == ["Full refresh"]+ # Canonical descriptions flow through.+ assert sig["description"]+++class TestValidateCredentials:+ def test_valid_key(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(source_module, "validate_dropbox_sign_credentials", lambda key: True)+ ok, err = DropboxSignSource().validate_credentials(DropboxSignSourceConfig(api_key="k"), team_id=1)+ assert ok is True+ assert err is None++ def test_invalid_key(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(source_module, "validate_dropbox_sign_credentials", lambda key: False)+ ok, err = DropboxSignSource().validate_credentials(DropboxSignSourceConfig(api_key="k"), team_id=1)+ assert ok is False+ assert err == "Invalid Dropbox Sign API key"+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.hellosign.com/v3/account",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.hellosign.com/v3/template/list?page=1",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = DropboxSignSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.hellosign.com', port=443): Read timed out."),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.hellosign.com/v3/account"),+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.hellosign.com/v3/account"),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = DropboxSignSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestResumableManager:+ def test_returns_manager_bound_to_resume_config(self) -> None:+ manager = DropboxSignSource().get_resumable_source_manager(_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is DropboxSignResumeConfig+++class TestSourceForPipeline:+ def test_passes_schema_name_and_credentials_through(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_source(**kwargs: Any) -> str:+ captured.update(kwargs)+ return "response"++ monkeypatch.setattr(source_module, "dropbox_sign_source", fake_source)++ manager = MagicMock()+ result = DropboxSignSource().source_for_pipeline(+ DropboxSignSourceConfig(api_key="my-key"),+ manager,+ _inputs(schema_name="signature_requests"),+ )++ assert cast(Any, result) == "response"+ assert captured["api_key"] == "my-key"+ assert captured["endpoint"] == "signature_requests"+ assert captured["resumable_source_manager"] is managerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex f445a188ebdf..fe889fe91237 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -989,7 +989,7 @@ class DripSourceConfig(config.Config):@config.configclass DropboxSignSourceConfig(config.Config):- pass+ api_key: str@config.config