: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
fix(wordpress): handle non-JSON responses without crashing (#73278)
Tom Owers73e020adc2a1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/source.pyindex fb630257aa0f..2e2fe64e7e53 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/source.py@@ -105,6 +105,10 @@ To sync private content or authenticate, create an [Application Password](https:"404 Client Error": "WordPress returned 404 (Not Found) for this collection. The REST API or this specific endpoint (for example /users, which security plugins often block to prevent user enumeration) may be disabled or restricted on your site. Enable REST API access for it, or remove this table from the sync.",HOST_NOT_ALLOWED_ERROR: "The WordPress site URL is not allowed. Please use a publicly reachable site URL.",HTTP_NOT_ALLOWED_ERROR: "The WordPress site URL must use HTTPS when credentials are provided. Please update the site URL to use https://.",+ # A 2xx response whose body isn't JSON (an HTML error/login/maintenance page, often from+ # a security or caching plugin) can't be turned into rows by retrying. Matches the stable+ # prefix RESTClientNonRetryableError uses, not the variable URL that follows.+ "Non-JSON response from": "The WordPress site returned a non-JSON response (for example an HTML error, login, or maintenance page) instead of data. Confirm the REST API is enabled and reachable at this URL and isn't blocked by a security or caching plugin, then try again.",}def get_canonical_descriptions(self) -> CanonicalDescriptions:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/tests/test_wordpress.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/tests/test_wordpress.pyindex 5c7d383efa6f..9c30a180979f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/tests/test_wordpress.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/tests/test_wordpress.py@@ -6,6 +6,9 @@ from unittest import mockimport requests+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (+ RESTClientNonRetryableError,+)from products.warehouse_sources.backend.temporal.data_imports.sources.wordpress import wordpress as wordpress_modulefrom products.warehouse_sources.backend.temporal.data_imports.sources.wordpress.settings import WORDPRESS_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.wordpress.wordpress import (@@ -13,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.wordpress.HTTP_NOT_ALLOWED_ERROR,WordpressHostNotAllowedError,WordpressResumeConfig,+ WordpressRetryableError,_build_initial_params,_build_initial_url,_format_incremental_value,@@ -27,7 +31,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.wordpress.def _response(- *, status_code: int = 200, json_data: Any = None, link: Optional[str] = None, text: str = ""+ *,+ status_code: int = 200,+ json_data: Any = None,+ link: Optional[str] = None,+ text: str = "",+ content: Optional[bytes] = None,+ json_raises: Optional[Exception] = None,) -> mock.MagicMock:response = mock.MagicMock()response.status_code = status_code@@ -35,11 +45,20 @@ def _response(response.is_redirect = status_code in (301, 302, 303, 307, 308)response.is_permanent_redirect = status_code in (301, 308)response.text = text- response.json.return_value = json_data+ if json_raises is not None:+ response.json.side_effect = json_raises+ else:+ response.json.return_value = json_data+ if content is not None:+ response.content = contentresponse.headers = {"Link": link} if link else {}return response+def _json_decode_error() -> requests.exceptions.JSONDecodeError:+ return requests.exceptions.JSONDecodeError("Expecting value: line 1 column 1 (char 0)", "", 0)++class _FakeBatcher:"""Yields whatever is buffered on every ``should_yield`` check, so the per-item save_state pathin ``get_rows`` is exercised without needing thousands of rows."""@@ -451,6 +470,40 @@ class TestGetRows:assert rows == []assert session.get.call_count == 1+ def test_empty_body_terminates_without_crashing(self):+ # A 2xx with an empty body used to crash get_rows with a raw JSONDecodeError; it must now+ # stop pagination cleanly.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ empty_body = _response(json_raises=_json_decode_error(), content=b"")+ rows, session = self._run(manager, [empty_body])++ assert rows == []+ assert session.get.call_count == 1++ def test_non_json_body_is_non_retryable(self):+ # A 2xx serving an HTML error/login page can't become data by retrying — fail fast and+ # non-retryably, without leaking the query string into the surfaced message.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ html = _response(json_raises=_json_decode_error(), content=b"<!DOCTYPE html><html><body>Login</body></html>")+ with pytest.raises(RESTClientNonRetryableError) as exc:+ self._run(manager, [html])+ assert str(exc.value).startswith("Non-JSON response from")+ assert "per_page" not in str(exc.value)++ def test_truncated_json_body_stays_retryable(self):+ # A body that begins as JSON but fails to parse is a truncated read, not a non-JSON error+ # page, so it must stay retryable rather than being classified non-retryable.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ truncated = _response(json_raises=_json_decode_error(), content=b'[{"id": 1}')+ with (+ mock.patch.object(wordpress_module, "_retry_wait", return_value=0),+ pytest.raises(WordpressRetryableError),+ ):+ self._run(manager, [truncated] * 5)+def test_does_not_follow_next_url_on_foreign_host(self):manager = mock.MagicMock()manager.can_resume.return_value = Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/tests/test_wordpress_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/tests/test_wordpress_source.pyindex 2da71e875c77..28a37fe22b5c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/tests/test_wordpress_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/tests/test_wordpress_source.py@@ -51,10 +51,20 @@ class TestWordpressSource:assert pass_field.required is Falseassert pass_field.secret is True- @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error", "404 Client Error"])+ @pytest.mark.parametrize(+ "expected_key", ["401 Client Error", "403 Client Error", "404 Client Error", "Non-JSON response from"]+ )def test_non_retryable_errors(self, expected_key):assert expected_key in self.source.get_non_retryable_errors()+ def test_non_json_response_message_matches_non_retryable_error(self):+ # A 2xx non-JSON body surfaces as "Non-JSON response from <url>"; the classifier matches on+ # the stable prefix, so the variable URL must not stop it being recognised as non-retryable.+ errors = self.source.get_non_retryable_errors()+ raised = "Non-JSON response from https://example.com/wp-json/wp/v2/posts"+ matches = [friendly for key, friendly in errors.items() if key in raised]+ assert matches and matches[0] is not None+def test_get_schemas_returns_all_endpoints(self):schemas = self.source.get_schemas(self.config, self.team_id)assert {s.name for s in schemas} == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/wordpress.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/wordpress.pyindex e8ea02484d2d..b308c1f7a5f3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/wordpress.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/wordpress.py@@ -14,6 +14,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (+ RESTClientNonRetryableError,+ _looks_like_json,+ _safe_url,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.wordpress.settings import (WORDPRESS_ENDPOINTS,@@ -359,7 +364,7 @@ def get_rows(wait=_retry_wait,reraise=True,)- def fetch_page(page_url: str) -> requests.Response:+ def fetch_page(page_url: str) -> tuple[requests.Response, Any]:# Don't follow redirects: an attacker-controlled host could 3xx to an internal address (SSRF).response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False@@ -382,12 +387,26 @@ def get_rows(logger.error(f"WordPress API error: status={response.status_code}, body={response.text}, url={page_url}")response.raise_for_status()- return response+ try:+ data = response.json()+ except requests.exceptions.JSONDecodeError as e:+ # Empty body on a 2xx is a complete "no more rows" answer — treat it as an empty page+ # and let pagination stop, rather than crashing.+ if not response.content or not response.content.strip():+ return response, None+ # A body that doesn't even begin with a JSON value is a non-JSON error page (HTML, a+ # login redirect, a WAF/maintenance page) served with a 2xx. Re-fetching returns the+ # same body, so fail fast and non-retryably. A body that starts as JSON but fails to+ # parse is a truncated read, which stays retryable.+ if not _looks_like_json(response.content):+ raise RESTClientNonRetryableError(f"Non-JSON response from {_safe_url(page_url)}") from e+ raise WordpressRetryableError(f"Malformed JSON response from {_safe_url(page_url)}: {e}") from e++ return response, datawhile True:- response = fetch_page(url)+ response, data = fetch_page(url)- data = response.json()if not isinstance(data, list) or not data:break