: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(notion): tell the customer what to do when the token check fails (#103412)
Tom Owersdeb7df4a3582
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.pyindex 19cc0108aae7..8d2dcb049a7e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py@@ -8,6 +8,8 @@ from structlog.types import FilteringBoundLoggerfrom tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitterfrom urllib3.util.retry import Retry+from posthog.exceptions_capture import capture_exception+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcherfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -216,20 +218,37 @@ def _request() from e+# Setup-time messages for a token Notion refuses. Worded to match the sync-time messages the+# source class maps the same two failures to, so the same problem reads the same way in the+# wizard and in the sync error panel.+INVALID_TOKEN_ERROR = (+ "Your Notion integration token is invalid or expired. Create a new internal integration token in Notion, "+ "then enter it here."+)+MISSING_CAPABILITIES_ERROR = (+ "Your Notion integration cannot read your content. Give it read capabilities in Notion and share the pages "+ "and databases you want to sync with it."+)+# The raw exception, and Notion's own error body, carry request URLs and response detail that mean+# nothing to the person filling in the form. Capture them instead and show fixed guidance.+TOKEN_CHECK_FAILED_ERROR = "PostHog could not check your Notion token. Wait a few minutes, then try again."++def validate_credentials(token: str, api_version: str) -> tuple[bool, str | None]:try:session = make_tracked_session(headers=_get_headers(token, api_version), redact_values=(token,))response = session.get(f"{NOTION_BASE_URL}/v1/users/me", timeout=10)except Exception as e:- return False, str(e)+ capture_exception(e)+ return False, TOKEN_CHECK_FAILED_ERRORif response.status_code == 200:return True, Noneif response.status_code == 401:- return False, "Invalid Notion integration token"+ return False, INVALID_TOKEN_ERRORif response.status_code == 403:- return False, "Notion integration token is missing the required capabilities"- return False, f"Notion API error: HTTP {response.status_code}"+ return False, MISSING_CAPABILITIES_ERROR+ return False, TOKEN_CHECK_FAILED_ERRORdef _search_body(object_filter: str, cursor: str | None) -> dict[str, Any]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.pyindex 67c92eb101a0..bcd395959564 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py@@ -545,8 +545,18 @@ class TestNotion:assert len(session.calls) == 1 + MAX_CHILD_PAGES_PER_PARENTassert logger.warning.called- @parameterized.expand([(200, True), (401, False), (403, False), (500, False)])- def test_validate_credentials_status_mapping(self, status_code: int, expected_valid: bool) -> None:+ @parameterized.expand(+ [+ (200, True, None),+ (401, False, "Create a new internal integration token"),+ (403, False, "Give it read capabilities"),+ (500, False, "Wait a few minutes"),+ ]+ )+ def test_validate_credentials_status_mapping(+ self, status_code: int, expected_valid: bool, expected_next_step: str | None+ ) -> None:+ # Every refusal has to name a next step: the wizard shows this string and nothing else.session = FakeSession([FakeResponse({}, status_code=status_code)])with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):valid, message = validate_credentials("tok", NOTION_VERSION_2026_03_11)@@ -555,14 +565,22 @@ class TestNotion:if expected_valid:assert message is Noneelse:- assert message is not None+ assert expected_next_step is not None+ assert expected_next_step in (message or "")+ assert str(status_code) not in (message or "")def test_validate_credentials_handles_exception(self) -> None:- with mock.patch(f"{MODULE}.make_tracked_session", side_effect=requests.ConnectionError("boom")):+ # A connection error repr names the host and the urllib3 internals, none of which the+ # person filling in the token field can act on.+ with mock.patch(+ f"{MODULE}.make_tracked_session",+ side_effect=requests.ConnectionError("HTTPSConnectionPool(host='api.notion.com', port=443)"),+ ):valid, message = validate_credentials("tok", NOTION_VERSION_2026_03_11)assert valid is False- assert message == "boom"+ assert "Wait a few minutes" in (message or "")+ assert "HTTPSConnectionPool" not in (message or "")@pytest.mark.parametrize("endpoint", list(NOTION_ENDPOINTS.keys()))