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): route the Pylon source to the EU API host for EU tokens (#96899)

posthog[bot]777602b723a2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/pylon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/pylon.py
index 499549195d77..dbde79a3046d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/pylon.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/pylon.py
@@ -17,7 +17,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.pylon.sett
PylonEndpointConfig,
)
-PYLON_BASE_URL = "https://api.usepylon.com"
+PYLON_US_BASE_URL = "https://api.usepylon.com"
+PYLON_EU_BASE_URL = "https://api.eu.usepylon.com"
+# Pylon issues region-scoped tokens: an EU-residency workspace's token only authenticates against the
+# EU host, and the US host rejects it with a 401 naming the correct region.
+PYLON_EU_TOKEN_PREFIX = "pylon_api_eu_"
class PylonRetryableError(Exception):
@@ -34,6 +38,13 @@ class PylonResumeConfig:
object_type: str | None = None
+def base_url_for_token(api_token: str) -> str:
+ """Pick Pylon's regional API host from the token's prefix, defaulting to US."""
+ if api_token.startswith(PYLON_EU_TOKEN_PREFIX):
+ return PYLON_EU_BASE_URL
+ return PYLON_US_BASE_URL
+
+
def _get_headers(api_token: str) -> dict[str, str]:
return {
"Authorization": f"Bearer {api_token}",
@@ -96,7 +107,8 @@ def validate_credentials(api_token: str) -> bool:
# redact_values masks the bearer token in logs/sample capture; allow_redirects=False keeps the
# credentialed request from following an off-origin redirect that could leak the token.
session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)
- response = session.get(f"{PYLON_BASE_URL}/me", headers=_get_headers(api_token), timeout=10)
+ base_url = base_url_for_token(api_token)
+ response = session.get(f"{base_url}/me", headers=_get_headers(api_token), timeout=10)
return response.status_code == 200
except Exception:
return False
@@ -105,6 +117,7 @@ def validate_credentials(api_token: str) -> bool:
def _iter_pages(
session: requests.Session,
headers: dict[str, str],
+ base_url: str,
path: str,
params: dict[str, Any],
logger: FilteringBoundLogger,
@@ -123,7 +136,7 @@ def _iter_pages(
if cursor:
page_params["cursor"] = cursor
- data = _fetch_page(session, _build_url(f"{PYLON_BASE_URL}{path}", page_params), headers, logger)
+ data = _fetch_page(session, _build_url(f"{base_url}{path}", page_params), headers, logger)
items = data.get("data") or []
pagination = data.get("pagination") or {}
next_cursor = pagination.get("cursor") if pagination.get("has_next_page") else None
@@ -145,6 +158,7 @@ def _iter_pages(
def _get_simple_rows(
session: requests.Session,
headers: dict[str, str],
+ base_url: str,
config: PylonEndpointConfig,
logger: FilteringBoundLogger,
manager: ResumableSourceManager[PylonResumeConfig],
@@ -155,7 +169,7 @@ def _get_simple_rows(
params["limit"] = config.limit
start_cursor = resume.cursor if resume else None
- for items, next_cursor in _iter_pages(session, headers, config.path, params, logger, start_cursor):
+ for items, next_cursor in _iter_pages(session, headers, base_url, config.path, params, logger, start_cursor):
if items:
yield items
# Save AFTER yielding so a crash re-yields the last page rather than skipping it; merge dedupes
@@ -167,6 +181,7 @@ def _get_simple_rows(
def _get_fan_out_rows(
session: requests.Session,
headers: dict[str, str],
+ base_url: str,
config: PylonEndpointConfig,
logger: FilteringBoundLogger,
manager: ResumableSourceManager[PylonResumeConfig],
@@ -188,7 +203,7 @@ def _get_fan_out_rows(
start_cursor = resume_cursor if index == 0 else None
resume_cursor = None
- for items, next_cursor in _iter_pages(session, headers, config.path, params, logger, start_cursor):
+ for items, next_cursor in _iter_pages(session, headers, base_url, config.path, params, logger, start_cursor):
# Stamp the queried object_type so a single table covers every type and the composite
# [object_type, id] primary key stays unique even if two types reuse an id.
stamped = [{**item, "object_type": item.get("object_type") or object_type} for item in items]
@@ -205,6 +220,7 @@ def _get_fan_out_rows(
def _get_windowed_rows(
session: requests.Session,
headers: dict[str, str],
+ base_url: str,
config: PylonEndpointConfig,
logger: FilteringBoundLogger,
manager: ResumableSourceManager[PylonResumeConfig],
@@ -251,7 +267,7 @@ def _get_windowed_rows(
start_cursor = resume_cursor
resume_cursor = None
- for items, next_cursor in _iter_pages(session, headers, config.path, params, logger, start_cursor):
+ for items, next_cursor in _iter_pages(session, headers, base_url, config.path, params, logger, start_cursor):
if items:
yield items
if next_cursor:
@@ -272,6 +288,7 @@ def get_rows(
) -> Iterator[list[dict[str, Any]]]:
config = PYLON_ENDPOINTS[endpoint]
headers = _get_headers(api_token)
+ base_url = base_url_for_token(api_token)
# redact_values masks the bearer token in logs/sample capture; allow_redirects=False keeps the
# credentialed request from following an off-origin redirect that could leak the token.
session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)
@@ -282,6 +299,7 @@ def get_rows(
yield from _get_windowed_rows(
session,
headers,
+ base_url,
config,
logger,
resumable_source_manager,
@@ -290,9 +308,9 @@ def get_rows(
db_incremental_field_last_value,
)
elif config.fan_out_object_types:
- yield from _get_fan_out_rows(session, headers, config, logger, resumable_source_manager, resume)
+ yield from _get_fan_out_rows(session, headers, base_url, config, logger, resumable_source_manager, resume)
else:
- yield from _get_simple_rows(session, headers, config, logger, resumable_source_manager, resume)
+ yield from _get_simple_rows(session, headers, base_url, config, logger, resumable_source_manager, resume)
def pylon_source(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/source.py
index e0378d6b3d03..ff6beb22c016 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/source.py
@@ -19,7 +19,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.pylon import PylonSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.pylon.pylon import (
+ PYLON_EU_BASE_URL,
+ PYLON_US_BASE_URL,
PylonResumeConfig,
+ base_url_for_token,
pylon_source,
validate_credentials as validate_pylon_credentials,
)
@@ -48,7 +51,7 @@ class PylonSource(ResumableSource[PylonSourceConfig, PylonResumeConfig]):
releaseStatus=ReleaseStatus.ALPHA,
caption="""Enter your Pylon API token to pull your Pylon support data into the PostHog Data warehouse.
-You can create an API token from your Pylon dashboard under **Settings > API tokens** (admin only).""",
+You can create an API token from your Pylon dashboard under **Settings > API tokens** (admin only). US and EU workspaces are detected from the token, so there is no region to pick.""",
iconPath="/static/services/pylon.png",
docsUrl="https://posthog.com/docs/cdp/sources/pylon",
fields=cast(
@@ -67,13 +70,17 @@ You can create an API token from your Pylon dashboard under **Settings > API tok
)
def get_non_retryable_errors(self) -> dict[str, str | None]:
- return {
- # A bad/revoked token surfaces as an HTTPError from `raise_for_status()`; retrying can never
- # fix a credential problem. Match the stable status text and base host, not the per-request
- # path/query.
- "401 Client Error: Unauthorized for url: https://api.usepylon.com": "Your Pylon API token is invalid or has been revoked. Create a new token in Settings > API tokens and reconnect.",
- "403 Client Error: Forbidden for url: https://api.usepylon.com": "Your Pylon API token is missing the permissions needed to sync this data. Recreate the token with the required access and reconnect.",
- }
+ invalid_token = "Your Pylon API token is invalid or has been revoked. Create a new token in Settings > API tokens and reconnect."
+ missing_permissions = "Your Pylon API token is missing the permissions needed to sync this data. Recreate the token with the required access and reconnect."
+ # A bad/revoked token surfaces as an HTTPError from `raise_for_status()`; retrying can never
+ # fix a credential problem. Match the stable status text and base host, not the per-request
+ # path/query. Both regional hosts need a key, since the URL in the error is whichever host the
+ # token routed to.
+ errors: dict[str, str | None] = {}
+ for base_url in (PYLON_US_BASE_URL, PYLON_EU_BASE_URL):
+ errors[f"401 Client Error: Unauthorized for url: {base_url}"] = invalid_token
+ errors[f"403 Client Error: Forbidden for url: {base_url}"] = missing_permissions
+ return errors
def get_schemas(
self,
@@ -106,7 +113,12 @@ You can create an API token from your Pylon dashboard under **Settings > API tok
if validate_pylon_credentials(config.api_token):
return True, None
- return False, "Invalid Pylon API token"
+ return (
+ False,
+ f"Pylon rejected this API token at {base_url_for_token(config.api_token)}. "
+ "PostHog picks that host from the token's prefix, so check that you copied the whole token "
+ "from the Pylon workspace you want to sync. You can create a new one under Settings > API tokens.",
+ )
def get_canonical_descriptions(self) -> CanonicalDescriptions:
from products.warehouse_sources.backend.temporal.data_imports.sources.pylon.canonical_descriptions import (
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon.py
index 5da14db465e2..6604b02e2740 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon.py
@@ -11,11 +11,14 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.pylon import pylon
from products.warehouse_sources.backend.temporal.data_imports.sources.pylon.pylon import (
+ PYLON_EU_BASE_URL,
+ PYLON_US_BASE_URL,
PylonResumeConfig,
_build_url,
_format_rfc3339,
_parse_rfc3339,
_to_datetime,
+ base_url_for_token,
get_rows,
pylon_source,
)
@@ -96,14 +99,55 @@ class TestValidateCredentials:
mp.setattr(pylon, "make_tracked_session", lambda *a, **k: session)
assert pylon.validate_credentials("token") is False
- def test_validate_credentials_hits_me_endpoint(self) -> None:
+ @parameterized.expand(
+ [
+ ("eu_token", "pylon_api_eu_abc123", f"{PYLON_EU_BASE_URL}/me"),
+ ("us_token", "pylon_api_abc123", f"{PYLON_US_BASE_URL}/me"),
+ ("unprefixed_token", "token", f"{PYLON_US_BASE_URL}/me"),
+ ]
+ )
+ def test_validate_credentials_hits_me_endpoint(self, _name: str, api_token: str, expected_url: str) -> None:
session = MagicMock()
session.get.return_value = MagicMock(status_code=200)
with pytest.MonkeyPatch().context() as mp:
mp.setattr(pylon, "make_tracked_session", lambda *a, **k: session)
- pylon.validate_credentials("token")
+ pylon.validate_credentials(api_token)
called_url = session.get.call_args.args[0]
- assert called_url == "https://api.usepylon.com/me"
+ assert called_url == expected_url
+
+
+class TestBaseUrlForToken:
+ @parameterized.expand(
+ [
+ ("eu_prefix", "pylon_api_eu_abc123", PYLON_EU_BASE_URL),
+ ("us_prefix", "pylon_api_abc123", PYLON_US_BASE_URL),
+ ("unprefixed", "token", PYLON_US_BASE_URL),
+ # "eu" only routes as the documented prefix, not anywhere in the token.
+ ("eu_elsewhere", "pylon_api_zeu_abc", PYLON_US_BASE_URL),
+ ]
+ )
+ def test_routes_by_prefix(self, _name: str, api_token: str, expected: str) -> None:
+ assert base_url_for_token(api_token) == expected
+
+
+class TestSyncPathRegion:
+ @parameterized.expand(
+ [
+ ("eu_token", "pylon_api_eu_abc123", PYLON_EU_BASE_URL),
+ ("us_token", "pylon_api_abc123", PYLON_US_BASE_URL),
+ ]
+ )
+ def test_get_rows_requests_the_tokens_region(self, _name: str, api_token: str, expected_base: str) -> None:
+ fetch_page = MagicMock(return_value=_page([{"id": "1"}]))
+ manager = _no_resume_manager()
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", fetch_page)
+ list(get_rows(api_token=api_token, endpoint="teams", logger=MagicMock(), resumable_source_manager=manager))
+
+ requested_url = fetch_page.call_args.args[1]
+ assert requested_url.startswith(expected_base)
class TestSimpleEndpointPagination:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon_source.py
index 4bf5da010fab..d60684d7d08d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon_source.py
@@ -7,6 +7,10 @@ from posthog.schema import ExternalDataSourceType as SchemaExternalDataSourceTyp
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.pylon import PylonSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.pylon import source as pylon_source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.pylon.pylon import (
+ PYLON_EU_BASE_URL,
+ PYLON_US_BASE_URL,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.pylon.settings import ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.pylon.source import PylonSource
@@ -46,12 +50,32 @@ class TestPylonGetSchemas:
class TestPylonValidateCredentials:
- @parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid Pylon API token"))])
- def test_validate_credentials(self, _name: str, api_returns: bool, expected: tuple[bool, str | None]) -> None:
+ def test_valid_token(self) -> None:
with pytest.MonkeyPatch().context() as mp:
- mp.setattr(pylon_source_module, "validate_pylon_credentials", lambda token: api_returns)
- result = PylonSource().validate_credentials(_config(), team_id=1)
- assert result == expected
+ mp.setattr(pylon_source_module, "validate_pylon_credentials", lambda token: True)
+ assert PylonSource().validate_credentials(_config(), team_id=1) == (True, None)
+
+ @parameterized.expand(
+ [
+ ("eu_token", "pylon_api_eu_abc123", PYLON_EU_BASE_URL),
+ ("us_token", "pylon_api_abc123", PYLON_US_BASE_URL),
+ ]
+ )
+ def test_failure_names_the_host_that_was_checked(self, _name: str, api_token: str, expected_host: str) -> None:
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon_source_module, "validate_pylon_credentials", lambda token: False)
+ ok, message = PylonSource().validate_credentials(_config(api_token), team_id=1)
+ assert ok is False
+ assert message is not None
+ assert expected_host in message
+
+
+class TestPylonNonRetryableErrors:
+ @parameterized.expand([("us", PYLON_US_BASE_URL), ("eu", PYLON_EU_BASE_URL)])
+ def test_covers_both_regional_hosts(self, _name: str, base_url: str) -> None:
+ errors = PylonSource().get_non_retryable_errors()
+ assert f"401 Client Error: Unauthorized for url: {base_url}" in errors
+ assert f"403 Client Error: Forbidden for url: {base_url}" in errors
class TestPylonSourceForPipeline: