: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 woocommerce import source (#61159)
Tom Owers0e21d7b4b4f8
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 6b41fee1dabd..93460e245a73 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -97,6 +97,7 @@ the row lists both.| tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ || vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |+| woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ || workos | HTTP | requests + `rest_source.RESTClient` | ✅ || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -214,7 +215,6 @@ doesn't conflict with concurrent PRs.- twilio- twitter_ads- webflow-- woocommerce- workday- wrike- xerodiff --git a/posthog/temporal/data_imports/sources/common/rest_source/__init__.py b/posthog/temporal/data_imports/sources/common/rest_source/__init__.pyindex 925af8ce386f..6003b10137db 100644--- a/posthog/temporal/data_imports/sources/common/rest_source/__init__.py+++ b/posthog/temporal/data_imports/sources/common/rest_source/__init__.py@@ -211,6 +211,7 @@ def create_resources(headers=client_config.get("headers"),auth=create_auth(client_config.get("auth")),paginator=create_paginator(client_config.get("paginator")),+ session=client_config.get("session"),)hooks = create_response_hooks(endpoint_config.get("response_actions"))diff --git a/posthog/temporal/data_imports/sources/common/rest_source/typing.py b/posthog/temporal/data_imports/sources/common/rest_source/typing.pyindex 995ad4046531..76285bdf618e 100644--- a/posthog/temporal/data_imports/sources/common/rest_source/typing.py+++ b/posthog/temporal/data_imports/sources/common/rest_source/typing.py@@ -2,6 +2,8 @@ from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom typing import Any, Literal, Optional, TypedDict+from requests import Session+from .auth import APIKeyAuth, AuthConfigBase, BearerTokenAuth, HttpBasicAuth, TApiKeyLocationfrom .jsonpath_utils import TJsonPath, compile_pathfrom .paginators import (@@ -125,6 +127,9 @@ class ClientConfig(TypedDict, total=False):headers: Optional[dict[str, str]]auth: Optional[AuthConfig]paginator: Optional[PaginatorConfig]+ # Optional pre-built session. Sources that need SSRF-guarding or other custom+ # transport behaviour pass one here; left unset, RESTClient builds a tracked session.+ session: Optional[Session]class IncrementalArgs(TypedDict, total=False):diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 149ce0608573..27d517ef71a4 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -868,7 +868,9 @@ class WebflowSourceConfig(config.Config):@config.configclass WooCommerceSourceConfig(config.Config):- pass+ store_url: str+ consumer_key: str+ consumer_secret: str@config.configdiff --git a/posthog/temporal/data_imports/sources/woocommerce/settings.py b/posthog/temporal/data_imports/sources/woocommerce/settings.pynew file mode 100644index 000000000000..f3dc9fc5f7c9--- /dev/null+++ b/posthog/temporal/data_imports/sources/woocommerce/settings.py@@ -0,0 +1,58 @@+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++# Resources a user is likely to want from a WooCommerce store. Each maps to a+# top-level WooCommerce REST API v3 collection endpoint (relative to+# `/wp-json/wc/v3`). Fan-out resources (product variations, per-order notes and+# refunds) are intentionally left out of this first pass.+ENDPOINTS = (+ "products",+ "orders",+ "coupons",+ "customers",+ "product_categories",+ "product_tags",+ "product_reviews",+ "product_attributes",+ "tax_rates",+ "shipping_zones",+)++# Schema/endpoint name -> WooCommerce REST API path (relative to `/wp-json/wc/v3`).+ENDPOINT_PATHS: dict[str, str] = {+ "products": "/products",+ "orders": "/orders",+ "coupons": "/coupons",+ "customers": "/customers",+ "product_categories": "/products/categories",+ "product_tags": "/products/tags",+ "product_reviews": "/products/reviews",+ "product_attributes": "/products/attributes",+ "tax_rates": "/taxes",+ "shipping_zones": "/shipping/zones",+}++# Only products, orders and coupons expose a genuine server-side `modified_after`+# timestamp filter (added in WooCommerce 5.8.0), so only those advertise+# incremental sync. Everything else is full refresh.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ endpoint: [+ {+ "label": "date_modified_gmt",+ "type": IncrementalFieldType.DateTime,+ "field": "date_modified_gmt",+ "field_type": IncrementalFieldType.DateTime,+ }+ ]+ for endpoint in ("products", "orders", "coupons")+}++# Stable creation-time field to partition on, per endpoint. Endpoints whose+# objects carry no creation timestamp (categories, tags, attributes, tax rates,+# shipping zones) are left unpartitioned.+PARTITION_FIELDS: dict[str, str] = {+ "products": "date_created_gmt",+ "orders": "date_created_gmt",+ "coupons": "date_created_gmt",+ "customers": "date_created_gmt",+ "product_reviews": "date_created_gmt",+}diff --git a/posthog/temporal/data_imports/sources/woocommerce/source.py b/posthog/temporal/data_imports/sources/woocommerce/source.pyindex 08dfde744c68..563e7369fa4b 100644--- a/posthog/temporal/data_imports/sources/woocommerce/source.py+++ b/posthog/temporal/data_imports/sources/woocommerce/source.py@@ -1,29 +1,177 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import WooCommerceSourceConfig+from posthog.temporal.data_imports.sources.woocommerce.settings import ENDPOINTS, INCREMENTAL_FIELDS, PARTITION_FIELDS+from posthog.temporal.data_imports.sources.woocommerce.woocommerce import (+ WooCommerceResumeConfig,+ validate_credentials as validate_woocommerce_credentials,+ woocommerce_source,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class WooCommerceSource(SimpleSource[WooCommerceSourceConfig]):+class WooCommerceSource(ResumableSource[WooCommerceSourceConfig, WooCommerceResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WOOCOMMERCE+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "WooCommerce authentication failed. Please check your consumer key and secret.",+ "403 Client Error": "WooCommerce authentication failed or the API key lacks read permission for this resource.",+ }++ def get_schemas(+ self,+ config: WooCommerceSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(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: WooCommerceSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if not config.store_url or not config.consumer_key or not config.consumer_secret:+ return False, "Missing WooCommerce credentials"++ status = validate_woocommerce_credentials(+ config.store_url, config.consumer_key, config.consumer_secret, team_id+ )++ if status == 200:+ return True, None++ # A valid key may legitimately lack read scope for the probe endpoint. Accept that at+ # source-create time; sync-time 403s are caught by `get_non_retryable_errors`.+ if status == 403 and schema_name is None:+ return True, None++ if status == 403:+ return False, "WooCommerce API key lacks read permission for this resource. Please check the key scope."++ if status == 401:+ return False, "WooCommerce authentication failed. Please check your consumer key and secret."++ return False, "Could not connect to your WooCommerce store. Please check the store URL."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WooCommerceResumeConfig]:+ return ResumableSourceManager[WooCommerceResumeConfig](inputs, WooCommerceResumeConfig)++ def source_for_pipeline(+ self,+ config: WooCommerceSourceConfig,+ resumable_source_manager: ResumableSourceManager[WooCommerceResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ # Only the endpoints that expose a server-side `modified_after` filter sync+ # incrementally — guard against a stale schema requesting it elsewhere.+ use_incremental = inputs.should_use_incremental_field and inputs.schema_name in INCREMENTAL_FIELDS++ resource = woocommerce_source(+ store_url=config.store_url,+ consumer_key=config.consumer_key,+ consumer_secret=config.consumer_secret,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=use_incremental,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value if use_incremental else None,+ )++ response = SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=["id"],+ column_hints=resource.column_hints,+ # Incremental endpoints can't be reliably sorted ascending by the+ # `date_modified` cursor server-side, so we only commit the watermark+ # once the whole resource has been read (desc semantics).+ sort_mode="desc" if use_incremental else "asc",+ )++ partition_key = PARTITION_FIELDS.get(inputs.schema_name)+ if partition_key:+ response.partition_count = 1+ response.partition_size = 1+ response.partition_mode = "datetime"+ response.partition_format = "month"+ response.partition_keys = [partition_key]++ return response+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.WOO_COMMERCE,label="WooCommerce",+ caption=(+ "Enter your WooCommerce store URL and REST API consumer key/secret to pull your store data "+ "into the PostHog Data warehouse. Create keys under **WooCommerce → Settings → Advanced → "+ "REST API** with at least **Read** permission."+ ),iconPath="/static/services/woocommerce.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/woocommerce",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="store_url",+ label="Store URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://example.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="consumer_key",+ label="Consumer key",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="consumer_secret",+ label="Consumer secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",+ secret=True,+ ),+ ],+ ),)diff --git a/posthog/temporal/data_imports/sources/woocommerce/tests/test_woocommerce.py b/posthog/temporal/data_imports/sources/woocommerce/tests/test_woocommerce.pynew file mode 100644index 000000000000..eca74d289024--- /dev/null+++ b/posthog/temporal/data_imports/sources/woocommerce/tests/test_woocommerce.py@@ -0,0 +1,359 @@+import json+from collections.abc import Iterable+from datetime import UTC, date, datetime, timedelta, timezone+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Request, Response++from posthog.temporal.data_imports.sources.common.http import TrackedHTTPAdapter+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.woocommerce.settings import ENDPOINT_PATHS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.woocommerce.woocommerce import (+ DEFAULT_PER_PAGE,+ WooCommercePaginator,+ WooCommerceResumeConfig,+ _HostGuardedAdapter,+ _to_woocommerce_datetime,+ get_resource,+ normalize_store_url,+ validate_credentials,+ woocommerce_source,+)+++class TestNormalizeStoreUrl:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("https://example.com", "https://example.com"),+ ("https://example.com/", "https://example.com"),+ ("http://example.com", "https://example.com"),+ ("example.com", "https://example.com"),+ (" https://example.com/ ", "https://example.com"),+ ("https://shop.example.com/store", "https://shop.example.com/store"),+ ],+ )+ def test_normalize(self, raw: str, expected: str) -> None:+ assert normalize_store_url(raw) == expected+++class TestToWooCommerceDatetime:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, None),+ ("2024-01-01T00:00:00", "2024-01-01T00:00:00"),+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05"),+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05"),+ (date(2024, 5, 6), "2024-05-06T00:00:00"),+ ],+ )+ def test_format(self, value: Any, expected: Any) -> None:+ assert _to_woocommerce_datetime(value) == expected++ def test_tz_aware_converted_to_utc(self) -> None:+ plus_two = timezone(timedelta(hours=2))+ value = datetime(2024, 1, 2, 12, 0, 0, tzinfo=plus_two)+ assert _to_woocommerce_datetime(value) == "2024-01-02T10:00:00"+++class TestWooCommercePaginator:+ def _response(self, total_pages: int | None) -> MagicMock:+ response = MagicMock()+ response.headers = {} if total_pages is None else {"X-WP-TotalPages": str(total_pages)}+ return response++ def test_initial_state(self) -> None:+ paginator = WooCommercePaginator()+ assert paginator.page == 1+ assert paginator.per_page == DEFAULT_PER_PAGE+ assert paginator.has_next_page is True++ def test_init_request_sets_page_and_per_page(self) -> None:+ paginator = WooCommercePaginator()+ request = Request(method="GET", url="https://example.com/wp-json/wc/v3/products")+ paginator.init_request(request)+ assert request.params["page"] == 1+ assert request.params["per_page"] == DEFAULT_PER_PAGE++ def test_has_more_pages_via_header(self) -> None:+ paginator = WooCommercePaginator()+ paginator.update_state(self._response(total_pages=3), data=[{"id": 1}])+ assert paginator.has_next_page is True+ assert paginator.page == 2++ def test_stops_on_last_page_via_header(self) -> None:+ paginator = WooCommercePaginator(page=3)+ paginator.update_state(self._response(total_pages=3), data=[{"id": 1}])+ assert paginator.has_next_page is False+ assert paginator.page == 3++ def test_stops_on_empty_page(self) -> None:+ paginator = WooCommercePaginator()+ paginator.update_state(self._response(total_pages=5), data=[])+ assert paginator.has_next_page is False++ def test_fallback_continues_on_full_page_without_header(self) -> None:+ paginator = WooCommercePaginator(per_page=2)+ paginator.update_state(self._response(total_pages=None), data=[{"id": 1}, {"id": 2}])+ assert paginator.has_next_page is True+ assert paginator.page == 2++ def test_fallback_stops_on_short_page_without_header(self) -> None:+ paginator = WooCommercePaginator(per_page=2)+ paginator.update_state(self._response(total_pages=None), data=[{"id": 1}])+ assert paginator.has_next_page is False++ def test_resume_state_round_trip(self) -> None:+ paginator = WooCommercePaginator()+ paginator.update_state(self._response(total_pages=10), data=[{"id": 1}])+ assert paginator.get_resume_state() == {"page": 2}++ resumed = WooCommercePaginator()+ resumed.set_resume_state({"page": 2})+ assert resumed.page == 2+ assert resumed.has_next_page is True++ def test_resume_state_none_on_terminal_page(self) -> None:+ paginator = WooCommercePaginator(page=2)+ paginator.update_state(self._response(total_pages=2), data=[{"id": 1}])+ assert paginator.get_resume_state() is None+++def _endpoint(resource: Any) -> dict[str, Any]:+ # `EndpointResource["endpoint"]` is typed `str | Endpoint | None`; in our resources it's+ # always the dict form, so cast for indexing in assertions.+ return cast(dict[str, Any], resource["endpoint"])+++class TestGetResource:+ @pytest.mark.parametrize("endpoint", sorted(ENDPOINT_PATHS))+ def test_path_and_name(self, endpoint: str) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=False)+ assert resource["name"] == endpoint+ assert resource["table_name"] == endpoint+ assert _endpoint(resource)["path"] == ENDPOINT_PATHS[endpoint]+ assert resource["table_format"] == "delta"++ def test_full_refresh_uses_replace(self) -> None:+ resource = get_resource("customers", should_use_incremental_field=False)+ assert resource["write_disposition"] == "replace"+ assert _endpoint(resource)["params"] == {}++ @pytest.mark.parametrize("endpoint", sorted(INCREMENTAL_FIELDS))+ def test_incremental_uses_merge_and_modified_after(self, endpoint: str) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=True)+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}++ params = cast(dict[str, Any], _endpoint(resource)["params"])+ assert params["dates_are_gmt"] == "true"+ modified_after = cast(dict[str, Any], params["modified_after"])+ assert modified_after["type"] == "incremental"+ assert modified_after["cursor_path"] == "date_modified_gmt"++ def test_non_incremental_endpoint_stays_full_refresh_even_when_requested(self) -> None:+ # `customers` has no server-side modified filter, so incremental must not be wired up.+ resource = get_resource("customers", should_use_incremental_field=True)+ assert resource["write_disposition"] == "replace"+ assert "modified_after" not in cast(dict[str, Any], _endpoint(resource)["params"])+++def _make_http_response(body: list[dict[str, Any]], total_pages: int | None = None, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ if total_pages is not None:+ resp.headers["X-WP-TotalPages"] = str(total_pages)+ return resp+++class TestWooCommerceSourceResumeBehavior:+ """End-to-end resume behaviour of ``woocommerce_source`` via ``rest_api_resource``."""++ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> list[dict[str, Any]]:+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(+ "posthog.temporal.data_imports.sources.woocommerce.woocommerce._make_guarded_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ resource = woocommerce_source(+ store_url="https://example.com",+ consumer_key="ck_test",+ consumer_secret="cs_test",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ )+ list(cast(Iterable[Any], resource))+ return sent_params++ def test_fresh_run_saves_page_after_each_non_terminal_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response([{"id": 1}], total_pages=3),+ _make_http_response([{"id": 2}], total_pages=3),+ _make_http_response([{"id": 3}], total_pages=3),+ ]+ sent_params = self._drive("products", manager, responses)++ assert [p.get("page") for p in sent_params] == [1, 2, 3]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [WooCommerceResumeConfig(page=2), WooCommerceResumeConfig(page=3)]++ def test_resume_seeds_paginator_with_saved_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = WooCommerceResumeConfig(page=5)++ responses = [_make_http_response([{"id": 9}], total_pages=5)]+ sent_params = self._drive("products", manager, responses)++ assert [p.get("page") for p in sent_params] == [5]+ manager.load_state.assert_called_once()++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response([{"id": 1}], total_pages=1)]+ self._drive("products", manager, responses)++ manager.save_state.assert_not_called()++ def test_does_not_load_state_when_cannot_resume(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response([{"id": 1}], total_pages=1)]+ self._drive("products", manager, responses)++ manager.load_state.assert_not_called()++ def test_incremental_injects_modified_after_filter(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response([{"id": 1}], total_pages=1)]+ sent_params = self._drive(+ "orders",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),+ )++ first = sent_params[0]+ assert first["modified_after"] == "2024-01-02T03:04:05"+ assert first["dates_are_gmt"] == "true"+ assert first["page"] == 1+ assert first["per_page"] == DEFAULT_PER_PAGE+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code", [200, 401, 403, 404])+ def test_returns_status_code(self, status_code: int) -> None:+ with patch(+ "posthog.temporal.data_imports.sources.woocommerce.woocommerce._make_guarded_session"+ ) as MockSession:+ MockSession.return_value.get.return_value = MagicMock(status_code=status_code)+ assert validate_credentials("https://example.com", "ck", "cs", 123) == status_code++ def test_returns_none_on_connection_error(self) -> None:+ with patch(+ "posthog.temporal.data_imports.sources.woocommerce.woocommerce._make_guarded_session"+ ) as MockSession:+ MockSession.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("https://example.com", "ck", "cs", 123) is None++ def test_unsafe_host_short_circuits_without_request(self) -> None:+ with (+ patch(+ "posthog.temporal.data_imports.sources.woocommerce.woocommerce._is_host_safe",+ return_value=(False, "blocked"),+ ),+ patch("posthog.temporal.data_imports.sources.woocommerce.woocommerce._make_guarded_session") as MockSession,+ ):+ assert validate_credentials("https://169.254.169.254", "ck", "cs", 123) is None+ MockSession.return_value.get.assert_not_called()+++class TestHostGuardedAdapter:+ def _prepared(self, url: str) -> Any:+ request = MagicMock()+ request.url = url+ return request++ def test_blocks_redirect_to_internal_host(self) -> None:+ adapter = _HostGuardedAdapter(team_id=123)+ with patch(+ "posthog.temporal.data_imports.sources.woocommerce.woocommerce._is_host_safe",+ return_value=(False, "Hosts with internal IP addresses are not allowed"),+ ):+ # `requests` calls `send` again for the redirect hop, so a 30x toward an+ # internal address is caught here even though the original host was safe.+ with pytest.raises(ValueError, match="internal IP"):+ adapter.send(self._prepared("https://169.254.169.254/wp-json/wc/v3/products"))++ def test_allows_safe_host_and_delegates(self) -> None:+ adapter = _HostGuardedAdapter(team_id=123)+ sentinel = MagicMock()+ with (+ patch(+ "posthog.temporal.data_imports.sources.woocommerce.woocommerce._is_host_safe",+ return_value=(True, None),+ ),+ patch.object(TrackedHTTPAdapter, "send", return_value=sentinel) as mock_super_send,+ ):+ result = adapter.send(self._prepared("https://example.com/wp-json/wc/v3/products"))++ assert result is sentinel+ mock_super_send.assert_called_once()+++class TestSourceHostGuard:+ def test_woocommerce_source_rejects_unsafe_host(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with patch(+ "posthog.temporal.data_imports.sources.woocommerce.woocommerce._is_host_safe",+ return_value=(False, "Hosts with internal IP addresses are not allowed"),+ ):+ with pytest.raises(ValueError, match="internal IP"):+ woocommerce_source(+ store_url="https://169.254.169.254",+ consumer_key="ck",+ consumer_secret="cs",+ endpoint="products",+ team_id=123,+ job_id="job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=None,+ )diff --git a/posthog/temporal/data_imports/sources/woocommerce/tests/test_woocommerce_source.py b/posthog/temporal/data_imports/sources/woocommerce/tests/test_woocommerce_source.pynew file mode 100644index 000000000000..01f67a6b84a5--- /dev/null+++ b/posthog/temporal/data_imports/sources/woocommerce/tests/test_woocommerce_source.py@@ -0,0 +1,180 @@+from typing import Optional++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import WooCommerceSourceConfig+from posthog.temporal.data_imports.sources.woocommerce.settings import ENDPOINTS, INCREMENTAL_FIELDS, PARTITION_FIELDS+from posthog.temporal.data_imports.sources.woocommerce.source import WooCommerceSource+from posthog.temporal.data_imports.sources.woocommerce.woocommerce import WooCommerceResumeConfig++from products.data_warehouse.backend.types import ExternalDataSourceType++INCREMENTAL_ENDPOINTS = set(INCREMENTAL_FIELDS.keys())+++def _make_inputs(schema_name: str, should_use_incremental_field: bool = False, last_value: object = None):+ return mock.MagicMock(+ schema_name=schema_name,+ team_id=123,+ job_id="job-1",+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=last_value,+ )+++class TestWooCommerceSource:+ def setup_method(self):+ self.source = WooCommerceSource()+ self.team_id = 123+ self.config = WooCommerceSourceConfig(+ store_url="https://example.com",+ consumer_key="ck_test",+ consumer_secret="cs_test",+ )++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.WOOCOMMERCE++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "WooCommerce"+ assert config.label == "WooCommerce"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/woocommerce.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["store_url", "consumer_key", "consumer_secret"]++ consumer_secret = config.fields[2]+ assert isinstance(consumer_secret, SourceFieldInputConfig)+ assert consumer_secret.type == SourceFieldInputConfigType.PASSWORD+ assert consumer_secret.secret is True+ assert consumer_secret.required is True++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_lists_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))+ def test_get_schemas_incremental_only_for_supported_endpoints(self, endpoint):+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ expected = endpoint in INCREMENTAL_ENDPOINTS++ assert schema.supports_incremental is expected+ assert schema.supports_append is expected+ if expected:+ assert schema.incremental_fields[0]["field"] == "date_modified_gmt"+ else:+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"])+ assert [s.name for s in schemas] == ["orders"]++ def test_get_schemas_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ @pytest.mark.parametrize(+ "status, schema_name, expected_valid",+ [+ (200, None, True),+ (200, "orders", True),+ (401, None, False),+ (403, None, True), # valid key without scope for the probe endpoint -> allowed at create+ (403, "orders", False), # but rejected for a specific schema check+ (404, None, False),+ (None, None, False), # connection error+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.woocommerce.source.validate_woocommerce_credentials")+ def test_validate_credentials(self, mock_validate, status, schema_name, expected_valid):+ mock_validate.return_value = status++ is_valid, _ = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)++ assert is_valid is expected_valid+ mock_validate.assert_called_once_with("https://example.com", "ck_test", "cs_test", self.team_id)++ def test_validate_credentials_missing_fields(self):+ config = WooCommerceSourceConfig(store_url="", consumer_key="", consumer_secret="")+ is_valid, message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert message == "Missing WooCommerce credentials"++ def test_get_resumable_source_manager(self):+ manager = self.source.get_resumable_source_manager(_make_inputs("orders"))+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is WooCommerceResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.woocommerce.source.woocommerce_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):+ mock_resource = mock.MagicMock(name="orders", column_hints=None)+ mock_source.return_value = mock_resource+ manager = mock.MagicMock(spec=ResumableSourceManager)+ inputs = _make_inputs("orders", should_use_incremental_field=True, last_value="2024-01-01T00:00:00")++ response = self.source.source_for_pipeline(self.config, manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["store_url"] == "https://example.com"+ assert kwargs["consumer_key"] == "ck_test"+ assert kwargs["consumer_secret"] == "cs_test"+ assert kwargs["endpoint"] == "orders"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00"+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "desc"++ def test_source_for_pipeline_full_refresh_drops_last_value(self):+ manager = mock.MagicMock(spec=ResumableSourceManager)+ inputs = _make_inputs("customers", should_use_incremental_field=False, last_value="2024-01-01T00:00:00")++ with mock.patch("posthog.temporal.data_imports.sources.woocommerce.source.woocommerce_source") as mock_source:+ mock_source.return_value = mock.MagicMock(name="customers", column_hints=None)+ response = self.source.source_for_pipeline(self.config, manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["db_incremental_field_last_value"] is None+ assert response.sort_mode == "asc"++ def test_source_for_pipeline_ignores_incremental_for_non_incremental_endpoint(self):+ # A non-incremental endpoint must stay full refresh even if the flag is set, so it+ # doesn't advertise desc semantics or carry a cursor value it can't honor.+ manager = mock.MagicMock(spec=ResumableSourceManager)+ inputs = _make_inputs("customers", should_use_incremental_field=True, last_value="2024-01-01T00:00:00")++ with mock.patch("posthog.temporal.data_imports.sources.woocommerce.source.woocommerce_source") as mock_source:+ mock_source.return_value = mock.MagicMock(name="customers", column_hints=None)+ response = self.source.source_for_pipeline(self.config, manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is None+ assert response.sort_mode == "asc"++ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))+ def test_source_for_pipeline_partitioning(self, endpoint):+ manager = mock.MagicMock(spec=ResumableSourceManager)+ inputs = _make_inputs(endpoint)++ with mock.patch("posthog.temporal.data_imports.sources.woocommerce.source.woocommerce_source") as mock_source:+ mock_source.return_value = mock.MagicMock(name=endpoint, column_hints=None)+ response = self.source.source_for_pipeline(self.config, manager, inputs)++ expected_key: Optional[str] = PARTITION_FIELDS.get(endpoint)+ if expected_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [expected_key]+ else:+ assert response.partition_keys is Nonediff --git a/posthog/temporal/data_imports/sources/woocommerce/woocommerce.py b/posthog/temporal/data_imports/sources/woocommerce/woocommerce.pynew file mode 100644index 000000000000..cbcbf76ae91f--- /dev/null+++ b/posthog/temporal/data_imports/sources/woocommerce/woocommerce.py@@ -0,0 +1,278 @@+import dataclasses+from collections.abc import Mapping+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlparse++from requests import PreparedRequest, Request, Response, Session++from posthog.temporal.data_imports.sources.common.http import DEFAULT_RETRY, TrackedHTTPAdapter+from posthog.temporal.data_imports.sources.common.mixins import _is_host_safe+from posthog.temporal.data_imports.sources.common.rest_source import RESTAPIConfig, rest_api_resource+from posthog.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from posthog.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.woocommerce.settings import ENDPOINT_PATHS, INCREMENTAL_FIELDS++# All WooCommerce REST API v3 endpoints hang off this path on the store domain.+WOOCOMMERCE_API_BASE_PATH = "/wp-json/wc/v3"+# WooCommerce caps `per_page` at 100.+DEFAULT_PER_PAGE = 100+++class WooCommerceResumeConfig:+ page: int+++def normalize_store_url(store_url: str) -> str:+ """Normalize a user-supplied store URL to an HTTPS base with no trailing slash.++ The WooCommerce REST API requires HTTPS for consumer key/secret Basic Auth, so+ an `http://` (or scheme-less) value is upgraded to `https://`. Any path segment+ the user includes (e.g. a store hosted under `/store`) is preserved.+ """+ url = store_url.strip().rstrip("/")+ if url.startswith("http://"):+ url = "https://" + url[len("http://") :]+ elif not url.startswith("https://"):+ url = "https://" + url+ return url+++def _base_url(store_url: str) -> str:+ return f"{normalize_store_url(store_url)}{WOOCOMMERCE_API_BASE_PATH}"+++def _assert_host_safe(store_url: str, team_id: int) -> None:+ """Block SSRF: reject store URLs that resolve to internal/private hosts.++ The store URL is fully user-controlled and drives server-side requests, so it+ must be vetted before any outbound call. `_is_host_safe` is a no-op on+ self-hosted instances and blocks private/internal IPs on PostHog Cloud.+ """+ host = urlparse(normalize_store_url(store_url)).hostname or ""+ is_safe, error = _is_host_safe(host, team_id)+ if not is_safe:+ raise ValueError(error or "WooCommerce store host is not allowed")+++class _HostGuardedAdapter(TrackedHTTPAdapter):+ """Re-validate the destination host on every dispatched request, redirects included.++ The up-front `_assert_host_safe` check only vets the URL the user typed.+ `requests` invokes `send` once per hop, so an attacker who passes that check+ and then 30x-redirects the worker toward an internal address (the classic+ open-redirect SSRF bypass) is blocked here instead. Legitimate cross-host+ redirects to public hosts — e.g. apex→www canonicalization — still resolve.+ """++ def __init__(self, team_id: int, **kwargs: Any) -> None:+ self._team_id = team_id+ super().__init__(**kwargs)++ def send(+ self,+ request: PreparedRequest,+ stream: bool = False,+ timeout: float | tuple[float, float] | tuple[float, None] | None = None,+ verify: bool | str = True,+ cert: bytes | str | tuple[bytes | str, bytes | str] | None = None,+ proxies: Mapping[str, str] | None = None,+ ) -> Response:+ host = urlparse(request.url or "").hostname or ""+ is_safe, error = _is_host_safe(host, self._team_id)+ if not is_safe:+ raise ValueError(error or "WooCommerce store host is not allowed")+ return super().send(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)+++def _make_guarded_session(team_id: int, redact_values: tuple[str, ...] = ()) -> Session:+ """A tracked `requests.Session` that re-checks every hop's host against SSRF rules."""+ # nosemgrep: data-imports-http-transport-requests-session -- mounts a TrackedHTTPAdapter subclass below, so logging/metrics are preserved while adding per-hop host validation.+ session = Session()+ adapter = _HostGuardedAdapter(team_id, max_retries=DEFAULT_RETRY, redact_values=redact_values)+ session.mount("https://", adapter)+ session.mount("http://", adapter)+ return session+++def _to_woocommerce_datetime(value: Any) -> Optional[str]:+ """Format an incremental cursor value as the ISO8601 string WooCommerce expects.++ We pair this with `dates_are_gmt=true`, so timezone-aware values are normalized+ to UTC first. WooCommerce expects `YYYY-MM-DDTHH:MM:SS` with no offset.+ """+ if value is None:+ return None+ if isinstance(value, datetime):+ if value.tzinfo is not None:+ value = value.astimezone(UTC)+ return value.strftime("%Y-%m-%dT%H:%M:%S")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00")+ return str(value)+++class WooCommercePaginator(BasePaginator):+ """Page-number pagination for the WooCommerce REST API.++ WooCommerce returns the total page count in the `X-WP-TotalPages` header and a+ JSON array as the body. We page until the header says we're done, falling back+ to stopping on a short/empty page when the header is absent. The current page+ number is the resumable checkpoint.+ """++ def __init__(self, per_page: int = DEFAULT_PER_PAGE, page: int = 1) -> None:+ super().__init__()+ self.per_page = per_page+ self.page = page++ def init_request(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["page"] = self.page+ request.params["per_page"] = self.per_page++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ if not data:+ self._has_next_page = False+ return++ total_pages: Optional[int] = None+ header = response.headers.get("X-WP-TotalPages")+ if header is not None:+ try:+ total_pages = int(header)+ except ValueError:+ total_pages = None++ if total_pages is not None:+ self._has_next_page = self.page < total_pages+ else:+ # No header to lean on: stop once a page comes back shorter than a full batch.+ self._has_next_page = len(data) >= self.per_page++ if self._has_next_page:+ self.page += 1++ def update_request(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["page"] = self.page++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if self._has_next_page:+ return {"page": self.page}+ return None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ page = state.get("page")+ if page is not None:+ self.page = int(page)+ self._has_next_page = True+++def get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointResource:+ path = ENDPOINT_PATHS[endpoint]+ use_incremental = should_use_incremental_field and endpoint in INCREMENTAL_FIELDS++ params: dict[str, Any] = {}+ if use_incremental:+ params["modified_after"] = {+ "type": "incremental",+ "cursor_path": "date_modified_gmt",+ "initial_value": None,+ "convert": _to_woocommerce_datetime,+ }+ params["dates_are_gmt"] = "true"++ return {+ "name": endpoint,+ "table_name": endpoint,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",+ "endpoint": {+ # WooCommerce list endpoints return a top-level JSON array, so no+ # data_selector is needed.+ "path": path,+ "params": params,+ },+ "table_format": "delta",+ }+++def woocommerce_source(+ store_url: str,+ consumer_key: str,+ consumer_secret: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[WooCommerceResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+):+ _assert_host_safe(store_url, team_id)++ config: RESTAPIConfig = {+ "client": {+ "base_url": _base_url(store_url),+ "auth": {+ "type": "http_basic",+ "username": consumer_key,+ "password": consumer_secret,+ },+ "paginator": WooCommercePaginator(),+ # Re-vet every hop (redirects included) so a redirect to an internal host can't+ # smuggle the credential past the up-front `_assert_host_safe` check.+ "session": _make_guarded_session(team_id, redact_values=(consumer_key, consumer_secret)),+ },+ # write_disposition is set per-resource by get_resource, so no defaults are needed.+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"page": resume_config.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only while there's a next page to resume to; the Redis TTL cleans up on completion.+ if state and state.get("page"):+ resumable_source_manager.save_state(WooCommerceResumeConfig(page=int(state["page"])))++ return rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def validate_credentials(store_url: str, consumer_key: str, consumer_secret: str, team_id: int) -> Optional[int]:+ """Probe a cheap authenticated endpoint. Returns the HTTP status code, or None on a connection error.++ Returns None (treated as a connection failure by the caller) for store URLs that resolve to an+ internal/private host, so a blocked SSRF target never reaches an outbound request.+ """+ host = urlparse(normalize_store_url(store_url)).hostname or ""+ is_safe, _ = _is_host_safe(host, team_id)+ if not is_safe:+ return None++ try:+ # The guarded session re-checks the host on any redirect hop, so a public store that+ # 30x-redirects to an internal address can't slip the probe past the up-front check.+ response = _make_guarded_session(team_id, redact_values=(consumer_key, consumer_secret)).get(+ f"{_base_url(store_url)}/products",+ params={"per_page": 1},+ auth=(consumer_key, consumer_secret),+ timeout=30,+ )+ except Exception:+ return None+ return response.status_code