Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(warehouse): authenticate WooCommerce via query string, not Basic header (#72750)

posthog[bot]e262b07bc375
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/source.py
index 0395f96317e7..13c7d6c5f07c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/source.py
@@ -59,9 +59,20 @@ class WooCommerceSource(ResumableSource[WooCommerceSourceConfig, WooCommerceResu
return CANONICAL_DESCRIPTIONS
def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # WooCommerce's own auth and permission failures return 401 (e.g. a bad key or a key
+ # without Read scope). A 403 on the REST API almost always comes from an upstream layer
+ # — a WAF, CDN, or security plugin — blocking the request before it reaches WooCommerce,
+ # so point users at that rather than blaming their key.
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.",
+ "401 Client Error": (
+ "WooCommerce rejected the request. Check your consumer key and secret are correct "
+ "and have Read permission for this store."
+ ),
+ "403 Client Error": (
+ "The request to your WooCommerce store was blocked before it reached WooCommerce, "
+ "usually by a firewall, CDN, or security plugin. Allow requests to the store's REST "
+ "API (/wp-json/wc/v3) and try again."
+ ),
}
def get_schemas(
@@ -92,16 +103,24 @@ class WooCommerceSource(ResumableSource[WooCommerceSourceConfig, WooCommerceResu
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`.
+ # A 403 on the probe endpoint is almost always an upstream block (WAF/CDN/security
+ # plugin), not the key itself, and can be endpoint-specific. Don't fail source creation
+ # on it — let the source be created and surface any real block per-schema at sync time
+ # via `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."
+ return False, (
+ "The request to your WooCommerce store was blocked before it reached WooCommerce, "
+ "usually by a firewall, CDN, or security plugin. Allow requests to the store's REST API."
+ )
if status == 401:
- return False, "WooCommerce authentication failed. Please check your consumer key and secret."
+ return False, (
+ "WooCommerce rejected the request. Check your consumer key and secret are correct "
+ "and have Read permission for this store."
+ )
return False, "Could not connect to your WooCommerce store. Please check the store URL."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce.py
index aeab84e1b304..8d1f74825281 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce.py
@@ -16,9 +16,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.woocommerc
)
from products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.woocommerce import (
DEFAULT_PER_PAGE,
+ WOOCOMMERCE_USER_AGENT,
+ WooCommerceAuth,
WooCommercePaginator,
WooCommerceResumeConfig,
_HostGuardedAdapter,
+ _make_guarded_session,
_to_woocommerce_datetime,
get_resource,
normalize_store_url,
@@ -279,6 +282,35 @@ class TestWooCommerceSourceResumeBehavior:
assert first["per_page"] == DEFAULT_PER_PAGE
+class TestGuardedSessionUserAgent:
+ def test_sets_non_default_user_agent(self) -> None:
+ # Managed WordPress hosts/WAFs block the default `python-requests` agent with a 403,
+ # so every request must go out under our identifiable agent instead.
+ session = _make_guarded_session(team_id=123)
+ assert session.headers["User-Agent"] == WOOCOMMERCE_USER_AGENT
+ assert "python-requests" not in session.headers["User-Agent"]
+
+
+class TestWooCommerceAuth:
+ def test_sends_query_string_credentials_and_no_authorization_header(self) -> None:
+ # Auth must go in the query string with no Authorization header. A Basic header trips
+ # hosts running a JWT/security plugin, which reject it with a 403 before WooCommerce
+ # sees the key; reintroducing the header would break those stores again.
+ prepared = Request(method="GET", url="https://example.com/wp-json/wc/v3/products", params={"page": 1}).prepare()
+
+ WooCommerceAuth("ck_test", "cs_test")(prepared)
+
+ assert "Authorization" not in prepared.headers
+ assert prepared.url is not None
+ assert "consumer_key=ck_test" in prepared.url
+ assert "consumer_secret=cs_test" in prepared.url
+ # Existing query params are preserved, not clobbered.
+ assert "page=1" in prepared.url
+
+ def test_secret_values_redacts_both_credentials(self) -> None:
+ assert set(WooCommerceAuth("ck_test", "cs_test").secret_values()) == {"ck_test", "cs_test"}
+
+
class TestValidateCredentials:
@pytest.mark.parametrize("status_code", [200, 401, 403, 404])
def test_returns_status_code(self, status_code: int) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/woocommerce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/woocommerce.py
index c9737dd4f02a..5188f46338dc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/woocommerce.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/woocommerce.py
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBase
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -27,6 +28,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.woocommerc
WOOCOMMERCE_API_BASE_PATH = "/wp-json/wc/v3"
# WooCommerce caps `per_page` at 100.
DEFAULT_PER_PAGE = 100
+# Managed WordPress hosts and security layers (Cloudflare, Wordfence, and similar WAFs)
+# frequently block the default `python-requests` User-Agent outright, returning a 403
+# before the request ever reaches WooCommerce. Identify ourselves with a stable,
+# non-default agent so those layers let legitimate sync traffic through.
+WOOCOMMERCE_USER_AGENT = "PostHog Data Warehouse (WooCommerce source; +https://posthog.com)"
@dataclasses.dataclass
@@ -103,9 +109,40 @@ def _make_guarded_session(team_id: int, redact_values: tuple[str, ...] = ()) ->
adapter = _HostGuardedAdapter(team_id, max_retries=DEFAULT_RETRY, redact_values=redact_values)
session.mount("https://", adapter)
session.mount("http://", adapter)
+ session.headers["User-Agent"] = WOOCOMMERCE_USER_AGENT
return session
+class WooCommerceAuth(AuthConfigBase):
+ """WooCommerce consumer key/secret auth via query-string parameters.
+
+ WooCommerce documents two ways to authenticate over HTTPS: an HTTP Basic
+ `Authorization` header, or the consumer key/secret as query-string parameters. We
+ use the query string and send no `Authorization` header at all, because the header
+ is the more fragile path in practice. Some hosts strip the `Authorization` header
+ before it reaches PHP, and some run a JWT/security plugin that greedily claims the
+ header, expects a `Bearer` token, and rejects our `Basic` scheme with a 403
+ (`jwt_auth_bad_auth_header`) before WooCommerce ever evaluates the key. The
+ query string sidesteps both. The store URL is always normalized to HTTPS, so the
+ credentials never travel over plaintext.
+ """
+
+ def __init__(self, consumer_key: str, consumer_secret: str) -> None:
+ self.consumer_key = consumer_key
+ self.consumer_secret = consumer_secret
+
+ def __call__(self, request: PreparedRequest) -> PreparedRequest:
+ request.prepare_url(
+ request.url,
+ {"consumer_key": self.consumer_key, "consumer_secret": self.consumer_secret},
+ )
+ return request
+
+ def secret_values(self) -> tuple[str, ...]:
+ # Both land in the request URL, so redact both from logs and raised exception messages.
+ return tuple(value for value in (self.consumer_secret, self.consumer_key) if value)
+
+
def _to_woocommerce_datetime(value: Any) -> Optional[str]:
"""Format an incremental cursor value as the ISO8601 string WooCommerce expects.
@@ -226,11 +263,7 @@ def woocommerce_source(
config: RESTAPIConfig = {
"client": {
"base_url": _base_url(store_url),
- "auth": {
- "type": "http_basic",
- "username": consumer_key,
- "password": consumer_secret,
- },
+ "auth": WooCommerceAuth(consumer_key, 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.
@@ -279,7 +312,9 @@ def validate_credentials(store_url: str, consumer_key: str, consumer_secret: str
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),
+ # Same query-string auth the sync uses, so the probe can't pass under one auth
+ # path and then fail at sync time under another.
+ auth=WooCommerceAuth(consumer_key, consumer_secret),
timeout=30,
)
except Exception: