: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 wordpress import source (#65633)
Tom Owerseba6167b40fa
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 5c38cd4b7fa8..6f705f39e531 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -220,6 +220,7 @@ the row lists both.| vitally | HTTP | requests + `rest_source.RESTClient` | ✅ || webflow | HTTP | requests | ✅ || woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ |+| wordpress | HTTP | requests | ✅ || workable | HTTP | requests | ✅ || workos | HTTP | requests + `rest_source.RESTClient` | ✅ || wrike | HTTP | requests | ✅ |@@ -689,7 +690,6 @@ doesn't conflict with concurrent PRs.- watchmode- when_i_work- wikipedia_pageviews-- wordpress- workday- workflowmax- workrampdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 989e572a4449..242e2be502bf 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -3323,7 +3323,9 @@ class WooCommerceSourceConfig(config.Config):@config.configclass WordpressSourceConfig(config.Config):- pass+ site_url: str+ username: str | None = None+ application_password: str | None = None@config.configdiff --git a/posthog/temporal/data_imports/sources/wordpress/canonical_descriptions.py b/posthog/temporal/data_imports/sources/wordpress/canonical_descriptions.pynew file mode 100644index 000000000000..c297bcb61133--- /dev/null+++ b/posthog/temporal/data_imports/sources/wordpress/canonical_descriptions.py@@ -0,0 +1,120 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Sourced from the WordPress core REST API handbook (https://developer.wordpress.org/rest-api/reference/).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "posts": {+ "description": "Blog posts published on the WordPress site.",+ "docs_url": "https://developer.wordpress.org/rest-api/reference/posts/",+ "columns": {+ "id": "Unique identifier for the post.",+ "date": "The post's publication date, in the site's timezone.",+ "date_gmt": "The post's publication date, as GMT.",+ "modified": "The date the post was last modified, in the site's timezone.",+ "modified_gmt": "The date the post was last modified, as GMT.",+ "slug": "An alphanumeric identifier for the post, unique to its type.",+ "status": "A named status for the post (e.g. publish, draft, pending).",+ "type": "Type of post (e.g. post).",+ "link": "URL to the post.",+ "title": "The title for the post.",+ "content": "The content for the post.",+ "excerpt": "The excerpt for the post.",+ "author": "The ID for the author of the post.",+ "featured_media": "The ID of the featured media for the post.",+ "comment_status": "Whether or not comments are open on the post.",+ "ping_status": "Whether or not the post can be pinged.",+ "sticky": "Whether or not the post should be treated as sticky.",+ "categories": "The terms assigned to the post in the category taxonomy.",+ "tags": "The terms assigned to the post in the post_tag taxonomy.",+ },+ },+ "pages": {+ "description": "Static pages published on the WordPress site.",+ "docs_url": "https://developer.wordpress.org/rest-api/reference/pages/",+ "columns": {+ "id": "Unique identifier for the page.",+ "date": "The page's publication date, in the site's timezone.",+ "modified": "The date the page was last modified, in the site's timezone.",+ "slug": "An alphanumeric identifier for the page, unique to its type.",+ "status": "A named status for the page (e.g. publish, draft).",+ "parent": "The ID for the parent of the page.",+ "menu_order": "The order of the page in relation to other pages.",+ "title": "The title for the page.",+ "content": "The content for the page.",+ "author": "The ID for the author of the page.",+ },+ },+ "comments": {+ "description": "Comments left on posts and pages.",+ "docs_url": "https://developer.wordpress.org/rest-api/reference/comments/",+ "columns": {+ "id": "Unique identifier for the comment.",+ "post": "The ID of the associated post object.",+ "parent": "The ID for the parent of the comment.",+ "author": "The ID of the user object, if author was a user.",+ "author_name": "Display name for the comment author.",+ "author_email": "Email address for the comment author.",+ "date": "The date the comment was published, in the site's timezone.",+ "date_gmt": "The date the comment was published, as GMT.",+ "content": "The content of the comment.",+ "link": "URL to the comment.",+ "status": "State of the comment (e.g. approved, hold, spam).",+ "type": "Type of the comment.",+ },+ },+ "media": {+ "description": "Media library items (attachments) such as images and documents.",+ "docs_url": "https://developer.wordpress.org/rest-api/reference/media/",+ "columns": {+ "id": "Unique identifier for the attachment.",+ "date": "The attachment's publication date, in the site's timezone.",+ "modified": "The date the attachment was last modified, in the site's timezone.",+ "slug": "An alphanumeric identifier for the attachment, unique to its type.",+ "status": "A named status for the attachment.",+ "title": "The title for the attachment.",+ "author": "The ID for the author of the attachment.",+ "media_type": "Type of attachment (e.g. image, file).",+ "mime_type": "MIME type of the attachment.",+ "source_url": "URL to the original attachment file.",+ "alt_text": "Alternative text to display when attachment is not displayed.",+ "caption": "The attachment caption.",+ "post": "The ID for the associated post of the attachment.",+ },+ },+ "categories": {+ "description": "Terms in the built-in category taxonomy.",+ "docs_url": "https://developer.wordpress.org/rest-api/reference/categories/",+ "columns": {+ "id": "Unique identifier for the category.",+ "count": "Number of published posts for the category.",+ "description": "HTML description of the category.",+ "name": "HTML title for the category.",+ "slug": "An alphanumeric identifier for the category unique to its type.",+ "parent": "The parent category ID.",+ "taxonomy": "Type attribution for the category (category).",+ },+ },+ "tags": {+ "description": "Terms in the built-in post_tag taxonomy.",+ "docs_url": "https://developer.wordpress.org/rest-api/reference/tags/",+ "columns": {+ "id": "Unique identifier for the tag.",+ "count": "Number of published posts for the tag.",+ "description": "HTML description of the tag.",+ "name": "HTML title for the tag.",+ "slug": "An alphanumeric identifier for the tag unique to its type.",+ "taxonomy": "Type attribution for the tag (post_tag).",+ },+ },+ "users": {+ "description": "Users who have authored published content on the site.",+ "docs_url": "https://developer.wordpress.org/rest-api/reference/users/",+ "columns": {+ "id": "Unique identifier for the user.",+ "name": "Display name for the user.",+ "url": "URL of the user.",+ "description": "Description of the user.",+ "link": "Author URL of the user.",+ "slug": "An alphanumeric identifier for the user.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/wordpress/settings.py b/posthog/temporal/data_imports/sources/wordpress/settings.pynew file mode 100644index 000000000000..545962ff7162--- /dev/null+++ b/posthog/temporal/data_imports/sources/wordpress/settings.py@@ -0,0 +1,111 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class WordpressEndpointConfig:+ name: str+ path: str # Path under /wp-json/wp/v2, e.g. "/posts"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None+ # Maps an incremental field name to the WordPress query param that bounds it server-side.+ # WordPress filters on the local `post_date`/`post_modified` columns: `after`/`before` bound+ # `date`, `modified_after`/`modified_before` bound `modified`. Only fields listed here actually+ # filter server-side (verified against the live API — comments silently ignore `modified_after`).+ incremental_filter_params: dict[str, str] = field(default_factory=dict)+ # Column to order by on a full / first sync. Every wp/v2 list endpoint accepts `orderby`; the+ # incremental field name doubles as its `orderby` value (date, modified, id all valid).+ stable_order_by: str = "id"+ partition_key: Optional[str] = None+ primary_key: str = "id"+ page_size: int = 100 # WordPress caps per_page at 100; larger values 400+++# Core REST API (wp/v2) collections the canonical WordPress connectors (Airbyte/Fivetran) expose.+# Incremental support is only declared where a server-side timestamp filter actually drops rows+# (verified against the live API with a future-date cutoff).+WORDPRESS_ENDPOINTS: dict[str, WordpressEndpointConfig] = {+ "posts": WordpressEndpointConfig(+ name="posts",+ path="/posts",+ incremental_fields=[+ _datetime_incremental_field("modified"),+ _datetime_incremental_field("date"),+ ],+ default_incremental_field="modified",+ incremental_filter_params={"modified": "modified_after", "date": "after"},+ stable_order_by="date",+ partition_key="date",+ ),+ "pages": WordpressEndpointConfig(+ name="pages",+ path="/pages",+ incremental_fields=[+ _datetime_incremental_field("modified"),+ _datetime_incremental_field("date"),+ ],+ default_incremental_field="modified",+ incremental_filter_params={"modified": "modified_after", "date": "after"},+ stable_order_by="date",+ partition_key="date",+ ),+ "comments": WordpressEndpointConfig(+ name="comments",+ path="/comments",+ # Comments expose only a `date` column and silently ignore `modified_after`/`orderby=modified`+ # (both verified against the live API), so `date`/`after` is the only incremental cursor.+ incremental_fields=[+ _datetime_incremental_field("date"),+ ],+ default_incremental_field="date",+ incremental_filter_params={"date": "after"},+ stable_order_by="date",+ partition_key="date",+ ),+ "media": WordpressEndpointConfig(+ name="media",+ path="/media",+ incremental_fields=[+ _datetime_incremental_field("modified"),+ _datetime_incremental_field("date"),+ ],+ default_incremental_field="modified",+ incremental_filter_params={"modified": "modified_after", "date": "after"},+ stable_order_by="date",+ partition_key="date",+ ),+ # Taxonomy terms and users have no date column and no server-side timestamp filter -> full refresh+ # only. Ordered by id for stable pagination.+ "categories": WordpressEndpointConfig(+ name="categories",+ path="/categories",+ stable_order_by="id",+ ),+ "tags": WordpressEndpointConfig(+ name="tags",+ path="/tags",+ stable_order_by="id",+ ),+ "users": WordpressEndpointConfig(+ name="users",+ path="/users",+ stable_order_by="id",+ ),+}++ENDPOINTS = tuple(WORDPRESS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in WORDPRESS_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/wordpress/source.py b/posthog/temporal/data_imports/sources/wordpress/source.pyindex 200413f8f315..9f417fe10d39 100644--- a/posthog/temporal/data_imports/sources/wordpress/source.py+++ b/posthog/temporal/data_imports/sources/wordpress/source.py@@ -1,31 +1,150 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,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, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom 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 WordpressSourceConfig+from posthog.temporal.data_imports.sources.wordpress.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.wordpress.wordpress import (+ HOST_NOT_ALLOWED_ERROR,+ HTTP_NOT_ALLOWED_ERROR,+ WordpressResumeConfig,+ validate_credentials as validate_wordpress_credentials,+ wordpress_source,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class WordpressSource(SimpleSource[WordpressSourceConfig]):+class WordpressSource(ResumableSource[WordpressSourceConfig, WordpressResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WORDPRESS+ @property+ def connection_host_fields(self) -> list[str]:+ # `site_url` is where any stored application password is sent; retargeting it must re-require+ # the credentials so a member can't point them at a server they control.+ return ["site_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.WORDPRESS,category=DataWarehouseSourceCategory.PRODUCTIVITY,- label="Wordpress",+ label="WordPress",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Sync posts, pages, comments, media, categories, tags, and users from a self-hosted WordPress site via the core REST API (`/wp-json/wp/v2`).++Enter your site URL (for example `https://example.com`). Public, published content syncs without credentials.++To sync private content or authenticate, create an [Application Password](https://wordpress.org/documentation/article/application-passwords/) under **Users > Profile > Application Passwords** and enter your username and that password. Application passwords require WordPress 5.6+ and an HTTPS site.""",iconPath="/static/services/wordpress.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/wordpress",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="site_url",+ label="Site URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://example.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="username",+ label="Username (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="admin",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="application_password",+ label="Application password (optional)",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="xxxx xxxx xxxx xxxx xxxx xxxx",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid WordPress username or application password. Create a new application password and reconnect.",+ "403 Client Error": "Your WordPress credentials lack permission to read this data. Check the user's role and try again.",+ 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://.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.wordpress.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: WordpressSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ 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: WordpressSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_wordpress_credentials(config.site_url, config.username, config.application_password, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WordpressResumeConfig]:+ return ResumableSourceManager[WordpressResumeConfig](inputs, WordpressResumeConfig)++ def source_for_pipeline(+ self,+ config: WordpressSourceConfig,+ resumable_source_manager: ResumableSourceManager[WordpressResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return wordpress_source(+ site_url=config.site_url,+ username=config.username,+ application_password=config.application_password,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ team_id=inputs.team_id,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/posthog/temporal/data_imports/sources/wordpress/tests/test_wordpress.py b/posthog/temporal/data_imports/sources/wordpress/tests/test_wordpress.pynew file mode 100644index 000000000000..8510e35dc54f--- /dev/null+++ b/posthog/temporal/data_imports/sources/wordpress/tests/test_wordpress.py@@ -0,0 +1,531 @@+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.wordpress import wordpress as wordpress_module+from posthog.temporal.data_imports.sources.wordpress.settings import WORDPRESS_ENDPOINTS+from posthog.temporal.data_imports.sources.wordpress.wordpress import (+ HOST_NOT_ALLOWED_ERROR,+ HTTP_NOT_ALLOWED_ERROR,+ WordpressHostNotAllowedError,+ WordpressResumeConfig,+ _build_initial_params,+ _build_initial_url,+ _format_incremental_value,+ _get_headers,+ _is_same_host,+ _parse_next_url,+ get_rows,+ normalize_host,+ validate_credentials,+ wordpress_source,+)+++def _response(+ *, status_code: int = 200, json_data: Any = None, link: Optional[str] = None, text: str = ""+) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 400+ 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+ response.headers = {"Link": link} if link else {}+ return response+++class _FakeBatcher:+ """Yields whatever is buffered on every ``should_yield`` check, so the per-item save_state path+ in ``get_rows`` is exercised without needing thousands of rows."""++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self._buf: list[Any] = []++ def batch(self, item: Any) -> None:+ self._buf.append(item)++ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:+ return len(self._buf) > 0++ def get_table(self) -> list[Any]:+ rows, self._buf = self._buf, []+ return rows+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ (None, ""),+ ("", ""),+ ("example.com", "https://example.com"),+ ("https://example.com", "https://example.com"),+ ("https://example.com/", "https://example.com"),+ (" blog.example.com ", "https://blog.example.com"),+ ("https://example.com/wp-json/wp/v2", "https://example.com"),+ ("https://example.com/wp-json", "https://example.com"),+ ("http://example.com:8080/wp-json/wp/v2/", "http://example.com:8080"),+ # Subdirectory installs keep their base path.+ ("https://example.com/blog", "https://example.com/blog"),+ ("https://example.com/blog/wp-json/wp/v2", "https://example.com/blog"),+ # Scheme and host are lower-cased.+ ("HTTPS://Example.COM/", "https://example.com"),+ # Query, fragment, params, or embedded credentials are rejected outright — they could+ # redirect the worker's requests elsewhere on the allowed host (SSRF).+ ("https://example.com/?redirect=internal", ""),+ ("https://example.com/path?x=1", ""),+ ("https://example.com/#frag", ""),+ ("https://example.com/path;params", ""),+ ("https://user:[email protected]/", ""),+ ("https://[email protected]/", ""),+ ],+ )+ def test_normalize_host(self, raw, expected):+ assert normalize_host(raw) == expected+++class TestGetHeaders:+ def test_anonymous_has_no_authorization(self):+ headers = _get_headers(None, None)+ assert "Authorization" not in headers+ assert headers["Accept"] == "application/json"++ def test_partial_credentials_are_anonymous(self):+ # A username without a password (or vice versa) is not enough to authenticate.+ assert "Authorization" not in _get_headers("admin", "")+ assert "Authorization" not in _get_headers("", "secret")++ def test_basic_auth_header_is_base64_of_user_colon_password(self):+ import base64++ headers = _get_headers("admin", "abcd efgh")+ expected = base64.b64encode(b"admin:abcd efgh").decode()+ assert headers["Authorization"] == f"Basic {expected}"+++class TestFormatIncrementalValue:+ @pytest.mark.parametrize(+ "value, expected",+ [+ # WordPress compares against the site-local datetime; we emit wall-clock with no tz conversion.+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14"),+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14"),+ (date(2026, 3, 4), "2026-03-04T00:00:00"),+ ("already-a-cursor", "already-a-cursor"),+ ],+ )+ def test_format(self, value, expected):+ assert _format_incremental_value(value) == expected++ def test_no_z_or_offset_suffix(self):+ result = _format_incremental_value(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))+ assert "+00:00" not in result and not result.endswith("Z")+++class TestBuildInitialParams:+ def test_posts_incremental_modified_uses_modified_after(self):+ params = _build_initial_params(+ WORDPRESS_ENDPOINTS["posts"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, 12, 0, 0),+ incremental_field="modified",+ )+ # 2-hour lookback applied before formatting.+ assert params["modified_after"] == "2024-01-01T10:00:00"+ assert params["orderby"] == "modified"+ assert params["order"] == "asc"+ assert params["per_page"] == 100++ def test_posts_incremental_date_uses_after(self):+ params = _build_initial_params(+ WORDPRESS_ENDPOINTS["posts"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, 12, 0, 0),+ incremental_field="date",+ )+ assert params["after"] == "2024-01-01T10:00:00"+ assert "modified_after" not in params+ assert params["orderby"] == "date"++ def test_posts_full_refresh_uses_stable_order_by(self):+ params = _build_initial_params(+ WORDPRESS_ENDPOINTS["posts"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2024, 1, 1),+ incremental_field=None,+ )+ assert "after" not in params and "modified_after" not in params+ assert params["orderby"] == "date"+ assert params["order"] == "asc"++ def test_incremental_without_watermark_has_no_filter(self):+ params = _build_initial_params(+ WORDPRESS_ENDPOINTS["posts"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="modified",+ )+ assert "modified_after" not in params+ assert params["orderby"] == "date" # stable order on the first sync++ def test_comments_incremental_uses_after_only(self):+ params = _build_initial_params(+ WORDPRESS_ENDPOINTS["comments"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, 12, 0, 0),+ incremental_field="date",+ )+ assert params["after"] == "2024-01-01T10:00:00"+ assert params["orderby"] == "date"++ def test_comments_reject_modified_incremental_field(self):+ # Comments silently ignore modified_after, so it isn't an advertised cursor and must raise.+ with pytest.raises(ValueError):+ _build_initial_params(+ WORDPRESS_ENDPOINTS["comments"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1),+ incremental_field="modified",+ )++ @pytest.mark.parametrize("endpoint", ["categories", "tags", "users"])+ def test_full_refresh_endpoints_only_order_by_id(self, endpoint):+ params = _build_initial_params(+ WORDPRESS_ENDPOINTS[endpoint],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1),+ incremental_field=None,+ )+ assert "after" not in params and "modified_after" not in params+ assert params["orderby"] == "id"+++class TestBuildInitialUrl:+ def test_builds_url_with_params(self):+ url = _build_initial_url("https://example.com", WORDPRESS_ENDPOINTS["posts"], {"per_page": 100})+ assert url == "https://example.com/wp-json/wp/v2/posts?per_page=100"++ def test_accepts_bare_hostname(self):+ url = _build_initial_url("example.com", WORDPRESS_ENDPOINTS["users"], {})+ assert url == "https://example.com/wp-json/wp/v2/users"+++class TestParseNextUrl:+ @pytest.mark.parametrize(+ "header, expected",+ [+ ("", None),+ ('<https://example.com/wp-json/wp/v2/posts?page=1>; rel="prev"', None),+ (+ '<https://example.com/wp-json/wp/v2/posts?page=2>; rel="next"',+ "https://example.com/wp-json/wp/v2/posts?page=2",+ ),+ ],+ )+ def test_parse(self, header, expected):+ assert _parse_next_url(header) == expected+++class TestIsSameHost:+ @pytest.mark.parametrize(+ "url, site_url, expected",+ [+ ("https://example.com/wp-json/wp/v2/posts?page=2", "https://example.com", True),+ # Scheme downgrade to http when configured https must be rejected (credential exposure).+ ("http://example.com/wp-json/wp/v2/posts?page=2", "https://example.com", False),+ # Foreign / internal host must be rejected (SSRF).+ ("https://169.254.169.254/latest/meta-data/", "https://example.com", False),+ # Anonymous http site: an http next URL on the same host is allowed.+ ("http://example.com/wp-json/wp/v2/posts?page=2", "http://example.com", True),+ ],+ )+ def test_is_same_host(self, url, site_url, expected):+ assert _is_same_host(url, site_url) is expected+++class TestValidateCredentials:+ def _patch_session(self, response=None, raises=None):+ session = mock.MagicMock()+ if raises is not None:+ session.get.side_effect = raises+ else:+ session.get.return_value = response+ return mock.patch.object(wordpress_module, "make_tracked_session", return_value=session)++ @pytest.mark.parametrize(+ "status_code, expected_valid, expected_msg_substr",+ [+ (200, True, None),+ (401, False, "Invalid WordPress username or application password"),+ (403, False, "lack permission"),+ (404, False, "REST API not found"),+ ],+ )+ def test_status_code_mapping(self, status_code, expected_valid, expected_msg_substr):+ with self._patch_session(_response(status_code=status_code)):+ valid, msg = validate_credentials("https://example.com", None, None)+ assert valid is expected_valid+ if expected_msg_substr is None:+ assert msg is None+ else:+ assert expected_msg_substr in (msg or "")++ def test_invalid_site_url(self):+ valid, msg = validate_credentials("", None, None)+ assert valid is False+ assert msg == "Invalid WordPress site URL"++ def test_request_exception_returns_failure(self):+ import requests++ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):+ valid, msg = validate_credentials("https://example.com", None, None)+ assert valid is False+ assert "boom" in (msg or "")++ def test_rejects_redirect_response(self):+ with self._patch_session(_response(status_code=302)) as patched:+ valid, msg = validate_credentials("https://example.com", None, None)+ assert valid is False+ assert msg == HOST_NOT_ALLOWED_ERROR+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False++ def test_rejects_plaintext_http_when_credentials_present(self):+ # Basic-auth credentials must never be sent over plaintext HTTP.+ with self._patch_session(_response(status_code=200)) as patched:+ valid, msg = validate_credentials("http://example.com", "admin", "app pass word")+ assert valid is False+ assert msg == HTTP_NOT_ALLOWED_ERROR+ patched.return_value.get.assert_not_called()++ def test_allows_plaintext_http_when_anonymous(self):+ # No credentials -> nothing to leak, so anonymous http is permitted.+ with self._patch_session(_response(status_code=200)):+ valid, msg = validate_credentials("http://example.com", None, None)+ assert valid is True+ assert msg is None++ def test_blocks_unsafe_host(self):+ with (+ mock.patch.object(wordpress_module, "_is_host_safe", return_value=(False, "internal address")),+ self._patch_session(_response(status_code=200)) as patched,+ ):+ valid, msg = validate_credentials("https://10.0.0.1", None, None, team_id=99)+ assert valid is False+ assert msg == "internal address"+ patched.return_value.get.assert_not_called()+++class TestWordpressSourceResponse:+ @pytest.mark.parametrize(+ "endpoint, partition_key",+ [+ ("posts", "date"),+ ("pages", "date"),+ ("comments", "date"),+ ("media", "date"),+ ("categories", None),+ ("tags", None),+ ("users", None),+ ],+ )+ def test_response_shape(self, endpoint, partition_key):+ response = wordpress_source(+ site_url="https://example.com",+ username=None,+ application_password=None,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ team_id=1,+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ if partition_key:+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestGetRows:+ def _run(self, manager, responses, endpoint="posts", site_url="https://example.com", **kwargs):+ session = mock.MagicMock()+ session.get.side_effect = responses+ with (+ mock.patch.object(wordpress_module, "make_tracked_session", return_value=session),+ mock.patch.object(wordpress_module, "Batcher", _FakeBatcher),+ ):+ rows: list[Any] = []+ for table in get_rows(+ site_url=site_url,+ username=None,+ application_password=None,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ **kwargs,+ ):+ rows.extend(table)+ return rows, session++ def test_follows_link_header_across_pages(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ page1 = _response(+ json_data=[{"id": 1}, {"id": 2}],+ link='<https://example.com/wp-json/wp/v2/posts?page=2>; rel="next"',+ )+ page2 = _response(json_data=[{"id": 3}])+ rows, session = self._run(manager, [page1, page2])++ assert [r["id"] for r in rows] == [1, 2, 3]+ second_url = session.get.call_args_list[1].args[0]+ assert second_url == "https://example.com/wp-json/wp/v2/posts?page=2"++ def test_saves_state_after_yielding(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ self._run(manager, [_response(json_data=[{"id": 1}])])++ assert manager.save_state.called+ saved = manager.save_state.call_args.args[0]+ assert isinstance(saved, WordpressResumeConfig)++ def test_resumes_from_saved_state(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = WordpressResumeConfig(+ next_url="https://example.com/wp-json/wp/v2/posts?page=5"+ )+ rows, session = self._run(manager, [_response(json_data=[{"id": 9}])])++ first_url = session.get.call_args_list[0].args[0]+ assert first_url == "https://example.com/wp-json/wp/v2/posts?page=5"+ assert [r["id"] for r in rows] == [9]++ def test_empty_page_terminates(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ empty = _response(+ json_data=[],+ link='<https://example.com/wp-json/wp/v2/posts?page=2>; rel="next"',+ )+ rows, session = self._run(manager, [empty])++ assert rows == []+ assert session.get.call_count == 1++ def test_does_not_follow_next_url_on_foreign_host(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ page1 = _response(+ json_data=[{"id": 1}],+ link='<http://169.254.169.254/latest/meta-data/>; rel="next"',+ )+ rows, session = self._run(manager, [page1])++ assert [r["id"] for r in rows] == [1]+ assert session.get.call_count == 1++ def test_ignores_resume_url_on_foreign_host(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = WordpressResumeConfig(next_url="http://169.254.169.254/latest/meta-data/")+ rows, session = self._run(manager, [_response(json_data=[{"id": 1}])])++ first_url = session.get.call_args_list[0].args[0]+ assert first_url.startswith("https://example.com/wp-json/wp/v2/posts")+ assert [r["id"] for r in rows] == [1]++ def test_does_not_follow_scheme_downgrade_next_url(self):+ # A Link header that downgrades https->http on the configured host must not be followed.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ page1 = _response(+ json_data=[{"id": 1}],+ link='<http://example.com/wp-json/wp/v2/posts?page=2>; rel="next"',+ )+ rows, session = self._run(manager, [page1])++ assert [r["id"] for r in rows] == [1]+ assert session.get.call_count == 1++ def test_raises_on_redirect(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ with pytest.raises(WordpressHostNotAllowedError) as exc:+ self._run(manager, [_response(status_code=302)])+ assert HOST_NOT_ALLOWED_ERROR in str(exc.value)++ def test_unsafe_host_error_is_marked_non_retryable(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ with (+ mock.patch.object(wordpress_module, "_is_host_safe", return_value=(False, "internal address")),+ pytest.raises(WordpressHostNotAllowedError) as exc,+ ):+ self._run(manager, [_response(json_data=[{"id": 1}])])+ assert HOST_NOT_ALLOWED_ERROR in str(exc.value)++ def test_rejects_plaintext_http_with_credentials_before_request(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ session = mock.MagicMock()+ with (+ mock.patch.object(wordpress_module, "make_tracked_session", return_value=session),+ mock.patch.object(wordpress_module, "Batcher", _FakeBatcher),+ pytest.raises(WordpressHostNotAllowedError) as exc,+ ):+ list(+ get_rows(+ site_url="http://example.com",+ username="admin",+ application_password="app pass word",+ endpoint="posts",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )+ assert HTTP_NOT_ALLOWED_ERROR in str(exc.value)+ session.get.assert_not_called()++ def test_passes_allow_redirects_false(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ _rows, session = self._run(manager, [_response(json_data=[{"id": 1}])])+ assert session.get.call_args.kwargs["allow_redirects"] is False+++class TestRetryAfter:+ @pytest.mark.parametrize(+ "header, expected",+ [+ ({"Retry-After": "5"}, 5.0),+ ({"Retry-After": " 9 "}, 9.0),+ ({"Retry-After": "100000"}, 60.0), # capped+ ({"Retry-After": "Wed, 21 Oct 2025 07:28:00 GMT"}, None), # HTTP-date ignored+ ({}, None),+ ],+ )+ def test_parse_retry_after(self, header, expected):+ from posthog.temporal.data_imports.sources.wordpress.wordpress import _parse_retry_after++ response = mock.MagicMock()+ response.headers = header+ assert _parse_retry_after(response) == expected++ def test_retry_wait_prefers_retry_after(self):+ from posthog.temporal.data_imports.sources.wordpress.wordpress import WordpressRetryableError, _retry_wait++ state = mock.MagicMock()+ state.outcome.exception.return_value = WordpressRetryableError("rate limited", retry_after=7.0)+ assert _retry_wait(state) == 7.0diff --git a/posthog/temporal/data_imports/sources/wordpress/tests/test_wordpress_source.py b/posthog/temporal/data_imports/sources/wordpress/tests/test_wordpress_source.pynew file mode 100644index 000000000000..51a454ebf5a4--- /dev/null+++ b/posthog/temporal/data_imports/sources/wordpress/tests/test_wordpress_source.py@@ -0,0 +1,165 @@+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.wordpress.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.wordpress.source import WordpressSource+from posthog.temporal.data_imports.sources.wordpress.wordpress import WordpressResumeConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestWordpressSource:+ def setup_method(self):+ self.source = WordpressSource()+ self.team_id = 123+ self.config = mock.MagicMock()+ self.config.site_url = "https://example.com"+ self.config.username = "admin"+ self.config.application_password = "app pass word"++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.WORDPRESS++ def test_connection_host_fields(self):+ assert self.source.connection_host_fields == ["site_url"]++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Wordpress"+ assert config.label == "WordPress"+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA++ field_names = [f.name for f in config.fields]+ assert field_names == ["site_url", "username", "application_password"]++ site_field, user_field, pass_field = config.fields+ assert isinstance(site_field, SourceFieldInputConfig)+ assert site_field.type == SourceFieldInputConfigType.TEXT+ assert site_field.required is True+ assert site_field.secret is False++ assert isinstance(user_field, SourceFieldInputConfig)+ assert user_field.required is False+ assert user_field.secret is False++ assert isinstance(pass_field, SourceFieldInputConfig)+ assert pass_field.type == SourceFieldInputConfigType.PASSWORD+ assert pass_field.required is False+ assert pass_field.secret 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_returns_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, incremental",+ [+ ("posts", True),+ ("pages", True),+ ("comments", True),+ ("media", True),+ ("categories", False),+ ("tags", False),+ ("users", False),+ ],+ )+ def test_schema_incremental_support(self, endpoint, incremental):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[endpoint].supports_incremental is incremental+ assert schemas[endpoint].supports_append is incremental++ @pytest.mark.parametrize(+ "endpoint, fields",+ [+ ("posts", {"modified", "date"}),+ ("comments", {"date"}),+ ("categories", set()),+ ],+ )+ def test_advertised_incremental_fields(self, endpoint, fields):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert {f["field"] for f in schemas[endpoint].incremental_fields} == fields++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["posts"])+ assert len(schemas) == 1+ assert schemas[0].name == "posts"++ def test_get_schemas_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected",+ [+ ((True, None), (True, None)),+ (+ (False, "Invalid WordPress username or application password"),+ (False, "Invalid WordPress username or application password"),+ ),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.wordpress.source.validate_wordpress_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected):+ mock_validate.return_value = mock_return++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="posts")++ assert result == expected+ mock_validate.assert_called_once_with(+ self.config.site_url, self.config.username, self.config.application_password, self.team_id+ )++ def test_get_resumable_source_manager(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is WordpressResumeConfig++ def test_canonical_descriptions_cover_every_endpoint(self):+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ @mock.patch("posthog.temporal.data_imports.sources.wordpress.source.wordpress_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_wordpress_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "posts"+ inputs.team_id = 42+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00"+ inputs.incremental_field = "modified"++ manager = mock.MagicMock()+ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_wordpress_source.assert_called_once()+ kwargs = mock_wordpress_source.call_args.kwargs+ assert kwargs["site_url"] == "https://example.com"+ assert kwargs["username"] == "admin"+ assert kwargs["application_password"] == "app pass word"+ assert kwargs["endpoint"] == "posts"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 42+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00"+ assert kwargs["incremental_field"] == "modified"++ @mock.patch("posthog.temporal.data_imports.sources.wordpress.source.wordpress_source")+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_wordpress_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "categories"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "ignored"+ inputs.incremental_field = None++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_wordpress_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/posthog/temporal/data_imports/sources/wordpress/wordpress.py b/posthog/temporal/data_imports/sources/wordpress/wordpress.pynew file mode 100644index 000000000000..1fd4a07190a3--- /dev/null+++ b/posthog/temporal/data_imports/sources/wordpress/wordpress.py@@ -0,0 +1,432 @@+import re+import base64+import dataclasses+from collections.abc import Iterator+from datetime import date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.mixins import _is_host_safe+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.wordpress.settings import WORDPRESS_ENDPOINTS, WordpressEndpointConfig++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+MAX_RETRY_AFTER_SECONDS = 60++API_PREFIX = "/wp-json/wp/v2"++HOST_NOT_ALLOWED_ERROR = "WordPress site URL is not allowed"+HTTP_NOT_ALLOWED_ERROR = "WordPress site URL must use HTTPS when credentials are provided"++# WordPress `after`/`modified_after` filter on the site-LOCAL post_date/post_modified columns, which+# can be non-monotonic across a DST transition. We re-request a small overlap on each incremental run+# and let primary-key merge dedupe the re-fetched rows. Two hours covers the largest DST shift (1h)+# with margin.+INCREMENTAL_LOOKBACK = timedelta(hours=2)+++class WordpressRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++class WordpressHostNotAllowedError(Exception):+ pass+++class WordpressResumeConfig:+ next_url: str+++def normalize_host(site_url: str | None) -> str:+ """Turn whatever the user typed into a bare WordPress site base URL.++ Accepts ``example.com``, ``https://example.com/``,+ ``https://example.com/wp-json/wp/v2``, or a subdirectory install such as+ ``https://example.com/blog`` and returns the bare base URL. Defaults to+ https when no scheme is given.++ Returns ``""`` for input carrying a query string, fragment, params, or+ embedded credentials: those have no place in a site base URL, and since the+ result is later concatenated with the REST path and sent by the worker,+ preserving them would let a caller smuggle an arbitrary request target past+ the host-only SSRF guard.+ """+ raw = (site_url or "").strip()+ if not raw:+ return ""+ if not re.match(r"^https?://", raw, flags=re.IGNORECASE):+ raw = f"https://{raw}"++ parsed = urlparse(raw)+ # Only scheme/host[:port]/path belong in a site base URL — anything else could redirect the+ # worker's requests elsewhere on the allowed host (SSRF), so reject rather than silently strip.+ if parsed.query or parsed.fragment or parsed.params or parsed.username or parsed.password:+ return ""+ if not parsed.hostname:+ return ""++ path = parsed.path.rstrip("/")+ # Tolerate a pasted REST root. The regex strips a non-slash suffix, so no trailing slash remains.+ path = re.sub(r"/wp-json(/wp/v2)?$", "", path, flags=re.IGNORECASE)++ return f"{parsed.scheme.lower()}://{parsed.netloc.lower()}{path}"+++def _base_url(site_url: str | None) -> str:+ return f"{normalize_host(site_url)}{API_PREFIX}"+++def _host_only(site_url: str | None) -> str:+ return (urlparse(normalize_host(site_url)).hostname or "").lower()+++def _scheme(site_url: str | None) -> str:+ return urlparse(normalize_host(site_url)).scheme+++def _has_credentials(username: str | None, application_password: str | None) -> bool:+ return bool((username or "").strip()) and bool((application_password or "").strip())+++def _get_headers(username: str | None, application_password: str | None) -> dict[str, str]:+ """Application Passwords authenticate via HTTP Basic. Public read endpoints work unauthenticated,+ so the Authorization header is only added when both credentials are present."""+ headers = {"Accept": "application/json"}+ if _has_credentials(username, application_password):+ # Application passwords are shown with spaces for readability; WordPress accepts them verbatim.+ token = base64.b64encode(f"{username}:{application_password}".encode()).decode()+ headers["Authorization"] = f"Basic {token}"+ return headers+++def _format_incremental_value(value: Any) -> str:+ """WordPress timestamp filters compare against the site-local datetime, formatted as naive ISO 8601.++ We emit the value's wall-clock components without converting timezones — the stored watermark is+ read back from the same local `date`/`modified` column, so preserving the wall clock keeps the+ filter consistent with the data (see INCREMENTAL_LOOKBACK for the DST guard)."""+ if isinstance(value, datetime):+ return value.strftime("%Y-%m-%dT%H:%M:%S")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00")+ return str(value)+++def _apply_lookback(value: Any) -> Any:+ if isinstance(value, datetime):+ return value - INCREMENTAL_LOOKBACK+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time()) - INCREMENTAL_LOOKBACK+ return value+++def _active_incremental_field(+ config: WordpressEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> str | None:+ """The field we actually filter/sort on this run, or None for a full / first sync."""+ if not (should_use_incremental_field and db_incremental_field_last_value and config.incremental_filter_params):+ return None+ field = incremental_field or config.default_incremental_field+ if field not in config.incremental_filter_params:+ raise ValueError(+ f"Unsupported WordPress incremental field '{field}' for endpoint '{config.name}'. "+ f"Expected one of: {sorted(config.incremental_filter_params)}."+ )+ return field+++def _build_initial_params(+ config: WordpressEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ params: dict[str, Any] = {"per_page": config.page_size}++ active_field = _active_incremental_field(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )+ if active_field is not None:+ filter_param = config.incremental_filter_params[active_field]+ params[filter_param] = _format_incremental_value(_apply_lookback(db_incremental_field_last_value))++ params["orderby"] = active_field or config.stable_order_by+ params["order"] = "asc"+ return params+++def _build_initial_url(site_url: str | None, config: WordpressEndpointConfig, params: dict[str, Any]) -> str:+ url = f"{_base_url(site_url)}{config.path}"+ if not params:+ return url+ return f"{url}?{urlencode(params)}"+++def _parse_next_url(link_header: str) -> str | None:+ """Return the URL with ``rel="next"`` from WordPress's ``Link`` header, if any."""+ if not link_header:+ return None+ for part in link_header.split(","):+ part = part.strip()+ match = re.match(r'<([^>]+)>;\s*rel="next"', part)+ if match:+ return match.group(1)+ return None+++def _is_same_host(url: str, site_url: str | None) -> bool:+ """Whether ``url`` points at the configured WordPress host with the configured scheme.++ Pagination/resume URLs are server-controlled (Link header / Redis), so we pin them to the+ validated host and scheme to avoid being redirected at an arbitrary internal address (SSRF) or+ downgraded from https to http (which would expose Basic-auth credentials)."""+ try:+ parsed = urlparse(url)+ configured = urlparse(normalize_host(site_url))+ return (+ parsed.scheme == configured.scheme+ and (parsed.hostname or "").lower() == (configured.hostname or "").lower()+ and (parsed.port or _default_port(parsed.scheme)) == (configured.port or _default_port(configured.scheme))+ )+ except Exception:+ return False+++def _default_port(scheme: str) -> int:+ return 443 if scheme == "https" else 80+++def validate_credentials(+ site_url: str | None,+ username: str | None,+ application_password: str | None,+ team_id: Optional[int] = None,+) -> tuple[bool, str | None]:+ """Probe the site's REST root to confirm it's reachable and any credentials are genuine."""+ host_only = _host_only(site_url)+ if not host_only:+ return False, "Invalid WordPress site URL"++ has_credentials = _has_credentials(username, application_password)++ # Basic-auth credentials ride in the Authorization header, so refuse plaintext HTTP before sending+ # them. Anonymous public access over http is allowed (nothing to leak).+ if has_credentials and _scheme(site_url) != "https":+ return False, HTTP_NOT_ALLOWED_ERROR++ # The host is customer-controlled, so block hosts that resolve to private/internal addresses+ # (SSRF). Only enforced on cloud — see _is_host_safe.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(host_only, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ # A cheap, always-present collection that exercises auth when credentials are set.+ url = f"{_base_url(site_url)}/posts?per_page=1"+ try:+ response = make_tracked_session().get(+ url,+ headers=_get_headers(username, application_password),+ timeout=10,+ allow_redirects=False,+ )+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.is_redirect or response.is_permanent_redirect:+ return False, HOST_NOT_ALLOWED_ERROR++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Invalid WordPress username or application password"++ if response.status_code == 403:+ return False, "These credentials lack permission to read this WordPress site"++ if response.status_code == 404:+ return False, "WordPress REST API not found at this URL — confirm the site URL and that the REST API is enabled"++ try:+ body = response.json()+ return False, body.get("message", response.text)+ except Exception:+ return False, response.text+++def _parse_retry_after(response: requests.Response) -> float | None:+ """Respect a whole-second ``Retry-After`` on 429; ignore HTTP-date forms."""+ raw = response.headers.get("Retry-After")+ if raw and raw.strip().isdigit():+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)+ return None+++def _retry_wait(retry_state: RetryCallState) -> float:+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, WordpressRetryableError) and exc.retry_after is not None:+ return exc.retry_after+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++def get_rows(+ site_url: str | None,+ username: str | None,+ application_password: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[WordpressResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = WORDPRESS_ENDPOINTS[endpoint]+ headers = _get_headers(username, application_password)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)++ # Re-check HTTPS at run time (host could have been edited after source creation) before any+ # credential-bearing request goes out. Non-retryable — see get_non_retryable_errors().+ if _has_credentials(username, application_password) and _scheme(site_url) != "https":+ raise WordpressHostNotAllowedError(HTTP_NOT_ALLOWED_ERROR)++ # Re-check at run time (not just at source-create) in case the host now resolves to an internal+ # address (SSRF / DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(_host_only(site_url), team_id)+ if not host_ok:+ raise WordpressHostNotAllowedError(+ f"{HOST_NOT_ALLOWED_ERROR}: {host_err}" if host_err else HOST_NOT_ALLOWED_ERROR+ )++ params = _build_initial_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )+ initial_url = _build_initial_url(site_url, config, params)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and _is_same_host(resume_config.next_url, site_url):+ url: str = resume_config.next_url+ logger.debug(f"WordPress: resuming from URL: {url}")+ else:+ if resume_config is not None:+ logger.warning("WordPress: ignoring resume URL whose host does not match the configured host")+ url = initial_url++ @retry(+ retry=retry_if_exception_type((WordpressRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+ )+ def fetch_page(page_url: str) -> requests.Response:+ # 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+ )++ if response.status_code == 429 or response.status_code >= 500:+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None+ raise WordpressRetryableError(+ f"WordPress API error (retryable): status={response.status_code}, url={page_url}",+ retry_after=retry_after,+ )++ if response.is_redirect or response.is_permanent_redirect:+ raise WordpressHostNotAllowedError(+ f"{HOST_NOT_ALLOWED_ERROR}: WordPress API returned an unexpected redirect "+ f"(status={response.status_code}); refusing to follow it"+ )++ if not response.ok:+ logger.error(f"WordPress API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response++ while True:+ response = fetch_page(url)++ data = response.json()+ if not isinstance(data, list) or not data:+ break++ next_url = _parse_next_url(response.headers.get("Link", ""))++ # Page and chunk boundaries don't line up, so checkpoint the CURRENT page URL. On resume we+ # re-fetch it and rely on primary-key merge semantics to dedupe already-yielded rows.+ checkpoint_url = url++ for item in data:+ batcher.batch(item)++ if batcher.should_yield():+ py_table = batcher.get_table()+ yield py_table+ resumable_source_manager.save_state(WordpressResumeConfig(next_url=checkpoint_url))++ if not next_url:+ break++ # The next-page URL is server-controlled; only follow it if it stays on the configured host.+ if not _is_same_host(next_url, site_url):+ logger.warning("WordPress: stopping pagination, next URL host does not match the configured host")+ break++ url = next_url++ if batcher.should_yield(include_incomplete_chunk=True):+ py_table = batcher.get_table()+ yield py_table+++def wordpress_source(+ site_url: str | None,+ username: str | None,+ application_password: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[WordpressResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = WORDPRESS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ site_url=site_url,+ username=username,+ application_password=application_password,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ team_id=team_id,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=[endpoint_config.primary_key],+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )