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 wufoo import source (#68567)

Tom Owersbff6fac649e0
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 271f508934fc..9ea8f40ad51f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -338,6 +338,7 @@ the row lists both.
| workable | HTTP | requests | ✅ |
| workos | HTTP | requests + `rest_source.RESTClient` | ✅ |
| wrike | HTTP | requests | ✅ |
+| wufoo | HTTP | requests | ✅ |
| zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |
| zendesk_sell | HTTP | requests | ✅ |
| zonka_feedback | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index f0df77a93c67..cc41d3b3eb90 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
@@ -3534,7 +3534,8 @@ class WrikeSourceConfig(config.Config):
@config.config
class WufooSourceConfig(config.Config):
- pass
+ subdomain: str
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/canonical_descriptions.py
new file mode 100644
index 000000000000..b2f4b5a9c958
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/canonical_descriptions.py
@@ -0,0 +1,57 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Wufoo REST API v3 docs (https://www.wufoo.com/docs/api/v3/).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "forms": {
+ "description": "A Wufoo form — the definition of a form used to collect entries, including its "
+ "URL, status, and settings.",
+ "docs_url": "https://www.wufoo.com/docs/api/v3/forms/",
+ "columns": {
+ "Name": "The name of the form.",
+ "Description": "The form's description.",
+ "RedirectMessage": "The confirmation message shown after a submission (when no redirect URL is set).",
+ "Url": "The URL slug of the form.",
+ "Email": "The email address that submission notifications are sent to.",
+ "IsPublic": "Whether the form is publicly accessible ('1') or disabled ('0').",
+ "Language": "The language the form is presented in.",
+ "StartDate": "The date the form starts accepting entries.",
+ "EndDate": "The date the form stops accepting entries.",
+ "EntryLimit": "The maximum number of entries the form will accept ('0' = unlimited).",
+ "EntryCountToday": "The number of entries submitted to the form today.",
+ "DateCreated": "The date and time the form was created.",
+ "DateUpdated": "The date and time the form was last updated.",
+ "Hash": "The unique hash identifying the form; used as the parent key for its entries and fields.",
+ },
+ },
+ "reports": {
+ "description": "A Wufoo report — a saved visualization/summary built on top of a form's entries.",
+ "docs_url": "https://www.wufoo.com/docs/api/v3/reports/",
+ "columns": {
+ "Name": "The name of the report.",
+ "Description": "The report's description.",
+ "IsPublic": "Whether the report is publicly accessible ('1') or private ('0').",
+ "Url": "The URL slug of the report.",
+ "DateCreated": "The date and time the report was created.",
+ "DateUpdated": "The date and time the report was last updated.",
+ "Hash": "The unique hash identifying the report.",
+ },
+ },
+ "users": {
+ "description": "A user on the Wufoo account, with their role and access level.",
+ "docs_url": "https://www.wufoo.com/docs/api/v3/users/",
+ "columns": {
+ "User": "The username of the account user.",
+ "Email": "The user's email address.",
+ "Type": "The user's account role (e.g. Administrator).",
+ "AccountUserId": "The numeric ID of the user within the account.",
+ "Hash": "The unique hash identifying the user.",
+ "Image": "The URL of the user's avatar image.",
+ "IsAccountOwner": "Whether the user owns the account ('1') or not ('0').",
+ "IsAdmin": "Whether the user has administrator access ('1') or not ('0').",
+ "TimeZone": "The user's configured time zone.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/settings.py
new file mode 100644
index 000000000000..859f3093b071
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/settings.py
@@ -0,0 +1,31 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@dataclass
+class WufooEndpointConfig:
+ name: str
+ # Path relative to https://<subdomain>.wufoo.com/api/v3 (includes the .json suffix).
+ path: str
+ # Top-level key in the JSON response that holds the list of records.
+ data_key: str
+ # Wufoo identifies every top-level object with a stable `Hash`, so it is a safe table-wide
+ # primary key (forms, reports, and users all expose one).
+ primary_keys: list[str] = field(default_factory=lambda: ["Hash"])
+
+
+# Top-level Wufoo REST API v3 list endpoints. Per-form fan-out resources (a form's fields,
+# entries, comments, widgets) require a parent form hash and are intentionally left out of this
+# first cut — they can't be listed without first enumerating forms.
+WUFOO_ENDPOINTS: dict[str, WufooEndpointConfig] = {
+ "forms": WufooEndpointConfig(name="forms", path="forms.json", data_key="Forms"),
+ "reports": WufooEndpointConfig(name="reports", path="reports.json", data_key="Reports"),
+ "users": WufooEndpointConfig(name="users", path="users.json", data_key="Users"),
+}
+
+ENDPOINTS = tuple(WUFOO_ENDPOINTS.keys())
+
+# Every endpoint is full refresh — Wufoo's account-level list endpoints expose no server-side
+# `updated_after`-style cursor, so there is no genuine incremental field to advance.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/source.py
index 080da459d4d2..2cddf3b28abc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/source.py
@@ -1,30 +1,156 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.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.generated_configs import WufooSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.wufoo.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.wufoo.wufoo import (
+ SUBDOMAIN_REGEX,
+ WufooResumeConfig,
+ validate_credentials as validate_wufoo_credentials,
+ wufoo_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class WufooSource(SimpleSource[WufooSourceConfig]):
+class WufooSource(ResumableSource[WufooSourceConfig, WufooResumeConfig]):
+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to
+ # render in public docs without credentials.
+ lists_tables_without_credentials = True
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.WUFOO
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API key is sent to <subdomain>.wufoo.com, so retargeting the subdomain on an existing
+ # source must force the key to be re-entered.
+ return ["subdomain"]
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.wufoo.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Auth failures surface as a requests HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the
+ # sync. The host is subdomain-specific, so match the stable status text only.
+ "401 Client Error: Unauthorized for url": "Your Wufoo API key is invalid, or the subdomain is wrong. Check both under Account → API Information and reconnect.",
+ "403 Client Error: Forbidden for url": "Your Wufoo API key does not have permission for this resource. Check that API access is enabled for the account.",
+ }
+
+ def get_schemas(
+ self,
+ config: WufooSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — Wufoo's account-level list endpoints expose no
+ # server-side timestamp filter, so there is no incremental cursor to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ 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: WufooSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if not SUBDOMAIN_REGEX.match(config.subdomain):
+ return False, "Wufoo subdomain is invalid"
+
+ status = validate_wufoo_credentials(config.api_key, config.subdomain)
+
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Wufoo credentials. Check your subdomain and API key under Account → API Information."
+ return False, "Could not connect to Wufoo. Please check your subdomain and API key."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WufooResumeConfig]:
+ return ResumableSourceManager[WufooResumeConfig](inputs, WufooResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: WufooSourceConfig,
+ resumable_source_manager: ResumableSourceManager[WufooResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return wufoo_source(
+ api_key=config.api_key,
+ subdomain=config.subdomain,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.WUFOO,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Wufoo",
+ caption="""Enter your Wufoo subdomain and API key to pull your Wufoo form data into the PostHog Data warehouse.
+
+Your **subdomain** is the account name in your Wufoo URL — e.g. `acme` for `acme.wufoo.com`.
+
+Your **API key** is on the **API Information** page of any form (log in, open a form in the Form Manager, then click **API Information**). The same key works across every form on the account.""",
iconPath="/static/services/wufoo.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/wufoo",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="subdomain",
+ label="Subdomain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="acme",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/tests/test_wufoo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/tests/test_wufoo.py
new file mode 100644
index 000000000000..b5fb6aba6cae
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/tests/test_wufoo.py
@@ -0,0 +1,185 @@
+import base64
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.wufoo import wufoo
+from products.warehouse_sources.backend.temporal.data_imports.sources.wufoo.settings import ENDPOINTS, WUFOO_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.wufoo.wufoo import (
+ PAGE_SIZE,
+ WufooResumeConfig,
+ WufooRetryableError,
+ _headers,
+ get_rows,
+ validate_credentials,
+ wufoo_source,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = wufoo._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: WufooResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[WufooResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> WufooResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: WufooResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(count: int, data_key: str = "Forms") -> dict[str, Any]:
+ return {data_key: [{"Hash": f"h{i}"} for i in range(count)]}
+
+
+class TestHeaders:
+ def test_basic_auth_uses_api_key_as_username_with_any_password(self) -> None:
+ # Wufoo authenticates with HTTP Basic where the API key is the username; a wrong header
+ # construction silently 401s every request, so pin the exact encoding.
+ header = _headers("secret-key")["Authorization"]
+ assert header.startswith("Basic ")
+ decoded = base64.b64decode(header.removeprefix("Basic ")).decode("ascii")
+ assert decoded == "secret-key:footastic"
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, dict], endpoint: str = "forms"
+ ) -> list[dict]:
+ def fake_fetch(session: Any, url: str, page_start: int, logger: Any) -> dict:
+ return pages[page_start]
+
+ monkeypatch.setattr(wufoo, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(wufoo, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="wufoo-key",
+ subdomain="acme",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_short_page_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {0: _page(2)})
+ assert len(rows) == 2
+ # The first page was short (< PAGE_SIZE), so no further page is requested or checkpointed.
+ assert manager.saved == []
+
+ def test_follows_offset_until_short_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {0: _page(PAGE_SIZE), PAGE_SIZE: _page(PAGE_SIZE), 2 * PAGE_SIZE: _page(3)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert len(rows) == 2 * PAGE_SIZE + 3
+ # State advances by PAGE_SIZE after each full page, and is never saved for the final short page.
+ assert [s.page_start for s in manager.saved] == [PAGE_SIZE, 2 * PAGE_SIZE]
+
+ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(WufooResumeConfig(page_start=PAGE_SIZE))
+ # Offset 0 must never be fetched on resume.
+ pages = {PAGE_SIZE: _page(2)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert len(rows) == 2
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {0: _page(0)})
+ assert rows == []
+
+ def test_uses_endpoint_data_key(self, monkeypatch: Any) -> None:
+ # Each endpoint wraps its rows under a distinct key; selecting the wrong one drops all rows.
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {0: _page(1, data_key="Users")}, endpoint="users")
+ assert len(rows) == 1
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: dict | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body or {}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(WufooRetryableError):
+ _fetch_page_unwrapped(session, "https://acme.wufoo.com/api/v3/forms.json", 0, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "https://acme.wufoo.com/api/v3/forms.json", 0, MagicMock())
+
+ def test_request_sends_pagestart_and_pagesize(self) -> None:
+ session = self._session_returning(200, _page(0))
+ _fetch_page_unwrapped(session, "https://acme.wufoo.com/api/v3/forms.json", PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"pageStart": PAGE_SIZE, "pageSize": PAGE_SIZE}
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status, expected",
+ [(200, 200), (401, 401), (403, 403), (500, 500)],
+ )
+ def test_returns_status_code(self, monkeypatch: Any, status: int, expected: int) -> None:
+ response = MagicMock()
+ response.status_code = status
+ session = MagicMock()
+ session.get.return_value = response
+ monkeypatch.setattr(wufoo, "make_tracked_session", lambda **kwargs: session)
+ assert validate_credentials("wufoo-key", "acme") == expected
+
+ def test_invalid_subdomain_short_circuits_without_request(self, monkeypatch: Any) -> None:
+ session = MagicMock()
+ monkeypatch.setattr(wufoo, "make_tracked_session", lambda **kwargs: session)
+ assert validate_credentials("wufoo-key", "bad subdomain!") is None
+ session.get.assert_not_called()
+
+ def test_connection_error_maps_to_none(self, monkeypatch: Any) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ monkeypatch.setattr(wufoo, "make_tracked_session", lambda **kwargs: session)
+ assert validate_credentials("wufoo-key", "acme") is None
+
+
+class TestWufooSourceResponse:
+ @parameterized.expand([("forms",), ("reports",), ("users",)])
+ def test_uses_hash_primary_key(self, endpoint: str) -> None:
+ response = wufoo_source(
+ api_key="wufoo-key",
+ subdomain="acme",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["Hash"]
+
+ def test_every_endpoint_uses_hash_primary_key(self) -> None:
+ assert all(config.primary_keys == ["Hash"] for config in WUFOO_ENDPOINTS.values())
+ assert set(WUFOO_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/tests/test_wufoo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/tests/test_wufoo_source.py
new file mode 100644
index 000000000000..1e886c613c81
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/tests/test_wufoo_source.py
@@ -0,0 +1,136 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import WufooSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.wufoo.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.wufoo.source import WufooSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.wufoo.wufoo import WufooResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestWufooSource:
+ def setup_method(self) -> None:
+ self.source = WufooSource()
+ self.team_id = 123
+ self.config = WufooSourceConfig(subdomain="acme", api_key="wufoo-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.WUFOO
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.label == "Wufoo"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible — it must not carry the scaffolding flag.
+ assert not config.unreleasedSource
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/wufoo"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["subdomain", "api_key"]
+
+ def test_field_types(self) -> None:
+ fields = {f.name: f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldInputConfig)}
+ # The subdomain determines where the key is sent, so it is a plain (non-secret) text field.
+ assert fields["subdomain"].type == SourceFieldInputConfigType.TEXT
+ assert fields["subdomain"].secret is False
+ # The API key is the credential and must be a preserved secret.
+ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD
+ assert fields["api_key"].secret is True
+
+ def test_connection_host_fields_cover_subdomain(self) -> None:
+ # The key is sent to <subdomain>.wufoo.com, so editing the subdomain must re-require the key.
+ assert self.source.connection_host_fields == ["subdomain"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["reports"])
+ assert [s.name for s in schemas] == ["reports"]
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://acme.wufoo.com/api/v3/forms.json?pageStart=0&pageSize=100",
+ "403 Client Error: Forbidden for url: https://acme.wufoo.com/api/v3/reports.json",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @pytest.mark.parametrize(
+ "unrelated_error",
+ [
+ "500 Server Error: Internal Server Error for url: https://acme.wufoo.com/api/v3/forms.json",
+ "429 Client Error: Too Many Requests for url: https://acme.wufoo.com/api/v3/users.json",
+ ],
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @pytest.mark.parametrize(
+ "status, expected_valid",
+ [(200, True), (401, False), (403, False), (500, False), (None, False)],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.wufoo.source.validate_wufoo_credentials"
+ )
+ def test_validate_credentials(
+ self, mock_validate: mock.MagicMock, status: int | None, expected_valid: bool
+ ) -> None:
+ mock_validate.return_value = status
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)
+ assert is_valid is expected_valid
+ if expected_valid:
+ assert message is None
+ else:
+ assert message is not None
+
+ def test_validate_credentials_rejects_bad_subdomain_without_probing(self) -> None:
+ bad_config = WufooSourceConfig(subdomain="not a domain!", api_key="wufoo-key")
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.wufoo.source.validate_wufoo_credentials"
+ ) as mock_validate:
+ is_valid, message = self.source.validate_credentials(bad_config, self.team_id)
+ assert is_valid is False
+ assert message == "Wufoo subdomain is invalid"
+ mock_validate.assert_not_called()
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is WufooResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.wufoo.source.wufoo_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_wufoo_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "forms"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_wufoo_source.call_args.kwargs
+ assert kwargs["api_key"] == "wufoo-key"
+ assert kwargs["subdomain"] == "acme"
+ assert kwargs["endpoint"] == "forms"
+ assert kwargs["resumable_source_manager"] is manager
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/wufoo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/wufoo.py
new file mode 100644
index 000000000000..98d5d8402cb4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wufoo/wufoo.py
@@ -0,0 +1,170 @@
+import re
+import base64
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+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.wufoo.settings import WUFOO_ENDPOINTS
+
+# Wufoo enforces a per-account hostname, so only the subdomain label is user-supplied. Restricting
+# it to host-safe characters keeps the request pinned to *.wufoo.com.
+SUBDOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9-]+$")
+
+# Wufoo caps `pageSize` at 100 rows per request.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+VALIDATE_TIMEOUT_SECONDS = 10
+MAX_RETRIES = 5
+
+
+class WufooRetryableError(Exception):
+ """Raised for transient API responses (429 / 5xx) so tenacity retries them."""
+
+
+class WufooResumeConfig:
+ # Row offset (Wufoo `pageStart`) of the next page to fetch. Limit/offset pagination is
+ # deterministic, so a crashed full-refresh sync resumes from the offset after the last page
+ # yielded; merge dedupes any re-pulled rows on the primary key.
+ page_start: int = 0
+
+
+def base_url(subdomain: str) -> str:
+ return f"https://{subdomain}.wufoo.com/api/v3"
+
+
+def _basic_token(api_key: str) -> str:
+ # Wufoo uses HTTP Basic auth with the API key as the username and any non-empty string as the
+ # password — the password value is ignored by Wufoo but must be present.
+ return base64.b64encode(f"{api_key}:footastic".encode("ascii")).decode("ascii")
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Basic {_basic_token(api_key)}", "Accept": "application/json"}
+
+
+def _redact_values(api_key: str) -> tuple[str, ...]:
+ # Mask both the raw key and the derived Basic token so neither leaks into logged URLs/samples.
+ return (api_key, _basic_token(api_key))
+
+
+@retry(
+ retry=retry_if_exception_type((WufooRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ page_start: int,
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.get(
+ url,
+ params={"pageStart": page_start, "pageSize": PAGE_SIZE},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise WufooRetryableError(f"Wufoo API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Wufoo API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_rows(
+ api_key: str,
+ subdomain: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[WufooResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = WUFOO_ENDPOINTS[endpoint]
+ # One session reused across pages so urllib3 keeps the connection alive. Redirects are pinned
+ # off so the user-supplied credential can't be replayed to a cross-host redirect target
+ # (SSRF / credential-exfiltration defense-in-depth). urllib3 retries are disabled so tenacity
+ # (on `_fetch_page`) is the single retry layer.
+ session = make_tracked_session(
+ headers=_headers(api_key),
+ redact_values=_redact_values(api_key),
+ allow_redirects=False,
+ retry=Retry(total=0),
+ )
+ url = f"{base_url(subdomain)}/{config.path}"
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page_start = resume.page_start if resume else 0
+ if resume and resume.page_start > 0:
+ logger.debug(f"Wufoo: resuming {endpoint} from pageStart {page_start}")
+
+ while True:
+ data = _fetch_page(session, url, page_start, logger)
+
+ items = data[config.data_key]
+ if not isinstance(items, list):
+ items = []
+ if items:
+ yield items
+
+ # A short (or empty) page means the account has no further rows for this endpoint.
+ if len(items) < PAGE_SIZE:
+ break
+
+ page_start += PAGE_SIZE
+ # Save state AFTER yielding so a crash re-fetches the page we just emitted rather than
+ # skipping it — merge dedupes the re-yielded rows on the primary key.
+ resumable_source_manager.save_state(WufooResumeConfig(page_start=page_start))
+
+
+def wufoo_source(
+ api_key: str,
+ subdomain: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[WufooResumeConfig],
+) -> SourceResponse:
+ config = WUFOO_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ subdomain=subdomain,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def validate_credentials(api_key: str, subdomain: str) -> Optional[int]:
+ """Probe a cheap list endpoint. Returns the HTTP status code, or ``None`` on a connection error."""
+ if not SUBDOMAIN_REGEX.match(subdomain):
+ return None
+ url = f"{base_url(subdomain)}/forms.json"
+ try:
+ response = make_tracked_session(
+ headers=_headers(api_key),
+ redact_values=_redact_values(api_key),
+ allow_redirects=False,
+ retry=Retry(total=0),
+ ).get(url, params={"pageSize": 1}, timeout=VALIDATE_TIMEOUT_SECONDS)
+ except Exception:
+ return None
+
+ return response.status_code