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.

feat(warehouse_sources): add notion permission groups table (#113314)

Tom Owers9ea87be1d402
diff --git a/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt b/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt
index 46ea6f1626a8..c06002ebd6b5 100644
--- a/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt
+++ b/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt
@@ -276,7 +276,6 @@ new_relic/new_relic.py::_get_event_rows
new_york_times/new_york_times.py::_get_article_search_rows
notion/notion.py::_page_fan_out
notion/notion.py::_search_stream
-notion/notion.py::_users_stream
npm_registry/npm_registry.py::_iter_downloads
npm_registry/npm_registry.py::get_rows
nuget/nuget.py::_get_catalog_event_rows
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index b1617b957d8a..fde483a079d2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -5930,6 +5930,14 @@ Diffed against: <https://developers.northpass.com/reference/get_v2-courses>
Note: Enumerated every /reference/get_v2-\* route from the ReadMe-hosted reference page (no public OpenAPI file is served). PostHog covers the 6 core objects plus 2 enrollment fan-outs; the learner-activity and assessment halves of the API are entirely absent.
+## Notion — gaps
+
+Today (6): `blocks`, `comments`, `databases`, `pages`, `permission_groups`, `users`
+
+Diffed against: <https://developers.notion.com/openapi-adminApi.json>
+
+- [x] `GET /admin/v1/spaces/{space_id}/groups` — workspace permission groups from the Admin API, admin-managed and SCIM-managed (medium). Added as `permission_groups`. It needs an optional organization bot token with the `permission-group:read` scope, which only eligible Enterprise organizations get. The workspace id comes from the integration token's bot user.
+
## NpmRegistry — gaps
Today (2): `Downloads`, `Versions`
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/notion.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/notion.py
index 4853561b4d8f..376ece2dd79e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/notion.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/notion.py
@@ -7,3 +7,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class NotionSourceConfig(config.Config):
api_key: str
+ admin_api_key: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/canonical_descriptions.py
index 947da6fce3ff..6c84612553f9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/canonical_descriptions.py
@@ -91,4 +91,13 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"created_by": "Reference to the user who created the comment.",
},
},
+ "permission_groups": {
+ "description": "A permission group in the Notion workspace, either admin-managed or SCIM-managed.",
+ "docs_url": "https://developers.notion.com/reference/admin/list-permission-groups",
+ "columns": {
+ "id": "Unique identifier for the group.",
+ "object": "Always 'group' for this object.",
+ "name": "The name of the group.",
+ },
+ },
}
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.py
index dcc413d32f2b..7877439d0080 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
@@ -2,6 +2,7 @@ import time
import dataclasses
from collections.abc import Callable, Iterator
from typing import Any, Literal, Optional
+from urllib.parse import urlencode
import requests
from structlog.types import FilteringBoundLogger
@@ -34,6 +35,11 @@ NOTION_BASE_URL = "https://api.notion.com"
NOTION_VERSION_2025_09_03 = "2025-09-03"
NOTION_VERSION_2026_03_11 = "2026-03-11"
+# The Admin API takes a different token (an organization bot token) and has its own version line, so
+# the source's version pin does not apply to it. Its header enum accepts only this one value.
+NOTION_ADMIN_BASE_PATH = "/admin"
+NOTION_ADMIN_API_VERSION = "2026-06-01"
+
CHUNK_SIZE = 2000
CHUNK_SIZE_BYTES = 100 * 1024 * 1024
@@ -87,6 +93,10 @@ class NotionBadRequestError(Exception):
the offending block/page and keep syncing rather than crashing the whole sync."""
+class NotionAdminTokenMissingError(Exception):
+ pass
+
+
@dataclasses.dataclass
class NotionResumeConfig:
# Cursor-paginated streams (search, users) persist the next page cursor.
@@ -257,6 +267,50 @@ def validate_credentials(token: str, api_version: str) -> tuple[bool, str | None
return False, TOKEN_CHECK_FAILED_ERROR
+ADMIN_TOKEN_MISSING_ERROR = (
+ "Add an organization bot token with the permission-group:read scope to sync permission groups. "
+ "Organization owners create these tokens in the Notion organization console."
+)
+ADMIN_TOKEN_INVALID_ERROR = (
+ "Your Notion organization bot token is invalid or revoked. Create a new one in the Notion organization console, "
+ "then update this source."
+)
+ADMIN_TOKEN_FORBIDDEN_ERROR = (
+ "Your Notion organization bot token cannot read permission groups. Give it the permission-group:read scope. "
+ "This scope is only available to eligible Notion Enterprise organizations."
+)
+
+
+def check_permission_groups_access(token: str, admin_token: str | None, api_version: str) -> str | None:
+ if not admin_token:
+ return ADMIN_TOKEN_MISSING_ERROR
+ try:
+ public_session = make_tracked_session(headers=_get_headers(token, api_version), redact_values=(token,))
+ me_response = public_session.get(f"{NOTION_BASE_URL}/v1/users/me", timeout=10)
+ # A bad integration token is reported by validate_credentials, not as a per-table problem.
+ if not me_response.ok:
+ return None
+ workspace_id = (me_response.json().get("bot") or {}).get("workspace_id")
+ if not workspace_id:
+ return None
+ admin_session = make_tracked_session(
+ headers=_get_headers(admin_token, NOTION_ADMIN_API_VERSION), redact_values=(admin_token,)
+ )
+ query = urlencode({"page_size": 1})
+ response = admin_session.get(
+ f"{NOTION_BASE_URL}{NOTION_ADMIN_BASE_PATH}/v1/spaces/{workspace_id}/groups?{query}", timeout=10
+ )
+ except Exception as e:
+ capture_exception(e)
+ return None
+
+ if response.status_code == 401:
+ return ADMIN_TOKEN_INVALID_ERROR
+ if response.status_code == 403:
+ return ADMIN_TOKEN_FORBIDDEN_ERROR
+ return None
+
+
def _search_body(object_filter: str, cursor: str | None) -> dict[str, Any]:
body: dict[str, Any] = {
"filter": {"property": "object", "value": object_filter},
@@ -319,8 +373,10 @@ def _search_stream(
yield batcher.get_table()
-def _users_stream(
+def _cursor_list_stream(
session: requests.Session,
+ path: str,
+ stream_name: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
throttle: Optional["_RateLimiter"] = None,
@@ -336,35 +392,73 @@ def _users_stream(
params["start_cursor"] = cursor
try:
- data = _request(session, "GET", "/v1/users", logger, params=params, throttle=throttle)
+ data = _request(session, "GET", path, logger, params=params, throttle=throttle)
except NotionBadRequestError as e:
if cursor is None or not _is_invalid_start_cursor(e):
raise
# A resumed cursor can expire before the retry runs; Notion then rejects it as invalid.
# Restart from the beginning rather than failing the sync — rows dedup on the primary key
# at merge, so replaying loses nothing.
- logger.warning("Notion: resumed users cursor rejected as invalid; restarting stream from the start")
+ logger.warning(
+ f"Notion: resumed {stream_name} cursor rejected as invalid; restarting stream from the start"
+ )
cursor = None
continue
results = data.get("results", [])
- has_more = data.get("has_more", False)
- next_cursor = data.get("next_cursor")
-
- for item in results:
- batcher.batch(item)
- if batcher.should_yield():
- yield batcher.get_table()
- if has_more and next_cursor:
- resumable_source_manager.save_state(NotionResumeConfig(next_cursor=next_cursor))
+ if results:
+ batcher.batch(results)
- if not has_more or not next_cursor:
+ next_cursor = data.get("next_cursor")
+ if not data.get("has_more") or not next_cursor:
break
+ # Yield only at a page boundary, so the staged cursor covers every row in the yielded table.
+ if batcher.should_yield():
+ resumable_source_manager.save_state(NotionResumeConfig(next_cursor=next_cursor))
+ yield batcher.get_table()
cursor = next_cursor
if batcher.should_yield(include_incomplete_chunk=True):
yield batcher.get_table()
+def _users_stream(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
+ throttle: Optional["_RateLimiter"] = None,
+) -> Iterator[Any]:
+ yield from _cursor_list_stream(session, "/v1/users", "users", logger, resumable_source_manager, throttle)
+
+
+def _get_workspace_id(
+ session: requests.Session, logger: FilteringBoundLogger, throttle: Optional["_RateLimiter"] = None
+) -> str:
+ # Admin API paths take the workspace id, which the integration token's bot user reports.
+ data = _request(session, "GET", "/v1/users/me", logger, throttle=throttle)
+ workspace_id = (data.get("bot") or {}).get("workspace_id")
+ if not workspace_id:
+ raise ValueError("Notion did not return a workspace_id for the integration token's bot user")
+ return workspace_id
+
+
+def _permission_groups_stream(
+ session: requests.Session,
+ admin_session: requests.Session,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
+ throttle: Optional["_RateLimiter"] = None,
+) -> Iterator[Any]:
+ workspace_id = _get_workspace_id(session, logger, throttle)
+ yield from _cursor_list_stream(
+ admin_session,
+ f"{NOTION_ADMIN_BASE_PATH}/v1/spaces/{workspace_id}/groups",
+ "permission_groups",
+ logger,
+ resumable_source_manager,
+ throttle,
+ )
+
+
def _iter_page_ids(
session: requests.Session, logger: FilteringBoundLogger, throttle: Optional["_RateLimiter"] = None
) -> Iterator[str]:
@@ -587,12 +681,20 @@ def get_rows(
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
api_version: str,
+ admin_token: str | None = None,
) -> Iterator[Any]:
config = NOTION_ENDPOINTS[endpoint]
session = _build_session(token, api_version)
throttle = _RateLimiter(NOTION_MIN_REQUEST_INTERVAL_SECONDS)
- if config.stream_type == "search":
+ if config.stream_type == "permission_groups":
+ if not admin_token:
+ raise NotionAdminTokenMissingError(
+ "Notion permission_groups table requires an organization bot token, but none is configured"
+ )
+ admin_session = _build_session(admin_token, NOTION_ADMIN_API_VERSION)
+ yield from _permission_groups_stream(session, admin_session, logger, resumable_source_manager, throttle)
+ elif config.stream_type == "search":
yield from _search_stream(session, config, logger, resumable_source_manager, throttle)
elif config.stream_type == "users":
yield from _users_stream(session, logger, resumable_source_manager, throttle)
@@ -610,6 +712,7 @@ def notion_source(
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
api_version: str,
+ admin_token: str | None = None,
) -> SourceResponse:
config = NOTION_ENDPOINTS[endpoint]
@@ -621,6 +724,7 @@ def notion_source(
logger=logger,
resumable_source_manager=resumable_source_manager,
api_version=api_version,
+ admin_token=admin_token,
),
primary_keys=["id"],
partition_count=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/settings.py
index 1e0094155e84..5d9c9eb1752d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/settings.py
@@ -6,7 +6,7 @@ from products.warehouse_sources.backend.types import IncrementalField
# Notion search and query endpoints cap page_size at 100.
NOTION_PAGE_SIZE = 100
-StreamType = Literal["search", "users", "blocks", "comments"]
+StreamType = Literal["search", "users", "blocks", "comments", "permission_groups"]
@dataclass
@@ -49,6 +49,11 @@ NOTION_ENDPOINTS: dict[str, NotionEndpointConfig] = {
stream_type="comments",
partition_key="created_time",
),
+ # Admin API endpoint: needs an organization bot token, and the organization must be on the Enterprise plan.
+ "permission_groups": NotionEndpointConfig(
+ name="permission_groups",
+ stream_type="permission_groups",
+ ),
}
ENDPOINTS = tuple(NOTION_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/source.py
index 03648d14863c..b4c619a2160c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/source.py
@@ -17,9 +17,13 @@ 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.notion import NotionSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.notion.notion import (
+ ADMIN_TOKEN_FORBIDDEN_ERROR,
+ ADMIN_TOKEN_INVALID_ERROR,
+ ADMIN_TOKEN_MISSING_ERROR,
NOTION_VERSION_2025_09_03,
NOTION_VERSION_2026_03_11,
NotionResumeConfig,
+ check_permission_groups_access,
notion_source,
validate_credentials as validate_notion_credentials,
)
@@ -43,7 +47,11 @@ class NotionSource(ResumableSource[NotionSourceConfig, NotionResumeConfig]):
return ExternalDataSourceType.NOTION
def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # The Admin API entries come first: they share the api.notion.com prefix, and the first match wins.
return {
+ "Notion permission_groups table requires an organization bot token": ADMIN_TOKEN_MISSING_ERROR,
+ "401 Client Error: Unauthorized for url: https://api.notion.com/admin": ADMIN_TOKEN_INVALID_ERROR,
+ "403 Client Error: Forbidden for url: https://api.notion.com/admin": ADMIN_TOKEN_FORBIDDEN_ERROR,
"401 Client Error: Unauthorized for url: https://api.notion.com": "Your Notion integration token is invalid or expired. Please generate a new token and reconnect.",
"403 Client Error: Forbidden for url: https://api.notion.com": "Your Notion integration is missing the required capabilities, or the pages/databases you want to sync have not been shared with it.",
}
@@ -86,6 +94,8 @@ class NotionSource(ResumableSource[NotionSourceConfig, NotionResumeConfig]):
Create an internal integration at [notion.so/my-integrations](https://www.notion.so/my-integrations) and copy its token (starts with `ntn_` or `secret_`).
Then **share** each page or database you want to sync with the integration (via the page's `•••` menu → Connections), otherwise it will not be visible to the sync.
+
+To sync the `permission_groups` table, also enter an organization bot token with the `permission-group:read` scope. Organization owners create these tokens in the Notion organization console. This needs a Notion Enterprise plan.
""",
iconPath="/static/services/notion.png",
docsUrl="https://posthog.com/docs/cdp/sources/notion",
@@ -100,6 +110,14 @@ Then **share** each page or database you want to sync with the integration (via
placeholder="ntn_...",
secret=True,
),
+ SourceFieldInputConfig(
+ name="admin_api_key",
+ label="Organization bot token (optional)",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
],
),
)
@@ -145,6 +163,20 @@ Then **share** each page or database you want to sync with the integration (via
# stamped with); a pinned source revalidates under its own `Notion-Version` header.
return validate_notion_credentials(config.api_key, self.resolve_api_version(api_version))
+ def get_endpoint_permissions(
+ self,
+ config: NotionSourceConfig,
+ team_id: int,
+ endpoints: list[str],
+ api_version: str | None = None,
+ ) -> dict[str, str | None]:
+ permissions: dict[str, str | None] = dict.fromkeys(endpoints)
+ if "permission_groups" in permissions:
+ permissions["permission_groups"] = check_permission_groups_access(
+ config.api_key, config.admin_api_key, self.resolve_api_version(api_version)
+ )
+ return permissions
+
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NotionResumeConfig]:
return ResumableSourceManager[NotionResumeConfig](inputs, NotionResumeConfig)
@@ -160,4 +192,5 @@ Then **share** each page or database you want to sync with the integration (via
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
api_version=self.resolve_api_version(inputs.api_version),
+ admin_token=config.admin_api_key,
)
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.py
index f756170c4449..03da0e7a9a69 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
@@ -9,6 +9,9 @@ from parameterized import parameterized
from tenacity import RetryCallState
from products.warehouse_sources.backend.temporal.data_imports.sources.notion.notion import (
+ ADMIN_TOKEN_FORBIDDEN_ERROR,
+ ADMIN_TOKEN_INVALID_ERROR,
+ ADMIN_TOKEN_MISSING_ERROR,
MAX_BLOCK_DEPTH,
MAX_CHILD_PAGES_PER_PARENT,
MAX_RETRY_AFTER_SECONDS,
@@ -24,11 +27,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.notion.not
_iter_block_children,
_iter_page_ids,
_parse_retry_after,
+ _permission_groups_stream,
_request,
_search_body,
_search_stream,
_users_stream,
_wait_strategy,
+ check_permission_groups_access,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.notion.settings import NOTION_ENDPOINTS
@@ -220,6 +225,51 @@ class TestNotion:
assert session.calls[0]["params"]["start_cursor"] == "stale-cursor"
assert "start_cursor" not in session.calls[1]["params"]
+ def test_users_stream_stages_next_cursor_before_yielding_a_finished_page(self) -> None:
+ session = FakeSession(
+ [
+ _list_response([{"id": "u1"}, {"id": "u2"}], has_more=True, next_cursor="c1"),
+ _list_response([{"id": "u3"}], has_more=False, next_cursor=None),
+ ]
+ )
+ manager = _fresh_manager()
+
+ with mock.patch(f"{MODULE}.CHUNK_SIZE", 1):
+ stream = _users_stream(cast(requests.Session, session), mock.MagicMock(), manager)
+ first = next(stream)
+ manager.save_state.assert_called_once_with(NotionResumeConfig(next_cursor="c1"))
+ rest = list(stream)
+
+ assert first.num_rows == 2
+ assert sum(t.num_rows for t in rest) == 1
+
+ def test_permission_groups_stream_pages_through_the_workspace_groups(self) -> None:
+ session = FakeSession([FakeResponse({"object": "user", "bot": {"workspace_id": "ws-1"}})])
+ admin_session = FakeSession(
+ [
+ _list_response([{"object": "group", "id": "g1", "name": "Eng"}], has_more=True, next_cursor="c1"),
+ _list_response([{"object": "group", "id": "g2", "name": "Ops"}], has_more=False, next_cursor=None),
+ ]
+ )
+
+ tables = list(
+ _permission_groups_stream(
+ cast(requests.Session, session),
+ cast(requests.Session, admin_session),
+ mock.MagicMock(),
+ _fresh_manager(),
+ )
+ )
+
+ assert sum(t.num_rows for t in tables) == 2
+ assert session.calls[0]["url"] == "https://api.notion.com/v1/users/me"
+ assert [call["url"] for call in admin_session.calls] == [
+ "https://api.notion.com/admin/v1/spaces/ws-1/groups",
+ "https://api.notion.com/admin/v1/spaces/ws-1/groups",
+ ]
+ assert "start_cursor" not in admin_session.calls[0]["params"]
+ assert admin_session.calls[1]["params"]["start_cursor"] == "c1"
+
def test_iter_page_ids_restarts_when_cursor_invalid(self) -> None:
# A page-id search cursor can expire mid-enumeration on a large workspace, which Notion
# rejects with the same 400 validation_error as the search/users streams. The blocks/comments
@@ -630,11 +680,40 @@ class TestNotion:
assert "Wait a few minutes" in (message or "")
assert "HTTPSConnectionPool" not in (message or "")
+ @parameterized.expand(
+ [
+ ("no_admin_token", None, 200, None, ADMIN_TOKEN_MISSING_ERROR),
+ ("integration_token_rejected", "adm", 401, None, None),
+ ("admin_token_rejected", "adm", 200, 401, ADMIN_TOKEN_INVALID_ERROR),
+ ("admin_scope_missing", "adm", 200, 403, ADMIN_TOKEN_FORBIDDEN_ERROR),
+ ("reachable", "adm", 200, 200, None),
+ ("rate_limited_is_not_a_denial", "adm", 200, 429, None),
+ ]
+ )
+ def test_check_permission_groups_access(
+ self,
+ _name: str,
+ admin_token: str | None,
+ me_status: int,
+ admin_status: int | None,
+ expected: str | None,
+ ) -> None:
+ public_session = FakeSession([FakeResponse({"bot": {"workspace_id": "ws-1"}}, status_code=me_status)])
+ admin_session = FakeSession([FakeResponse({"results": []}, status_code=admin_status or 200)])
+ with mock.patch(f"{MODULE}.make_tracked_session", side_effect=[public_session, admin_session]):
+ message = check_permission_groups_access("tok", admin_token, NOTION_VERSION_2026_03_11)
+
+ assert message == expected
+ expected_admin_urls = (
+ ["https://api.notion.com/admin/v1/spaces/ws-1/groups?page_size=1"] if admin_status is not None else []
+ )
+ assert [call["url"] for call in admin_session.calls] == expected_admin_urls
+
@pytest.mark.parametrize("endpoint", list(NOTION_ENDPOINTS.keys()))
def test_every_endpoint_has_config(endpoint: str) -> None:
config = NOTION_ENDPOINTS[endpoint]
assert config.name == endpoint
- assert config.stream_type in ("search", "users", "blocks", "comments")
+ assert config.stream_type in ("search", "users", "blocks", "comments", "permission_groups")
if config.stream_type == "search":
assert config.object_filter in ("page", "data_source")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion_source.py
index e29e6aa04931..f771fdba6a55 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion_source.py
@@ -5,11 +5,16 @@ import requests
import structlog
from parameterized import parameterized
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.notion import NotionSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.notion.notion import (
+ ADMIN_TOKEN_INVALID_ERROR,
+ ADMIN_TOKEN_MISSING_ERROR,
NOTION_VERSION_2025_09_03,
NOTION_VERSION_2026_03_11,
+ NotionAdminTokenMissingError,
+ get_rows,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.notion.settings import ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.notion.source import NotionSource
@@ -116,6 +121,50 @@ class TestNotionSource:
non_retryable = self.source.get_non_retryable_errors()
assert any(pattern in error_message for pattern in non_retryable)
+ @parameterized.expand(
+ [
+ (
+ "admin_token_rejected",
+ "401 Client Error: Unauthorized for url: https://api.notion.com/admin/v1/spaces/ws-1/groups",
+ ADMIN_TOKEN_INVALID_ERROR,
+ ),
+ (
+ "integration_token_rejected",
+ "401 Client Error: Unauthorized for url: https://api.notion.com/v1/users",
+ "Your Notion integration token is invalid or expired. Please generate a new token and reconnect.",
+ ),
+ ]
+ )
+ def test_non_retryable_error_shows_the_message_for_the_failing_token(
+ self, _name: str, error_message: str, expected_message: str
+ ) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ matching = [
+ message for pattern, message in non_retryable.items() if error_message_matches(error_message, [pattern])
+ ]
+ assert matching[0] == expected_message
+
+ def test_permission_groups_sync_without_admin_token_fails_with_setup_guidance(self) -> None:
+ with mock.patch(f"{NOTION_MODULE}.make_tracked_session"):
+ with pytest.raises(NotionAdminTokenMissingError) as exc_info:
+ list(
+ get_rows("tok", "permission_groups", mock.MagicMock(), mock.MagicMock(), NOTION_VERSION_2026_03_11)
+ )
+
+ non_retryable = self.source.get_non_retryable_errors()
+ matching = [
+ message
+ for pattern, message in non_retryable.items()
+ if error_message_matches(str(exc_info.value), [pattern])
+ ]
+ assert matching == [ADMIN_TOKEN_MISSING_ERROR]
+
+ def test_endpoint_permissions_only_flag_permission_groups_without_admin_token(self) -> None:
+ permissions = self.source.get_endpoint_permissions(
+ NotionSourceConfig(api_key="tok"), team_id=1, endpoints=["pages", "permission_groups"]
+ )
+ assert permissions == {"pages": None, "permission_groups": ADMIN_TOKEN_MISSING_ERROR}
+
def test_other_errors_are_retryable(self) -> None:
non_retryable = self.source.get_non_retryable_errors()
assert not any(