: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
fix(data-warehouse): accept Cloudflare tokens /user/tokens/verify can't check (#103101)
posthog[bot]3ff8503696e8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/cloudflare.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/cloudflare.pyindex 1442cf760283..914854f98be9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/cloudflare.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/cloudflare.py@@ -4,6 +4,8 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplitfrom requests import Response+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.settings import (ACCOUNTS_PARENT,CLOUDFLARE_ENDPOINTS,@@ -312,26 +314,107 @@ def _fanout_resource(return resources[endpoint].add_map(_rename_parent_key)-def validate_credentials(api_token: str) -> tuple[bool, int | None]:- """Confirm the API token is valid with Cloudflare's token verify endpoint.+def _transient_status(status: int | None) -> bool:+ """Cloudflare was unreachable or busy rather than refusing the token."""+ return status is None or status == 429 or status >= 500+++@frozen+class TokenCheck:+ """Outcome of checking an API token against Cloudflare.++ ``status`` is ``None`` when Cloudflare was never reached, which is what keeps a refused+ token distinguishable from a request that never got an answer.+ """++ is_valid: bool+ status: int | None+ reason: str | None = None++ @property+ def is_transient(self) -> bool:+ return not self.is_valid and _transient_status(self.status)+- Returns ``(is_valid, status_code)``. ``status_code`` is ``None`` when Cloudflare was- unreachable so the caller can tell a rejected token apart from a transient failure and- avoid telling the user their token is invalid when it may be fine.+def _cloudflare_error(response: Response) -> str | None:+ """Cloudflare's own reason for refusing a request, from the `errors` array it returns.++ Without this the caller can only say "rejected", which is the same sentence for a revoked+ token, an IP-filtered one, and a token this endpoint structurally cannot verify."""try:- response = make_tracked_session(redact_values=(api_token,)).get(- f"{CLOUDFLARE_BASE_URL}/user/tokens/verify",+ errors = response.json().get("errors") or []+ except Exception:+ return None+ for error in errors:+ if not isinstance(error, dict):+ continue+ message = str(error.get("message") or "").strip()+ code = error.get("code")+ if message and code:+ return f"{message} (code {code})"+ if message:+ return message+ return None+++def _get(api_token: str, path: str, **params: Any) -> Optional[Response]:+ try:+ return make_tracked_session(redact_values=(api_token,)).get(+ f"{CLOUDFLARE_BASE_URL}{path}",headers={"Authorization": f"Bearer {api_token}"},+ params=params or None,timeout=10,)except Exception:- return False, None+ return None+++def _succeeded(response: Response) -> bool:try:- is_valid = response.status_code == 200 and bool(response.json().get("success"))+ return response.status_code == 200 and bool(response.json().get("success"))except Exception:- is_valid = False- return is_valid, response.status_code+ return False+++def validate_credentials(api_token: str) -> TokenCheck:+ """Confirm the API token can reach the data the connector syncs.++ ``/user/tokens/verify`` only verifies *user* tokens. An account-owned token — the kind+ Cloudflare recommends for durable service integrations, created under Manage Account >+ Account API Tokens — is verified at ``/accounts/{account_id}/tokens/verify`` instead, so it+ is refused here however broad its permissions are, and we hold no account id to check it+ against. Fall back to the two top-level lists the sync fans out from: a token that can read+ either one can run this source, which is the question validation is actually asking.+ """+ verify = _get(api_token, "/user/tokens/verify")+ if verify is not None and _succeeded(verify):+ return TokenCheck(is_valid=True, status=verify.status_code)++ status = verify.status_code if verify is not None else None+ if _transient_status(status):+ return TokenCheck(is_valid=False, status=status)++ # Verify refused, but that refusal is not a verdict on the token, so these probes are what+ # decides. A probe that never got an answer therefore leaves the question open instead of+ # confirming the refusal — reporting "rejected" there would send someone off to rebuild a+ # token that was fine.+ probe_statuses: list[int | None] = []+ for path in _PARENT_PATHS.values():+ probe = _get(api_token, path, per_page=1)+ if probe is None:+ probe_statuses.append(None)+ continue+ if _succeeded(probe):+ return TokenCheck(is_valid=True, status=probe.status_code)+ probe_statuses.append(probe.status_code)++ transient = [probe_status for probe_status in probe_statuses if _transient_status(probe_status)]+ if transient:+ return TokenCheck(is_valid=False, status=transient[0])++ assert verify is not None # a None verify is transient, handled above+ return TokenCheck(is_valid=False, status=status, reason=_cloudflare_error(verify))def cloudflare_source(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/source.pyindex a3766f387900..333ebe56af91 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/source.py@@ -115,18 +115,22 @@ Create an API token in the [Cloudflare dashboard](https://dash.cloudflare.com/prschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- is_valid, status = validate_cloudflare_credentials(config.api_token)- if is_valid:+ check = validate_cloudflare_credentials(config.api_token)+ if check.is_valid:return True, None- if status is None or status == 429 or status >= 500:+ if check.is_transient:return (False,"Couldn't reach Cloudflare to verify your API token. Try again in a moment.",)+ # Naming Cloudflare's own reason matters more than naming a remedy: the token is refused+ # for reasons permissions never explain, so guessing one sends people round in circles.+ detail = f" Cloudflare said: {check.reason}." if check.reason else ""return (False,- "Your Cloudflare API token was rejected. Create a new token with read permissions in your Cloudflare dashboard, then reconnect.",+ f"Cloudflare rejected your API token.{detail} Check the token is still active, isn't "+ "restricted to IP addresses that exclude PostHog, and hasn't expired, then reconnect.",)def source_for_pipeline(self, config: CloudflareSourceConfig, inputs: SourceInputs) -> SourceResponse:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_client.pyindex 790470088056..2295e9952306 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_client.py@@ -10,6 +10,7 @@ from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.cloudflare import (PAGE_SIZE,+ TokenCheck,_redact_access_app,_redact_custom_hostname,_redact_healthcheck,@@ -90,11 +91,22 @@ def _rows(source_response) -> list[dict[str, Any]]:return [row for page in source_response.items() for row in page]+def _rejected_response(status_code: int, message: str | None = None, code: int = 1000) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp.url = "https://api.cloudflare.com/client/v4/user/tokens/verify"+ error: dict[str, Any] = {"code": code}+ if message is not None:+ error["message"] = message+ resp._content = json.dumps({"success": False, "errors": [error]}).encode()+ return resp++class TestValidateCredentials:@mock.patch(CLOUDFLARE_SESSION_PATCH)def test_valid_on_verify_success(self, mock_session) -> None:mock_session.return_value.get.return_value = _response([], total_pages=1)- assert validate_credentials("token") == (True, 200)+ assert validate_credentials("token") == TokenCheck(is_valid=True, status=200)@mock.patch(CLOUDFLARE_SESSION_PATCH)def test_invalid_when_success_false(self, mock_session) -> None:@@ -102,19 +114,99 @@ class TestValidateCredentials:resp.status_code = 200resp._content = json.dumps({"success": False, "result": None}).encode()mock_session.return_value.get.return_value = resp- assert validate_credentials("token") == (False, 200)+ assert validate_credentials("token") == TokenCheck(is_valid=False, status=200)- @pytest.mark.parametrize("status_code", [401, 403, 500])+ @pytest.mark.parametrize("status_code", [401, 403])@mock.patch(CLOUDFLARE_SESSION_PATCH)def test_invalid_on_error_status(self, mock_session, status_code) -> None:mock_session.return_value.get.return_value = _error_response(status_code)# The status flows back so the caller can tell a rejected token from a 5xx/unreachable one.- assert validate_credentials("token") == (False, status_code)+ assert validate_credentials("token") == TokenCheck(is_valid=False, status=status_code)++ @mock.patch(CLOUDFLARE_SESSION_PATCH)+ def test_transient_status_skips_the_fallback_probe(self, mock_session) -> None:+ mock_session.return_value.get.return_value = _error_response(500)+ assert validate_credentials("token") == TokenCheck(is_valid=False, status=500)+ # A 5xx says nothing about the token, so probing twice more only delays the retry advice.+ assert mock_session.return_value.get.call_count == 1@mock.patch(CLOUDFLARE_SESSION_PATCH)def test_unreachable_on_exception(self, mock_session) -> None:mock_session.return_value.get.side_effect = Exception("boom")- assert validate_credentials("token") == (False, None)+ assert validate_credentials("token") == TokenCheck(is_valid=False, status=None)++ @mock.patch(CLOUDFLARE_SESSION_PATCH)+ def test_valid_when_verify_refuses_but_a_parent_list_reads(self, mock_session) -> None:+ # An account-owned token can't be verified at /user/tokens/verify but can still sync.+ mock_session.return_value.get.side_effect = [+ _rejected_response(400, "Invalid API Token"),+ _response([{"id": "z1"}], total_pages=1),+ ]+ assert validate_credentials("token") == TokenCheck(is_valid=True, status=200)++ @mock.patch(CLOUDFLARE_SESSION_PATCH)+ def test_falls_through_to_the_second_parent_list(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = [+ _rejected_response(400, "Invalid API Token"),+ _error_response(403),+ _response([{"id": "a1"}], total_pages=1),+ ]+ assert validate_credentials("token") == TokenCheck(is_valid=True, status=200)++ @mock.patch(CLOUDFLARE_SESSION_PATCH)+ def test_surfaces_cloudflare_reason_when_every_probe_fails(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = [+ _rejected_response(400, "Invalid API Token", code=1000),+ _error_response(403),+ _error_response(403),+ ]+ assert validate_credentials("token") == TokenCheck(+ is_valid=False, status=400, reason="Invalid API Token (code 1000)"+ )++ @mock.patch(CLOUDFLARE_SESSION_PATCH)+ def test_reason_is_none_when_cloudflare_names_no_message(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = [+ _rejected_response(400, None),+ _error_response(403),+ _error_response(403),+ ]+ assert validate_credentials("token") == TokenCheck(is_valid=False, status=400)++ @mock.patch(CLOUDFLARE_SESSION_PATCH)+ def test_probe_exception_leaves_the_question_open(self, mock_session) -> None:+ # Verify's refusal decides nothing on its own, so two probes that never got an answer+ # leave the token unjudged. Reporting it rejected would send someone off to rebuild a+ # token that was fine.+ mock_session.return_value.get.side_effect = [+ _rejected_response(400, "Invalid API Token"),+ Exception("boom"),+ Exception("boom"),+ ]+ check = validate_credentials("token")+ assert check == TokenCheck(is_valid=False, status=None)+ assert check.is_transient++ @mock.patch(CLOUDFLARE_SESSION_PATCH)+ def test_rate_limited_probe_leaves_the_question_open(self, mock_session) -> None:+ # A 429 on one parent says nothing about whether the other would have read.+ mock_session.return_value.get.side_effect = [+ _rejected_response(400, "Invalid API Token"),+ _error_response(429),+ _error_response(403),+ ]+ check = validate_credentials("token")+ assert check == TokenCheck(is_valid=False, status=429)+ assert check.is_transient++ @mock.patch(CLOUDFLARE_SESSION_PATCH)+ def test_definitive_probe_failures_are_not_transient(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = [+ _rejected_response(400, "Invalid API Token"),+ _error_response(403),+ _error_response(403),+ ]+ assert validate_credentials("token").is_transient is Falseclass TestPagination:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_source.pyindex 3c9d3ccf4da6..afcd1169f956 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_source.py@@ -4,6 +4,7 @@ from unittest import mockfrom products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.canonical_descriptions import (CANONICAL_DESCRIPTIONS,)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.cloudflare import TokenCheckfrom products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.settings import (ENDPOINTS,INCREMENTAL_FIELDS,@@ -63,12 +64,19 @@ class TestCloudflareSource:@pytest.mark.parametrize("mock_return, expected_valid, expected_substring",[- ((True, 200), True, None),- ((False, 401), False, "was rejected"),- ((False, 403), False, "was rejected"),- ((False, None), False, "Couldn't reach Cloudflare"),- ((False, 500), False, "Couldn't reach Cloudflare"),- ((False, 429), False, "Couldn't reach Cloudflare"),+ (TokenCheck(is_valid=True, status=200), True, None),+ (TokenCheck(is_valid=False, status=401), False, "Cloudflare rejected your API token."),+ (TokenCheck(is_valid=False, status=403), False, "Cloudflare rejected your API token."),+ # Cloudflare's own reason is what tells a revoked token from one this endpoint+ # structurally cannot verify, so it has to reach the person reading the wizard.+ (+ TokenCheck(is_valid=False, status=400, reason="Invalid API Token (code 1000)"),+ False,+ "Invalid API Token (code 1000)",+ ),+ (TokenCheck(is_valid=False, status=None), False, "Couldn't reach Cloudflare"),+ (TokenCheck(is_valid=False, status=500), False, "Couldn't reach Cloudflare"),+ (TokenCheck(is_valid=False, status=429), False, "Couldn't reach Cloudflare"),],)@mock.patch(