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(klaviyo): say why the API key failed instead of calling it invalid (#107226)

Tom Owerse879fd7ecf22
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
index 4c08b7b452f9..2b7a762bc53d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
@@ -8,9 +8,12 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.exceptions_capture import capture_exception
+
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.constants import (
KLAVIYO_API_VERSION_2026_07_15,
@@ -158,15 +161,41 @@ def _get_headers(api_key: str, revision: str = KLAVIYO_API_VERSION_2026_07_15) -
}
-def validate_credentials(api_key: str, api_version: str = KLAVIYO_API_VERSION_2026_07_15) -> bool:
+_KLAVIYO_INVALID_KEY_ERROR = (
+ "Your Klaviyo API key is invalid or has been revoked. Create a new private API key in your "
+ "Klaviyo account settings, then reconnect."
+)
+
+# The probe reads /accounts, so a scoped key that was never granted account read lands here even
+# though it is a live key. Telling that user to replace the key sends them down the wrong path.
+_KLAVIYO_MISSING_SCOPE_ERROR = (
+ "Your Klaviyo API key can't read your account. Give the key read access to Accounts in your "
+ "Klaviyo account settings, then reconnect."
+)
+
+_KLAVIYO_UNREACHABLE_ERROR = "Couldn't reach Klaviyo to validate your API key. Try again in a few minutes."
+
+
+def validate_credentials(api_key: str, api_version: str = KLAVIYO_API_VERSION_2026_07_15) -> tuple[bool, str | None]:
# Probe under the caller's resolved pin so a 2024-10-15-pinned source validates on the
# same `revision` header it syncs with.
- url = f"{KLAVIYO_BASE_URL}/accounts"
- try:
- response = make_tracked_session().get(url, headers=_get_headers(api_key, api_version), timeout=10)
- return response.status_code == 200
- except Exception:
- return False
+ ok, status = validate_via_probe(
+ make_tracked_session,
+ f"{KLAVIYO_BASE_URL}/accounts",
+ headers=_get_headers(api_key, api_version),
+ )
+ if ok:
+ return True, None
+ if status == 401:
+ return False, _KLAVIYO_INVALID_KEY_ERROR
+ if status == 403:
+ return False, _KLAVIYO_MISSING_SCOPE_ERROR
+ # No status means the request never completed. That, a rate limit and a Klaviyo-side error are
+ # all transient, so none of them should point the user at a key that may be fine.
+ if status is None or status == 429 or status >= 500:
+ return False, _KLAVIYO_UNREACHABLE_ERROR
+ capture_exception(Exception(f"Unexpected Klaviyo credential validation response ({status})"))
+ return False, _KLAVIYO_INVALID_KEY_ERROR
def _flatten_item(item: dict[str, Any]) -> dict[str, Any]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/source.py
index 8585b9772c85..263a838681c2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/source.py
@@ -190,10 +190,7 @@ The campaign and flow performance tables (campaign_values_reports, flow_values_r
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- if validate_klaviyo_credentials(config.api_key, self.resolve_api_version(api_version)):
- return True, None
-
- return False, "Invalid Klaviyo API key"
+ return validate_klaviyo_credentials(config.api_key, self.resolve_api_version(api_version))
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KlaviyoResumeConfig]:
return ResumableSourceManager[KlaviyoResumeConfig](inputs, KlaviyoResumeConfig)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
index 61bb2da5725e..2147ef39dd48 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
@@ -1520,7 +1520,7 @@ class TestValidateCredentialsResolvedPin:
def test_class_probe_threads_resolved_pin(self, pin: str | None, expected: str) -> None:
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.source.validate_klaviyo_credentials",
- return_value=True,
+ return_value=(True, None),
) as mock_validate:
KlaviyoSource().validate_credentials(KlaviyoSourceConfig(api_key="pk_test"), 1, api_version=pin)
@@ -1532,7 +1532,30 @@ class TestValidateCredentialsResolvedPin:
with patch.object(klaviyo, "make_tracked_session") as session_factory:
response = MagicMock(status_code=200)
session_factory.return_value.get.return_value = response
- assert klaviyo.validate_credentials("pk_test", api_version) is True
+ assert klaviyo.validate_credentials("pk_test", api_version) == (True, None)
headers = session_factory.return_value.get.call_args.kwargs["headers"]
assert headers["revision"] == api_version
+
+ @parameterized.expand(
+ [
+ (401, klaviyo._KLAVIYO_INVALID_KEY_ERROR),
+ (403, klaviyo._KLAVIYO_MISSING_SCOPE_ERROR),
+ (503, klaviyo._KLAVIYO_UNREACHABLE_ERROR),
+ ]
+ )
+ def test_failure_status_picks_the_matching_message(self, status: int, expected: str) -> None:
+ with patch.object(klaviyo, "make_tracked_session") as session_factory:
+ session_factory.return_value.get.return_value = MagicMock(status_code=status)
+ ok, error = klaviyo.validate_credentials("pk_test")
+
+ assert ok is False
+ assert error == expected
+
+ def test_unreachable_klaviyo_does_not_blame_the_key(self) -> None:
+ with patch.object(klaviyo, "make_tracked_session") as session_factory:
+ session_factory.return_value.get.side_effect = requests.ConnectionError("boom")
+ ok, error = klaviyo.validate_credentials("pk_test")
+
+ assert ok is False
+ assert error == klaviyo._KLAVIYO_UNREACHABLE_ERROR