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-sources): make the Etsy source able to authenticate (#97053)

posthog[bot]cdfb7881232f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/etsy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/etsy.py
index 45841aed201c..b6bd43c2bf75 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/etsy.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/etsy.py
@@ -67,19 +67,20 @@ class EtsyResumeConfig:
class EtsyClient:
"""Etsy Open API v3 transport: x-api-key on every call plus a bearer minted from a refresh token.
- Etsy's OAuth2 uses PKCE, so the refresh exchange takes the app's keystring as ``client_id`` and
- carries no client secret. Access tokens last an hour, which a backfill routinely outlives, so a
- 401 re-mints once and replays the request.
+ Since 9 February 2026 Etsy rejects any v3 request whose ``x-api-key`` is the keystring alone, so
+ the header pairs it with the app's shared secret as ``keystring:secret``. The OAuth2 refresh
+ exchange still uses PKCE and takes the keystring on its own as ``client_id``. Access tokens last
+ an hour, which a backfill routinely outlives, so a 401 re-mints once and replays the request.
"""
- def __init__(self, api_key: str, refresh_token: str, logger: FilteringBoundLogger) -> None:
+ def __init__(self, api_key: str, shared_secret: str, refresh_token: str, logger: FilteringBoundLogger) -> None:
self._api_key = api_key
self._refresh_token = refresh_token
self._logger = logger
self._access_token: Optional[str] = None
self._session = make_tracked_session(
- headers={"x-api-key": api_key, "Accept": "application/json"},
- redact_values=(api_key, refresh_token),
+ headers={"x-api-key": f"{api_key}:{shared_secret}", "Accept": "application/json"},
+ redact_values=(api_key, shared_secret, refresh_token),
# The keystring rides a custom header, which requests does not strip across a redirect.
allow_redirects=False,
)
@@ -87,7 +88,8 @@ class EtsyClient:
def _mint_token(self) -> str:
response = self._session.post(
ETSY_TOKEN_URL,
- json={
+ # An OAuth2 token endpoint takes form encoding; Etsy rejects a JSON body outright.
+ data={
"grant_type": "refresh_token",
"client_id": self._api_key,
"refresh_token": self._refresh_token,
@@ -139,7 +141,9 @@ class EtsyClient:
return str(shop_id)
-def validate_credentials(api_key: str, refresh_token: str, shop_id: Optional[str]) -> tuple[bool, Optional[str]]:
+def validate_credentials(
+ api_key: str, shared_secret: str, refresh_token: str, shop_id: Optional[str]
+) -> tuple[bool, Optional[str]]:
"""Cheap probe: mint a token and read the token's own identity.
Always hits `/users/me`, even with a shop ID configured — otherwise a bogus keystring or refresh
@@ -153,10 +157,10 @@ def validate_credentials(api_key: str, refresh_token: str, shop_id: Optional[str
try:
# No job logger exists on the create-time probe path, so use the module logger.
- client = EtsyClient(api_key, refresh_token, structlog.get_logger(__name__))
+ client = EtsyClient(api_key, shared_secret, refresh_token, structlog.get_logger(__name__))
identity = client.request("/users/me")
except Exception:
- return False, "Could not authenticate with Etsy. Check your API keystring and refresh token."
+ return False, "Could not authenticate with Etsy. Check your API keystring, shared secret and refresh token."
if not (shop_id and shop_id.strip()) and identity.get("shop_id") is None:
return False, NO_SHOP_ERROR
@@ -296,6 +300,7 @@ def _offset_pages(
def get_rows(
api_key: str,
+ shared_secret: str,
refresh_token: str,
shop_id: Optional[str],
endpoint: str,
@@ -306,7 +311,7 @@ def get_rows(
incremental_field: Optional[str] = None,
) -> Iterator[list[dict[str, Any]]]:
config = ETSY_ENDPOINTS[endpoint]
- client = EtsyClient(api_key, refresh_token, logger)
+ client = EtsyClient(api_key, shared_secret, refresh_token, logger)
path = f"/shops/{client.resolve_shop_id(shop_id)}{config.path}"
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
@@ -360,6 +365,7 @@ def _window_start(should_use_incremental_field: bool, db_incremental_field_last_
def etsy_source(
api_key: str,
+ shared_secret: str,
refresh_token: str,
shop_id: Optional[str],
endpoint: str,
@@ -375,6 +381,7 @@ def etsy_source(
name=endpoint,
items=lambda: get_rows(
api_key=api_key,
+ shared_secret=shared_secret,
refresh_token=refresh_token,
shop_id=shop_id,
endpoint=endpoint,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.py
index 5658e4f976e5..8b881c734ee6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.py
@@ -57,7 +57,7 @@ class EtsySource(ResumableSource[EtsySourceConfig, EtsyResumeConfig]):
keywords=["etsy", "receipts", "orders", "marketplace"],
caption="""Sync your Etsy shop's orders, listings, reviews and payment ledger into the PostHog Data warehouse.
-Register a personal app in the [Etsy developer portal](https://www.etsy.com/developers/your-apps) to get a keystring, then run Etsy's OAuth flow to grant your shop and keep the refresh token it returns. The token needs the `transactions_r`, `listings_r` and `shops_r` scopes — add `billing_r` if you want the payment ledger. Leave the shop ID blank and we'll use the shop the token belongs to.""",
+Register a personal app in the [Etsy developer portal](https://www.etsy.com/developers/your-apps) to get a keystring and its shared secret, then run Etsy's OAuth flow to grant your shop and keep the refresh token it returns. The token needs the `transactions_r`, `listings_r` and `shops_r` scopes — add `billing_r` if you want the payment ledger. Leave the shop ID blank and we'll use the shop the token belongs to.""",
iconPath="/static/services/etsy.png",
docsUrl="https://posthog.com/docs/cdp/sources/etsy",
fields=cast(
@@ -71,6 +71,14 @@ Register a personal app in the [Etsy developer portal](https://www.etsy.com/deve
placeholder="Your app's keystring",
secret=True,
),
+ SourceFieldInputConfig(
+ name="shared_secret",
+ label="Shared secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Your app's shared secret",
+ secret=True,
+ ),
SourceFieldInputConfig(
name="refresh_token",
label="Refresh token",
@@ -103,7 +111,7 @@ Register a personal app in the [Etsy developer portal](https://www.etsy.com/deve
# Etsy answers a revoked or expired refresh token with a 400 from the token endpoint.
# Refresh tokens last 90 days, so this is the expected end-of-life failure.
"400 Client Error: Bad Request for url: https://api.etsy.com/v3/public/oauth/token": "Your Etsy refresh token is expired or revoked. Etsy refresh tokens last 90 days — reauthorize the app and paste the new token.",
- "401 Client Error: Unauthorized for url: https://api.etsy.com": "Etsy rejected your credentials. Check the API keystring and refresh token, then reconnect.",
+ "401 Client Error: Unauthorized for url: https://api.etsy.com": "Etsy rejected your credentials. Check the API keystring, shared secret and refresh token, then reconnect.",
"403 Client Error: Forbidden for url: https://api.etsy.com": "Your Etsy token is missing a scope this table needs (transactions_r, listings_r, shops_r or billing_r). Reauthorize with the scopes you want to sync.",
"This Etsy account has no shop": "The connected Etsy account does not own a shop. Enter the shop ID you want to sync, or reconnect with the seller account.",
}
@@ -126,7 +134,7 @@ Register a personal app in the [Etsy developer portal](https://www.etsy.com/deve
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- return validate_etsy_credentials(config.api_key, config.refresh_token, config.shop_id)
+ return validate_etsy_credentials(config.api_key, config.shared_secret, config.refresh_token, config.shop_id)
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[EtsyResumeConfig]:
return ResumableSourceManager[EtsyResumeConfig](inputs, EtsyResumeConfig)
@@ -139,6 +147,7 @@ Register a personal app in the [Etsy developer portal](https://www.etsy.com/deve
) -> SourceResponse:
return etsy_source(
api_key=config.api_key,
+ shared_secret=config.shared_secret,
refresh_token=config.refresh_token,
shop_id=config.shop_id,
endpoint=inputs.schema_name,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py
index 477563eea752..fc315e86508c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py
@@ -31,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.setti
_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.etsy.etsy.make_tracked_session"
_API_KEY = "etsy-keystring-abcdef123456"
+_SHARED_SECRET = "etsy-shared-secret-abcdef123456"
_REFRESH_TOKEN = "etsy-refresh-token-abcdef123456"
_LOGGER = structlog.get_logger(__name__)
@@ -62,6 +63,7 @@ class _FakeSession:
def __init__(self, get_responses: list[Response], post_responses: Optional[list[Response]] = None) -> None:
self.get_calls: list[tuple[str, dict[str, Any], dict[str, str]]] = []
self.post_bodies: list[dict[str, Any]] = []
+ self.post_json_bodies: list[dict[str, Any]] = []
self._get_responses = list(get_responses)
self._post_responses = list(post_responses) if post_responses is not None else [_token()]
@@ -77,8 +79,17 @@ class _FakeSession:
raise AssertionError(f"unexpected extra GET: {url} {params}")
return self._get_responses.pop(0)
- def post(self, url: str, json: Optional[dict[str, Any]] = None, timeout: Optional[float] = None) -> Response: # noqa: A002 — matches requests' keyword name
- self.post_bodies.append(dict(json or {}))
+ def post(
+ self,
+ url: str,
+ data: Optional[dict[str, Any]] = None,
+ json: Optional[dict[str, Any]] = None, # noqa: A002 — matches requests' keyword name
+ timeout: Optional[float] = None,
+ ) -> Response:
+ # `data` and `json` are separate keywords so a test can tell form encoding from a JSON body.
+ self.post_bodies.append(dict(data or json or {}))
+ if json is not None:
+ self.post_json_bodies.append(dict(json))
if not self._post_responses:
raise AssertionError("unexpected extra token request")
return self._post_responses.pop(0)
@@ -117,6 +128,7 @@ def _collect(
with patch(_SESSION_PATCH, return_value=session):
batches: Iterator[list[dict[str, Any]]] = get_rows(
api_key=_API_KEY,
+ shared_secret=_SHARED_SECRET,
refresh_token=_REFRESH_TOKEN,
shop_id=shop_id,
endpoint=endpoint,
@@ -138,6 +150,8 @@ class TestEtsyTransport:
assert session.post_bodies == [
{"grant_type": "refresh_token", "client_id": _API_KEY, "refresh_token": _REFRESH_TOKEN}
]
+ # Etsy's token endpoint rejects a JSON body, which leaves the source unable to connect at all.
+ assert session.post_json_bodies == []
assert session.get_calls[0][2]["Authorization"] == "Bearer token-1"
def test_secrets_are_redacted_and_api_key_header_is_set(self) -> None:
@@ -146,6 +160,7 @@ class TestEtsyTransport:
list(
get_rows(
api_key=_API_KEY,
+ shared_secret=_SHARED_SECRET,
refresh_token=_REFRESH_TOKEN,
shop_id="1",
endpoint="shop_sections",
@@ -155,8 +170,9 @@ class TestEtsyTransport:
)
kwargs = mock_session.call_args.kwargs
- assert kwargs["headers"]["x-api-key"] == _API_KEY
- assert set(kwargs["redact_values"]) == {_API_KEY, _REFRESH_TOKEN}
+ # Etsy rejects a keystring-only x-api-key, so the secret has to ride the same header.
+ assert kwargs["headers"]["x-api-key"] == f"{_API_KEY}:{_SHARED_SECRET}"
+ assert set(kwargs["redact_values"]) == {_API_KEY, _SHARED_SECRET, _REFRESH_TOKEN}
# A custom credential header survives a redirect, so the session must not follow one.
assert kwargs["allow_redirects"] is False
@@ -412,13 +428,13 @@ class TestEtsyValidateCredentials:
def test_valid_credentials_resolve_the_shop(self) -> None:
session = _FakeSession([_response({"user_id": 1, "shop_id": 5})])
with patch(_SESSION_PATCH, return_value=session):
- assert validate_credentials(_API_KEY, _REFRESH_TOKEN, None) == (True, None)
+ assert validate_credentials(_API_KEY, _SHARED_SECRET, _REFRESH_TOKEN, None) == (True, None)
def test_configured_shop_id_still_probes_the_token(self) -> None:
# Skipping the probe here would let a bogus keystring or refresh token pass source creation.
session = _FakeSession([_response({"user_id": 1, "shop_id": None})])
with patch(_SESSION_PATCH, return_value=session):
- assert validate_credentials(_API_KEY, _REFRESH_TOKEN, "77") == (True, None)
+ assert validate_credentials(_API_KEY, _SHARED_SECRET, _REFRESH_TOKEN, "77") == (True, None)
assert session.get_calls[0][0].endswith("/users/me")
@@ -429,7 +445,7 @@ class TestEtsyValidateCredentials:
[_response({}, status=status), _response({}, status=status)], post_responses=[_token(), _token()]
)
with patch(_SESSION_PATCH, return_value=session):
- ok, error = validate_credentials(_API_KEY, _REFRESH_TOKEN, None)
+ ok, error = validate_credentials(_API_KEY, _SHARED_SECRET, _REFRESH_TOKEN, None)
assert ok is False
assert error is not None
@@ -437,19 +453,19 @@ class TestEtsyValidateCredentials:
def test_account_without_a_shop_surfaces_its_own_message(self) -> None:
session = _FakeSession([_response({"user_id": 1, "shop_id": None})])
with patch(_SESSION_PATCH, return_value=session):
- ok, error = validate_credentials(_API_KEY, _REFRESH_TOKEN, None)
+ ok, error = validate_credentials(_API_KEY, _SHARED_SECRET, _REFRESH_TOKEN, None)
assert ok is False
assert error is not None and "no shop" in error
def test_transport_failure_does_not_raise(self) -> None:
with patch(_SESSION_PATCH, side_effect=OSError("boom")):
- assert validate_credentials(_API_KEY, _REFRESH_TOKEN, None)[0] is False
+ assert validate_credentials(_API_KEY, _SHARED_SECRET, _REFRESH_TOKEN, None)[0] is False
def test_invalid_shop_id_fails_validation_without_probing(self) -> None:
# A malformed shop ID is caught up front, so no request is issued to authenticate.
with patch(_SESSION_PATCH, side_effect=AssertionError("must not connect")):
- ok, error = validate_credentials(_API_KEY, _REFRESH_TOKEN, "../users/me")
+ ok, error = validate_credentials(_API_KEY, _SHARED_SECRET, _REFRESH_TOKEN, "../users/me")
assert ok is False
assert error is not None and "positive number" in error
@@ -460,6 +476,7 @@ class TestEtsySourceResponse:
def test_source_response_shape(self, endpoint: str) -> None:
response = etsy_source(
api_key=_API_KEY,
+ shared_secret=_SHARED_SECRET,
refresh_token=_REFRESH_TOKEN,
shop_id="1",
endpoint=endpoint,
@@ -478,6 +495,7 @@ class TestEtsySourceResponse:
session = _FakeSession([_page(_rows(3), 3)])
response = etsy_source(
api_key=_API_KEY,
+ shared_secret=_SHARED_SECRET,
refresh_token=_REFRESH_TOKEN,
shop_id="1",
endpoint="receipts",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy_source.py
index cc3a2aea4aa9..74b7a8d00805 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy_source.py
@@ -1,4 +1,4 @@
-from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.settings import ENDPOINTS, ETSY_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.source import EtsySource
@@ -19,6 +19,17 @@ class TestEtsySourceClass:
# A hidden source cannot be connected — a finished source must stay visible.
assert config.unreleasedSource is None
+ def test_credential_fields_include_the_shared_secret(self) -> None:
+ # Etsy rejects a keystring-only x-api-key, so setup has to collect the secret alongside it.
+ secret_field = next(
+ field
+ for field in EtsySource().get_source_config.fields
+ if isinstance(field, SourceFieldInputConfig) and field.name == "shared_secret"
+ )
+
+ assert secret_field.required is True
+ assert secret_field.secret is True
+
def test_shop_id_is_a_connection_host_field(self) -> None:
# shop_id steers where the stored token is sent, so changing it must force credential re-entry.
assert EtsySource().connection_host_fields == ["shop_id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/etsy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/etsy.py
index d381b0dcff2c..8c4b32949e6e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/etsy.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/etsy.py
@@ -7,5 +7,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class EtsySourceConfig(config.Config):
api_key: str
+ shared_secret: str
refresh_token: str
shop_id: str | None = None