: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(microsoft_clarity): say how to fix a token rejected for the project (#100255)
Tom Owers7d025f42a385
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/microsoft_clarity.py b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/microsoft_clarity.pyindex b6060b52b267..8ecfb4425cab 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/microsoft_clarity.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/microsoft_clarity.py@@ -2,6 +2,7 @@ from datetime import UTC, datetimefrom typing import Any, Optionalimport requests+import structlogfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -13,6 +14,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_BASE_URL = "https://www.clarity.ms"INSIGHTS_PATH = "/export-data/api/v1/project-live-insights"+LOGGER = structlog.get_logger(__name__)+# Cheapest possible probe to confirm a token is genuine: one day, no breakdown dimensions. Still# counts against the project's 10-requests/day quota, which is an accepted tradeoff for validating# credentials at source-create time.@@ -20,6 +23,21 @@ _VALIDATION_NUM_OF_DAYS = "1"_REQUEST_TIMEOUT = 30+TOKEN_INVALID_ERROR = (+ "Your Microsoft Clarity API token is invalid or expired. Generate a new token in Clarity "+ "under Settings -> Data Export and reconnect."+)+# A Clarity token only ever grants access to the project it was generated in, so a 403 means the+# token belongs to another project rather than that it is missing a permission.+TOKEN_WRONG_PROJECT_ERROR = (+ "Your Microsoft Clarity API token isn't authorized for this project. Generate one in the "+ "Clarity project you want to sync, under Settings -> Data Export, then reconnect."+)+TOKEN_CHECK_FAILED_ERROR = (+ "Microsoft Clarity rejected the connection check. Confirm the token is still listed in Clarity "+ "under Settings -> Data Export, then reconnect."+)+def _build_params(num_of_days: str, dimensions: list[str]) -> dict[str, str]:params: dict[str, str] = {"numOfDays": num_of_days}@@ -49,14 +67,15 @@ def validate_credentials(token: str) -> tuple[bool, str | None]:if response.ok:return True, Noneif response.status_code == 401:- return False, "Invalid or expired Microsoft Clarity API token."+ return False, TOKEN_INVALID_ERRORif response.status_code == 403:- return False, "This Microsoft Clarity API token is not authorized for this project."+ return False, TOKEN_WRONG_PROJECT_ERRORif response.status_code == 429:# The project's 10-requests/day quota is already exhausted (possibly by other tooling), but# that doesn't mean the token itself is invalid — don't block source creation over it.return True, None- return False, f"Microsoft Clarity returned status {response.status_code}."+ LOGGER.warning("Microsoft Clarity rejected the credential probe", status_code=response.status_code)+ return False, TOKEN_CHECK_FAILED_ERRORdef _resolve_dimensions(dimension1: Optional[str], dimension2: Optional[str], dimension3: Optional[str]) -> list[str]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/source.pyindex 9a0018fd0ac1..f876b5e1f70e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/source.py@@ -25,6 +25,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_MicrosoftClaritySourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity.microsoft_clarity import (+ TOKEN_INVALID_ERROR,+ TOKEN_WRONG_PROJECT_ERROR,microsoft_clarity_source,validate_credentials as validate_clarity_credentials,)@@ -58,8 +60,8 @@ class MicrosoftClaritySource(SimpleSource[MicrosoftClaritySourceConfig]):def get_non_retryable_errors(self) -> dict[str, str | None]:return {"400 Client Error": "Microsoft Clarity rejected the request. Check the reporting window and breakdown dimensions on this source and reconnect.",- "401 Client Error": "Your Microsoft Clarity API token is invalid or expired. Generate a new token in Clarity under Settings -> Data Export and reconnect.",- "403 Client Error": "This Microsoft Clarity API token is not authorized for this project.",+ "401 Client Error": TOKEN_INVALID_ERROR,+ "403 Client Error": TOKEN_WRONG_PROJECT_ERROR,"429 Client Error": "The Microsoft Clarity daily quota (10 requests per project) has been used up. Try again after the quota resets.",}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity.py b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity.pyindex 92b92a498284..9bf5898440f4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity.py@@ -68,10 +68,31 @@ class TestValidateCredentials:@parameterized.expand([("ok", 200, [], True, None),- ("unauthorized", 401, None, False, "Invalid or expired Microsoft Clarity API token."),- ("forbidden", 403, None, False, "This Microsoft Clarity API token is not authorized for this project."),+ (+ "unauthorized",+ 401,+ None,+ False,+ "Your Microsoft Clarity API token is invalid or expired. Generate a new token in Clarity "+ "under Settings -> Data Export and reconnect.",+ ),+ (+ "forbidden",+ 403,+ None,+ False,+ "Your Microsoft Clarity API token isn't authorized for this project. Generate one in the "+ "Clarity project you want to sync, under Settings -> Data Export, then reconnect.",+ ),("quota_exceeded_still_valid", 429, None, True, None),- ("unexpected_status", 400, None, False, "Microsoft Clarity returned status 400."),+ (+ "unexpected_status",+ 400,+ None,+ False,+ "Microsoft Clarity rejected the connection check. Confirm the token is still listed in Clarity "+ "under Settings -> Data Export, then reconnect.",+ ),])@mock.patch(SESSION_PATCH)