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(data-warehouse): per-endpoint Stripe permission gating (#59950)

Daniel RCa755bfc31c2c
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 254a30141007..7253b900ea32 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5915,6 +5915,12 @@ export interface ExternalDataSourceSyncSchema {
primary_key_columns: string[] | null
available_columns: AvailableColumn[]
detected_primary_keys: string[] | null
+ /**
+ * For sources that gate read access by scope (e.g. Stripe restricted API keys), the
+ * reason this endpoint is currently unreachable. `null`/undefined = endpoint is
+ * available. The UI should disable selection and surface this string when set.
+ */
+ permission_error?: string | null
/**
* User-selected source columns to sync. `null`/undefined = sync all columns.
* PK columns and the active incremental field are always retained server-side.
diff --git a/posthog/temporal/data_imports/sources/common/base.py b/posthog/temporal/data_imports/sources/common/base.py
index 762d8e7c5850..27ad85d3cb3c 100644
--- a/posthog/temporal/data_imports/sources/common/base.py
+++ b/posthog/temporal/data_imports/sources/common/base.py
@@ -111,6 +111,10 @@ class _BaseSource(ABC, Generic[ConfigType]):
"""Check whether the provided credentials are valid for this source. Returns an optional error message"""
return True, None
+ def get_endpoint_permissions(self, config: ConfigType, team_id: int, endpoints: list[str]) -> dict[str, str | None]:
+ """Per-endpoint access check. ``{name: None}`` if reachable, ``{name: reason}`` if not. Default = all reachable."""
+ return dict.fromkeys(endpoints)
+
def cleanup_cdc_resources_on_deletion(self, source: "ExternalDataSource") -> None:
"""Best-effort teardown of CDC resources tied to the source. No-op by default."""
return None
diff --git a/posthog/temporal/data_imports/sources/stripe/source.py b/posthog/temporal/data_imports/sources/stripe/source.py
index 6324d7a343bc..e5a12e17ee87 100644
--- a/posthog/temporal/data_imports/sources/stripe/source.py
+++ b/posthog/temporal/data_imports/sources/stripe/source.py
@@ -19,6 +19,7 @@ from posthog.schema import (
SuggestedTable,
)
+from posthog.exceptions_capture import capture_exception
from posthog.models.integration import OauthIntegration
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
from posthog.temporal.data_imports.sources.common.base import (
@@ -51,6 +52,7 @@ from posthog.temporal.data_imports.sources.stripe.stripe import (
StripePermissionError,
StripeResumeConfig,
StripeValidationError,
+ check_endpoint_permissions as check_stripe_endpoint_permissions,
create_webhook,
delete_webhook,
get_external_webhook_info,
@@ -292,9 +294,11 @@ If automatic creation failed due to a permissions error and you're using a restr
team_id: int,
schema_name: Optional[str] = None,
) -> tuple[bool, str | None]:
+ # No schema_name → basic auth probe. With schema_name → probe that endpoint.
+ endpoints = [schema_name] if schema_name is not None else None
try:
api_key = self._get_api_key(config, team_id)
- if validate_stripe_credentials(api_key, schema_name, auth_method=config.auth_method.selection):
+ if validate_stripe_credentials(api_key, endpoints, auth_method=config.auth_method.selection):
return True, None
else:
return False, "Invalid Stripe credentials"
@@ -334,6 +338,26 @@ If automatic creation failed due to a permissions error and you're using a restr
except Exception as e:
return False, str(e)
+ def get_endpoint_permissions(
+ self, config: StripeSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ # 401 → mark every endpoint with the auth error so caller can surface it once.
+ try:
+ api_key = self._get_api_key(config, team_id)
+ except ValueError as e:
+ # Known credential-config issues from _get_api_key — message is curated and safe to surface.
+ return dict.fromkeys(endpoints, str(e))
+ except Exception as e:
+ # Unknown failure (OAuth refresh, integration lookup, etc.). Capture for triage but
+ # render a generic reason so we never leak an unintended message to the UI.
+ capture_exception(e)
+ return dict.fromkeys(endpoints, "Stripe credentials are not available")
+
+ try:
+ return check_stripe_endpoint_permissions(api_key, endpoints, auth_method=config.auth_method.selection)
+ except StripeAuthenticationError as e:
+ return dict.fromkeys(endpoints, e.stripe_message)
+
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[StripeResumeConfig]:
return ResumableSourceManager[StripeResumeConfig](inputs, StripeResumeConfig)
diff --git a/posthog/temporal/data_imports/sources/stripe/stripe.py b/posthog/temporal/data_imports/sources/stripe/stripe.py
index 2bc979d7ac51..2ff0f047dda9 100644
--- a/posthog/temporal/data_imports/sources/stripe/stripe.py
+++ b/posthog/temporal/data_imports/sources/stripe/stripe.py
@@ -398,90 +398,82 @@ class StripeValidationError(Exception):
super().__init__(message)
+def _resolve_to_flat(
+ name: str, all_resources: dict[str, Union[StripeResource, StripeNestedResource]]
+) -> tuple[str, StripeResource]:
+ """Nested resources display as `<nested> (<parent>)` and probe the parent endpoint."""
+ entry = all_resources[name]
+ if isinstance(entry, StripeNestedResource):
+ # Parent_name registration enforced by test_validate_credentials_nested_resources_have_registered_parents.
+ parent_entry = cast(StripeResource, all_resources[entry.parent_name])
+ return f"{name} ({entry.parent_name})", parent_entry
+ return name, entry
+
+
+def _probe_endpoint(resource: StripeResource) -> tuple[str | None, str | None]:
+ """Cheap limit=1 probe. Returns ``(permission_msg, error_msg)``. 401 raises ``StripeAuthenticationError``.
+
+ Exactly one tuple slot is set on failure; both ``None`` means success.
+ """
+ try:
+ resource.method(params={"limit": 1})
+ return None, None
+ except stripe_lib.AuthenticationError as e:
+ raise StripeAuthenticationError(_clean_stripe_error_message(str(e))) from e
+ except stripe_lib.PermissionError as e:
+ raw = getattr(e, "user_message", None) or str(e)
+ return _clean_stripe_error_message(raw), None
+ except Exception as e:
+ return None, _clean_stripe_error_message(str(e))
+
+
+# customers.list is in default RAK scopes + OAuth-reachable — cheap auth probe.
+_BASIC_AUTH_PROBE_ENDPOINT = CUSTOMER_RESOURCE_NAME
+
+
def validate_credentials(
- api_key: str, table_name: Optional[str] = None, auth_method: Literal["api_key", "oauth"] = "api_key"
+ api_key: str,
+ endpoints: Optional[list[str]] = None,
+ auth_method: Literal["api_key", "oauth"] = "api_key",
) -> bool:
- """
- Validates Stripe API credentials and checks permissions for all required resources.
- Returns True if the API key is valid and has all required permissions.
- Raises StripeAuthenticationError if the key is invalid/expired (401) — short-circuits the per-resource loop
- so the user does not see a misleading "lacks permissions for ALL resources" message.
- Raises StripePermissionError if the key is valid but lacks permissions for specific resources (403).
+ """Validate Stripe credentials.
+
+ - ``endpoints=None``: single auth probe. 401 → ``StripeAuthenticationError``, 403 → pass.
+ - ``endpoints=[...]``: probe each (nested → parent). Raises Permission/Validation errors.
"""
client = StripeClient(api_key, base_addresses=_stripe_base_addresses(), http_client=_tracked_stripe_http_client())
-
- # Drive validation off the same resource definitions get_rows uses — single source of truth.
- # Nested resources (e.g. /v1/customers/:id/payment_methods) can't be listed without a parent
- # ID, so we resolve them to their parent via the StripeNestedResource.parent_name field,
- # which names the top-level entry that gates the same scope.
all_resources = _build_resources(client, logger=None)
- def _resolve_to_flat(name: str) -> tuple[str, StripeResource]:
- """Return (display_name, resource_to_probe) for a given table.
-
- For nested resources, the display name is `<nested> (<parent>)` — keeping the
- nested table the user toggled visible while making the actionable scope (the
- parent) explicit in the same string.
- """
- entry = all_resources[name]
- if isinstance(entry, StripeNestedResource):
- # Type narrowed via the CI test, not at runtime — see
- # test_validate_credentials_nested_resources_have_registered_parents.
- parent_entry = cast(StripeResource, all_resources[entry.parent_name])
- return f"{name} ({entry.parent_name})", parent_entry
- return name, entry
-
- # accounts.list requires Connect platform access — OAuth connected-account tokens can't call it.
- # If a per-table check is requested for Account under OAuth, skip it cleanly: Account is also
- # absent from ENDPOINTS so it can never be synced via OAuth anyway.
- if auth_method == "oauth" and table_name == ACCOUNT_RESOURCE_NAME:
+ if endpoints is None:
+ probe_name, probe_resource = _resolve_to_flat(_BASIC_AUTH_PROBE_ENDPOINT, all_resources)
+ # 403 = auth valid, scope missing — not a failure for the basic check.
+ _, error_msg = _probe_endpoint(probe_resource)
+ if error_msg is not None:
+ raise StripeValidationError({probe_name: error_msg})
return True
missing_permissions: dict[str, str] = {}
errors: dict[str, str] = {}
+ resources_to_check: list[tuple[str, StripeResource]] = []
- if table_name is not None and table_name not in all_resources:
- raise StripePermissionError({table_name: f"{table_name} does not exist"})
-
- if table_name is not None:
- # Single-table validation: hit just that resource (or its parent for nested).
- display_name, flat_resource = _resolve_to_flat(table_name)
- resources_to_check = [(display_name, flat_resource)]
- else:
- # Full validation: probe every flat resource. Nested resources are covered by their
- # parent's check, so no need to enumerate them separately.
- resources_to_check = [
- (name, resource) for name, resource in all_resources.items() if isinstance(resource, StripeResource)
- ]
- if auth_method == "oauth":
- # accounts.list requires Connect platform access — OAuth connected-account tokens can't call it.
- resources_to_check = [
- (name, resource) for name, resource in resources_to_check if name != ACCOUNT_RESOURCE_NAME
- ]
+ for name in endpoints:
+ # OAuth tokens can't call accounts.list (needs Connect platform access). Silent-skip here
+ # because this is a pass/fail validation; check_endpoint_permissions renders an explicit
+ # "not available for OAuth" reason instead since it feeds the UI.
+ if auth_method == "oauth" and name == ACCOUNT_RESOURCE_NAME:
+ continue
+ if name not in all_resources:
+ raise StripePermissionError({name: f"{name} does not exist"})
+ resources_to_check.append(_resolve_to_flat(name, all_resources))
for display_name, resource in resources_to_check:
- try:
- # Override params to limit=1 for cheap permission probing — we don't need real data.
- resource.method(params={"limit": 1})
- except stripe_lib.AuthenticationError as e:
- # 401 — key itself is bad; no point checking other resources, every call will 401 the same way.
- raise StripeAuthenticationError(_clean_stripe_error_message(str(e))) from e
- except stripe_lib.PermissionError as e:
- # 403 — this specific resource is not authorized for the key. The user_message is the
- # concise Stripe explanation; str(e) on a stripe error includes request id, status code,
- # and headers — way too noisy when the cause ("missing X read scope") is already obvious
- # from the resource name.
- raw = getattr(e, "user_message", None) or str(e)
- missing_permissions[display_name] = _clean_stripe_error_message(raw)
- except Exception as e:
- # Anything else (network, schema, rate limit, unexpected Stripe API change) is not a
- # permission problem — track separately so callers can render the verbose underlying
- # message instead of pretending it's a missing scope.
- errors[display_name] = _clean_stripe_error_message(str(e))
-
- # Errors take precedence over permission gaps because they indicate something went genuinely
- # wrong rather than a configuration issue the customer can self-serve. We still pass any
- # collected 403s along so the caller can report both in one message.
+ permission_msg, error_msg = _probe_endpoint(resource)
+ if permission_msg is not None:
+ missing_permissions[display_name] = permission_msg
+ elif error_msg is not None:
+ errors[display_name] = error_msg
+
+ # Non-403 errors win but carry 403s along so the caller can report both.
if errors:
raise StripeValidationError(errors, missing_permissions=missing_permissions)
if missing_permissions:
@@ -490,6 +482,34 @@ def validate_credentials(
return True
+def check_endpoint_permissions(
+ api_key: str,
+ endpoints: list[str],
+ auth_method: Literal["api_key", "oauth"] = "api_key",
+) -> dict[str, str | None]:
+ """Probe each endpoint's read scope. Returns ``{name: None}`` if reachable, ``{name: reason}`` otherwise.
+
+ Never raises for missing permissions (schema UI needs the full picture). 401 still raises.
+ """
+ client = StripeClient(api_key, base_addresses=_stripe_base_addresses(), http_client=_tracked_stripe_http_client())
+ all_resources = _build_resources(client, logger=None)
+
+ results: dict[str, str | None] = {}
+ for name in endpoints:
+ if auth_method == "oauth" and name == ACCOUNT_RESOURCE_NAME:
+ results[name] = "Account is not available for OAuth-connected Stripe sources"
+ continue
+ if name not in all_resources:
+ results[name] = f"{name} is not a known Stripe resource"
+ continue
+
+ _, probe_resource = _resolve_to_flat(name, all_resources)
+ permission_msg, error_msg = _probe_endpoint(probe_resource)
+ results[name] = permission_msg or error_msg
+
+ return results
+
+
def create_webhook(api_key: str, stripe_account_id: str | None, webhook_url: str) -> WebhookCreationResult:
logger = LOGGER.bind()
diff --git a/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py b/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py
index c4d7eb3b8537..8f3c81e6571b 100644
--- a/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py
+++ b/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py
@@ -24,6 +24,7 @@ from posthog.temporal.data_imports.sources.stripe.stripe import (
StripeValidationError,
_build_resources,
_clean_stripe_error_message,
+ check_endpoint_permissions,
validate_credentials,
)
from posthog.temporal.tests.data_imports.conftest import run_external_data_job_workflow
@@ -224,10 +225,7 @@ async def test_stripe_source_incremental(team, mock_stripe_api, external_data_so
}
-def test_validate_credentials():
- mock_client = mock.MagicMock()
-
- # Mock each resource's list method
+def _mock_all_stripe_endpoints(mock_client):
mock_client.accounts.list = mock.MagicMock()
mock_client.balance_transactions.list = mock.MagicMock()
mock_client.charges.list = mock.MagicMock()
@@ -242,56 +240,25 @@ def test_validate_credentials():
mock_client.refunds.list = mock.MagicMock()
mock_client.credit_notes.list = mock.MagicMock()
- with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
- result = validate_credentials("api_key")
-
- assert result is True
- mock_client.accounts.list.assert_called_once_with(params={"limit": 1})
- mock_client.balance_transactions.list.assert_called_once_with(params={"limit": 1})
- mock_client.charges.list.assert_called_once_with(params={"limit": 1})
- mock_client.customers.list.assert_called_once_with(params={"limit": 1})
- mock_client.disputes.list.assert_called_once_with(params={"limit": 1})
- mock_client.invoice_items.list.assert_called_once_with(params={"limit": 1})
- mock_client.invoices.list.assert_called_once_with(params={"limit": 1})
- mock_client.payouts.list.assert_called_once_with(params={"limit": 1})
- mock_client.prices.list.assert_called_once_with(params={"limit": 1})
- mock_client.products.list.assert_called_once_with(params={"limit": 1})
- mock_client.subscriptions.list.assert_called_once_with(params={"limit": 1})
- mock_client.refunds.list.assert_called_once_with(params={"limit": 1})
- mock_client.credit_notes.list.assert_called_once_with(params={"limit": 1})
-
-
-def test_validate_credentials_with_table_name():
+def test_validate_credentials_basic_only_probes_one_endpoint():
+ """Default (no `endpoints`) is the cheap auth probe — one call total. We must not bang
+ every resource during initial source setup; that's what schema selection is for."""
mock_client = mock.MagicMock()
-
- # Mock each resource's list method
- mock_client.accounts.list = mock.MagicMock()
- mock_client.balance_transactions.list = mock.MagicMock()
- mock_client.charges.list = mock.MagicMock()
- mock_client.customers.list = mock.MagicMock()
- mock_client.disputes.list = mock.MagicMock()
- mock_client.invoice_items.list = mock.MagicMock()
- mock_client.invoices.list = mock.MagicMock()
- mock_client.payouts.list = mock.MagicMock()
- mock_client.prices.list = mock.MagicMock()
- mock_client.products.list = mock.MagicMock()
- mock_client.subscriptions.list = mock.MagicMock()
- mock_client.refunds.list = mock.MagicMock()
- mock_client.credit_notes.list = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
- result = validate_credentials("api_key", ACCOUNT_RESOURCE_NAME)
+ result = validate_credentials("api_key")
assert result is True
- # Accounts should be called
- mock_client.accounts.list.assert_called_once_with(params={"limit": 1})
+ # Only the basic-probe endpoint (Customer) is hit.
+ mock_client.customers.list.assert_called_once_with(params={"limit": 1})
- # No other endpoint should be though
+ # Every other endpoint stays untouched.
+ mock_client.accounts.list.assert_not_called()
mock_client.balance_transactions.list.assert_not_called()
mock_client.charges.list.assert_not_called()
- mock_client.customers.list.assert_not_called()
mock_client.disputes.list.assert_not_called()
mock_client.invoice_items.list.assert_not_called()
mock_client.invoices.list.assert_not_called()
@@ -303,14 +270,75 @@ def test_validate_credentials_with_table_name():
mock_client.credit_notes.list.assert_not_called()
-def test_validate_credentials_authentication_error_short_circuits():
- """An invalid API key (401) must raise StripeAuthenticationError immediately,
- not bucket every resource into StripePermissionError. Otherwise the user sees
- a misleading 'lacks permissions for ALL 13 resources' message and tries to
- grant permissions they already have."""
+def test_validate_credentials_basic_treats_403_as_success():
+ """Basic mode is auth-only: a 403 on the probe means the key is valid but lacks that
+ specific scope. Schema selection is responsible for per-endpoint scope reporting, so
+ the wizard's connect step must not block on a missing scope here."""
+ mock_client = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
+ mock_client.customers.list = mock.MagicMock(side_effect=stripe_lib.PermissionError(message="Forbidden"))
+
+ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
+ result = validate_credentials("api_key")
+
+ assert result is True
+
+
+def test_validate_credentials_basic_unknown_error_raises_validation_error():
+ """Network / schema / rate-limit failures on the basic probe must surface as
+ StripeValidationError so the underlying message is shown, not silently swallowed."""
+ mock_client = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
+ mock_client.customers.list = mock.MagicMock(side_effect=RuntimeError("connection reset by peer"))
+
+ with (
+ mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client),
+ pytest.raises(StripeValidationError) as e,
+ ):
+ validate_credentials("api_key")
+
+ assert "connection reset" in next(iter(e.value.errors.values()))
+
+
+def test_validate_credentials_with_explicit_endpoint():
+ """When the caller names one endpoint, only that endpoint is probed."""
+ mock_client = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
+
+ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
+ result = validate_credentials("api_key", endpoints=[ACCOUNT_RESOURCE_NAME])
+
+ assert result is True
+
+ mock_client.accounts.list.assert_called_once_with(params={"limit": 1})
+ mock_client.balance_transactions.list.assert_not_called()
+ mock_client.charges.list.assert_not_called()
+ mock_client.customers.list.assert_not_called()
+
+
+def test_validate_credentials_basic_authentication_error_short_circuits():
+ """An invalid API key (401) on the basic probe must raise StripeAuthenticationError
+ so the user sees the right reason rather than a misleading permissions error."""
+ mock_client = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
+ mock_client.customers.list = mock.MagicMock(
+ side_effect=stripe_lib.AuthenticationError(message="Invalid API Key provided: rk_live_***")
+ )
+
+ with (
+ mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client),
+ pytest.raises(StripeAuthenticationError) as e,
+ ):
+ validate_credentials("api_key")
+
+ assert "Invalid API Key" in str(e.value)
+
+
+def test_validate_credentials_endpoint_list_authentication_error_short_circuits():
+ """In endpoint-list mode, a 401 on any probe must abort the loop immediately —
+ every other call will 401 the same way and we should not keep banging the API."""
mock_client = mock.MagicMock()
auth_error = stripe_lib.AuthenticationError(message="Invalid API Key provided: rk_live_***")
- # First call (accounts) raises 401 — loop must abort before touching others.
mock_client.accounts.list = mock.MagicMock(side_effect=auth_error)
mock_client.balance_transactions.list = mock.MagicMock()
mock_client.charges.list = mock.MagicMock()
@@ -319,94 +347,61 @@ def test_validate_credentials_authentication_error_short_circuits():
mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client),
pytest.raises(StripeAuthenticationError) as e,
):
- validate_credentials("api_key")
+ validate_credentials(
+ "api_key",
+ endpoints=[ACCOUNT_RESOURCE_NAME, "BalanceTransaction", "Charge"],
+ )
assert "Invalid API Key" in str(e.value)
- # Critically: we did not keep banging the API after a 401.
mock_client.balance_transactions.list.assert_not_called()
mock_client.charges.list.assert_not_called()
-def test_validate_credentials_permission_error_lists_only_403_resources():
- """403 on a single resource must be reported as a per-resource permission gap,
+def test_validate_credentials_endpoint_list_permission_error_lists_only_403_resources():
+ """403 on one requested endpoint must be reported as a per-resource permission gap,
not poisoned by other unrelated successes."""
mock_client = mock.MagicMock()
- mock_client.accounts.list = mock.MagicMock()
- mock_client.balance_transactions.list = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
mock_client.charges.list = mock.MagicMock(side_effect=stripe_lib.PermissionError(message="Forbidden"))
- mock_client.customers.list = mock.MagicMock()
- mock_client.disputes.list = mock.MagicMock()
- mock_client.invoice_items.list = mock.MagicMock()
- mock_client.invoices.list = mock.MagicMock()
- mock_client.payouts.list = mock.MagicMock()
- mock_client.prices.list = mock.MagicMock()
- mock_client.products.list = mock.MagicMock()
- mock_client.subscriptions.list = mock.MagicMock()
- mock_client.refunds.list = mock.MagicMock()
- mock_client.credit_notes.list = mock.MagicMock()
with (
mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client),
pytest.raises(StripePermissionError) as e,
):
- validate_credentials("api_key")
+ validate_credentials("api_key", endpoints=["Charge", "Customer", "Account"])
assert list(e.value.missing_permissions.keys()) == ["Charge"]
-def test_validate_credentials_unknown_error_raises_validation_error():
- """Non-403 failures (network, schema, rate limit) are not permission gaps — must raise
- StripeValidationError so the caller surfaces the verbose underlying message rather than
- pretending the customer needs to grant a missing scope."""
+def test_validate_credentials_endpoint_list_unknown_error_raises_validation_error():
+ """Non-403 failures on a requested endpoint surface verbatim via StripeValidationError."""
mock_client = mock.MagicMock()
- mock_client.accounts.list = mock.MagicMock()
- mock_client.balance_transactions.list = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
mock_client.charges.list = mock.MagicMock(side_effect=RuntimeError("connection reset by peer"))
- mock_client.customers.list = mock.MagicMock()
- mock_client.disputes.list = mock.MagicMock()
- mock_client.invoice_items.list = mock.MagicMock()
- mock_client.invoices.list = mock.MagicMock()
- mock_client.payouts.list = mock.MagicMock()
- mock_client.prices.list = mock.MagicMock()
- mock_client.products.list = mock.MagicMock()
- mock_client.subscriptions.list = mock.MagicMock()
- mock_client.refunds.list = mock.MagicMock()
- mock_client.credit_notes.list = mock.MagicMock()
with (
mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client),
pytest.raises(StripeValidationError) as e,
):
- validate_credentials("api_key")
+ validate_credentials("api_key", endpoints=["Charge", "Customer"])
assert list(e.value.errors.keys()) == ["Charge"]
assert "connection reset" in e.value.errors["Charge"]
assert e.value.missing_permissions == {}
-def test_validate_credentials_mixed_403_and_unknown_raises_validation_error_with_both():
- """When both true 403s and unknown errors are present, the validation error should win
- (it's the higher-severity signal) but carry the 403s along so callers can show both."""
+def test_validate_credentials_endpoint_list_mixed_403_and_unknown_raises_validation_error_with_both():
+ """Validation errors win (higher-severity) but carry collected 403s along."""
mock_client = mock.MagicMock()
- mock_client.accounts.list = mock.MagicMock()
- mock_client.balance_transactions.list = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
mock_client.charges.list = mock.MagicMock(side_effect=RuntimeError("connection reset"))
- mock_client.customers.list = mock.MagicMock()
- mock_client.disputes.list = mock.MagicMock()
- mock_client.invoice_items.list = mock.MagicMock()
- mock_client.invoices.list = mock.MagicMock()
- mock_client.payouts.list = mock.MagicMock()
- mock_client.prices.list = mock.MagicMock()
- mock_client.products.list = mock.MagicMock()
mock_client.subscriptions.list = mock.MagicMock(side_effect=stripe_lib.PermissionError(message="Forbidden"))
- mock_client.refunds.list = mock.MagicMock()
- mock_client.credit_notes.list = mock.MagicMock()
with (
mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client),
pytest.raises(StripeValidationError) as e,
):
- validate_credentials("api_key")
+ validate_credentials("api_key", endpoints=["Charge", "Subscription", "Customer"])
assert list(e.value.errors.keys()) == ["Charge"]
assert list(e.value.missing_permissions.keys()) == ["Subscription"]
@@ -425,7 +420,7 @@ def test_validate_credentials_nested_resource_validates_via_parent(nested_table_
mock_client.customers.list = mock.MagicMock()
with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
- result = validate_credentials("api_key", nested_table_name)
+ result = validate_credentials("api_key", endpoints=[nested_table_name])
assert result is True
# The parent's list endpoint is the one we actually call.
@@ -447,7 +442,7 @@ def test_validate_credentials_nested_resource_surfaces_parent_permission_error(n
mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client),
pytest.raises(StripePermissionError) as e,
):
- validate_credentials("api_key", nested_table_name)
+ validate_credentials("api_key", endpoints=[nested_table_name])
assert list(e.value.missing_permissions.keys()) == [f"{nested_table_name} (Customer)"]
@@ -508,27 +503,13 @@ def test_validate_credentials_nested_resources_have_registered_parents():
def test_validate_credentials_with_missing_table_name():
mock_client = mock.MagicMock()
-
- # Mock each resource's list method
- mock_client.accounts.list = mock.MagicMock()
- mock_client.balance_transactions.list = mock.MagicMock()
- mock_client.charges.list = mock.MagicMock()
- mock_client.customers.list = mock.MagicMock()
- mock_client.disputes.list = mock.MagicMock()
- mock_client.invoice_items.list = mock.MagicMock()
- mock_client.invoices.list = mock.MagicMock()
- mock_client.payouts.list = mock.MagicMock()
- mock_client.prices.list = mock.MagicMock()
- mock_client.products.list = mock.MagicMock()
- mock_client.subscriptions.list = mock.MagicMock()
- mock_client.refunds.list = mock.MagicMock()
- mock_client.credit_notes.list = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
with (
mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client),
pytest.raises(StripePermissionError) as e,
):
- validate_credentials("api_key", "bad_table")
+ validate_credentials("api_key", endpoints=["bad_table"])
# No endpoint should be called
mock_client.accounts.list.assert_not_called()
@@ -548,51 +529,84 @@ def test_validate_credentials_with_missing_table_name():
assert "bad_table" in str(e)
-def test_validate_credentials_oauth_skips_account():
+def test_validate_credentials_endpoint_list_oauth_skips_account():
+ """accounts.list requires Connect platform access — OAuth connected-account tokens
+ can't call it. When the caller asks for Account explicitly under OAuth, the probe
+ must be silently dropped rather than producing a confusing 403."""
mock_client = mock.MagicMock()
-
- mock_client.accounts.list = mock.MagicMock()
- mock_client.balance_transactions.list = mock.MagicMock()
- mock_client.charges.list = mock.MagicMock()
- mock_client.customers.list = mock.MagicMock()
- mock_client.disputes.list = mock.MagicMock()
- mock_client.invoice_items.list = mock.MagicMock()
- mock_client.invoices.list = mock.MagicMock()
- mock_client.payouts.list = mock.MagicMock()
- mock_client.prices.list = mock.MagicMock()
- mock_client.products.list = mock.MagicMock()
- mock_client.subscriptions.list = mock.MagicMock()
- mock_client.refunds.list = mock.MagicMock()
- mock_client.credit_notes.list = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
- result = validate_credentials("oauth_token", auth_method="oauth")
+ result = validate_credentials(
+ "oauth_token",
+ endpoints=[ACCOUNT_RESOURCE_NAME, "Customer", "Charge"],
+ auth_method="oauth",
+ )
assert result is True
- # accounts.list requires Connect platform access — must not be called for OAuth tokens
+ # accounts.list must NOT be called for OAuth tokens
mock_client.accounts.list.assert_not_called()
-
- # All other resources should still be checked
- mock_client.balance_transactions.list.assert_called_once_with(params={"limit": 1})
- mock_client.charges.list.assert_called_once_with(params={"limit": 1})
+ # Other listed endpoints still get probed
mock_client.customers.list.assert_called_once_with(params={"limit": 1})
- mock_client.disputes.list.assert_called_once_with(params={"limit": 1})
- mock_client.invoice_items.list.assert_called_once_with(params={"limit": 1})
- mock_client.invoices.list.assert_called_once_with(params={"limit": 1})
- mock_client.payouts.list.assert_called_once_with(params={"limit": 1})
- mock_client.prices.list.assert_called_once_with(params={"limit": 1})
- mock_client.products.list.assert_called_once_with(params={"limit": 1})
- mock_client.subscriptions.list.assert_called_once_with(params={"limit": 1})
- mock_client.refunds.list.assert_called_once_with(params={"limit": 1})
- mock_client.credit_notes.list.assert_called_once_with(params={"limit": 1})
-
-
-def test_validate_credentials_oauth_account_table_name_returns_true():
+ mock_client.charges.list.assert_called_once_with(params={"limit": 1})
+
+
+def test_check_endpoint_permissions_returns_per_endpoint_status():
+ """check_endpoint_permissions feeds the schema-selection UI. It must report each
+ endpoint's status individually instead of short-circuiting on the first denial."""
mock_client = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
+ mock_client.charges.list = mock.MagicMock(side_effect=stripe_lib.PermissionError(message="Forbidden"))
+ mock_client.subscriptions.list = mock.MagicMock(side_effect=RuntimeError("connection reset"))
with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
- result = validate_credentials("oauth_token", ACCOUNT_RESOURCE_NAME, auth_method="oauth")
+ results = check_endpoint_permissions("api_key", endpoints=["Customer", "Charge", "Subscription"])
+
+ assert results["Customer"] is None
+ assert results["Charge"] is not None and "Forbidden" in results["Charge"]
+ assert results["Subscription"] is not None and "connection reset" in results["Subscription"]
+
+
+def test_check_endpoint_permissions_raises_on_401():
+ """A bad key (401) must short-circuit — every probe will fail the same way and the
+ UI needs to surface a credential failure rather than render thirteen denial rows."""
+ mock_client = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
+ mock_client.customers.list = mock.MagicMock(
+ side_effect=stripe_lib.AuthenticationError(message="Invalid API Key provided: rk_live_***")
+ )
+
+ with (
+ mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client),
+ pytest.raises(StripeAuthenticationError),
+ ):
+ check_endpoint_permissions("api_key", endpoints=["Customer", "Charge"])
+
+
+def test_check_endpoint_permissions_oauth_marks_account_as_unavailable():
+ """OAuth tokens can't reach accounts.list. Surface a clear, non-403 reason so the UI
+ can render the right message instead of leaving the user wondering about scopes."""
+ mock_client = mock.MagicMock()
+ _mock_all_stripe_endpoints(mock_client)
+
+ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
+ results = check_endpoint_permissions(
+ "oauth_token", endpoints=[ACCOUNT_RESOURCE_NAME, "Customer"], auth_method="oauth"
+ )
+
+ account_reason = results[ACCOUNT_RESOURCE_NAME]
+ assert account_reason is not None
+ assert "OAuth" in account_reason
+ assert results["Customer"] is None
+ mock_client.accounts.list.assert_not_called()
+
+
+def test_validate_credentials_oauth_account_endpoint_returns_true():
+ mock_client = mock.MagicMock()
+
+ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
+ result = validate_credentials("oauth_token", endpoints=[ACCOUNT_RESOURCE_NAME], auth_method="oauth")
assert result is True
@@ -644,3 +658,27 @@ class TestGetApiKey:
config = StripeSourceConfig.from_dict({"auth_method": {"selection": "oauth", "stripe_integration_id": 99999}})
with pytest.raises(ValueError, match="Integration not found"):
stripe_source._get_api_key(config, team.pk)
+
+
+class TestGetEndpointPermissions:
+ """`get_endpoint_permissions` feeds the UI — it must never leak unexpected exception details."""
+
+ @pytest.fixture
+ def stripe_source(self):
+ return StripeSource()
+
+ def test_value_error_from_get_api_key_surfaces_message(self, stripe_source):
+ config = StripeSourceConfig.from_dict({"auth_method": {"selection": "api_key"}})
+ result = stripe_source.get_endpoint_permissions(config, team_id=1, endpoints=["Customer", "Charge"])
+ # Curated ValueError messages from _get_api_key are safe to render verbatim.
+ assert result == {"Customer": "Missing Stripe API key", "Charge": "Missing Stripe API key"}
+
+ def test_unexpected_exception_renders_generic_reason(self, stripe_source):
+ config = StripeSourceConfig.from_dict(
+ {"auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"}}
+ )
+ with mock.patch.object(stripe_source, "_get_api_key", side_effect=RuntimeError("internal token=secret123")):
+ result = stripe_source.get_endpoint_permissions(config, team_id=1, endpoints=["Customer"])
+ # Generic message — never leak the raw exception body to the UI.
+ assert result == {"Customer": "Stripe credentials are not available"}
+ assert "secret123" not in result["Customer"]
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 469fee7ef933..6f71d18be296 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -1702,6 +1702,15 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
data={"message": str(e)},
)
+ # Best-effort per-endpoint scope probe — transient failure falls back to "available".
+ try:
+ endpoint_permissions = source.get_endpoint_permissions(
+ source_config, self.team_id, [schema.name for schema in schemas]
+ )
+ except Exception as e:
+ capture_exception(e, {"source_type": source_type, "team_id": self.team_id})
+ endpoint_permissions = {schema.name: None for schema in schemas}
+
# Cache the CDC flag once: in non-DEBUG environments this calls posthoganalytics.feature_enabled,
# which makes a network round-trip per call. With large schema lists (e.g. Slack workspaces with
# thousands of channels) the per-iteration call inflated the response loop past the 120s gateway.
@@ -1728,6 +1737,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
for col_name, col_type, nullable in schema.columns
],
"detected_primary_keys": schema.detected_primary_keys,
+ "permission_error": endpoint_permissions.get(schema.name),
}
for schema in schemas
]
diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.py
index 4745379f11ab..3a3aeb51ed17 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_source.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py
@@ -2641,10 +2641,16 @@ class TestExternalDataSource(APIBaseTest):
postgres_connection.close()
def test_database_schema_stripe_credentials(self):
- with patch(
- "posthog.temporal.data_imports.sources.stripe.source.validate_stripe_credentials"
- ) as validate_credentials_mock:
+ with (
+ patch(
+ "posthog.temporal.data_imports.sources.stripe.source.validate_stripe_credentials"
+ ) as validate_credentials_mock,
+ patch(
+ "posthog.temporal.data_imports.sources.stripe.source.check_stripe_endpoint_permissions"
+ ) as check_perms_mock,
+ ):
validate_credentials_mock.return_value = True
+ check_perms_mock.return_value = {}
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_sources/database_schema/",
@@ -2656,6 +2662,10 @@ class TestExternalDataSource(APIBaseTest):
)
assert response.status_code == 200
+ # Each schema in the response should expose the new permission_error field —
+ # mock returns {} so every entry defaults to None (available).
+ for entry in response.json():
+ assert entry["permission_error"] is None
def test_database_schema_stripe_credentials_sad_path(self):
with patch(
@@ -2694,6 +2704,35 @@ class TestExternalDataSource(APIBaseTest):
assert response.status_code == 400
assert "Stripe credentials lack permissions for Account, Invoice" in response.json()["message"]
+ def test_database_schema_stripe_surfaces_per_endpoint_permission_errors(self):
+ """Schema-selection step calls get_endpoint_permissions and merges the per-endpoint
+ result into each schema row so the UI can disable tables the credentials can't reach."""
+ with (
+ patch(
+ "posthog.temporal.data_imports.sources.stripe.source.validate_stripe_credentials"
+ ) as validate_credentials_mock,
+ patch(
+ "posthog.temporal.data_imports.sources.stripe.source.check_stripe_endpoint_permissions"
+ ) as check_perms_mock,
+ ):
+ validate_credentials_mock.return_value = True
+ # Mark Charge as denied; everything else implicitly returns None via .get()
+ check_perms_mock.return_value = {"Charge": "Missing rak_charge_read"}
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/database_schema/",
+ data={
+ "source_type": "Stripe",
+ "auth_method": {"selection": "api_key", "stripe_secret_key": "blah"},
+ "stripe_account_id": "blah",
+ },
+ )
+
+ assert response.status_code == 200
+ by_table = {entry["table"]: entry for entry in response.json()}
+ assert by_table["Charge"]["permission_error"] == "Missing rak_charge_read"
+ assert by_table["Customer"]["permission_error"] is None
+
def test_database_schema_zendesk_credentials(self):
with patch(
"posthog.temporal.data_imports.sources.zendesk.source.validate_credentials"
@@ -2761,6 +2800,7 @@ class TestExternalDataSource(APIBaseTest):
mock_source.get_schemas.return_value = [
SourceSchema(name="table_1", supports_incremental=False, supports_append=False, row_count=42)
]
+ mock_source.get_endpoint_permissions.return_value = {}
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_sources/database_schema/",
@@ -2852,6 +2892,7 @@ class TestExternalDataSource(APIBaseTest):
{"field": "id", "label": "id", "type": "integer", "nullable": True},
],
"detected_primary_keys": ["id"],
+ "permission_error": None,
}
]
@@ -2919,6 +2960,7 @@ class TestExternalDataSource(APIBaseTest):
{"field": "id", "label": "id", "type": "integer", "nullable": True},
],
"detected_primary_keys": ["id"],
+ "permission_error": None,
}
]
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index 76e22b262132..d1c92e08959e 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -444,22 +444,28 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
{
setDatabaseSchemas: (_, { schemas }) => schemas,
toggleAllTables: (state, { selectAll, tableNames }) => {
+ // permission_error rows stay off — bulk toggle never queues guaranteed-403 syncs.
if (!tableNames) {
return state.map((schema) => ({
...schema,
- should_sync: selectAll,
+ should_sync: schema.permission_error ? false : selectAll,
}))
}
const targetSet = new Set(tableNames)
return state.map((schema) => ({
...schema,
- should_sync: targetSet.has(schema.table) ? selectAll : schema.should_sync,
+ should_sync: targetSet.has(schema.table)
+ ? schema.permission_error
+ ? false
+ : selectAll
+ : schema.should_sync,
}))
},
toggleSchemaShouldSync: (state, { schema, shouldSync }) => {
return state.map((s) => ({
...s,
- should_sync: s.table === schema.table ? shouldSync : s.should_sync,
+ should_sync:
+ s.table === schema.table ? (s.permission_error ? false : shouldSync) : s.should_sync,
}))
},
setSchemaSyncedColumns: (state, { schema, enabledColumns }) => {
@@ -1013,7 +1019,9 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
should_sync:
splitDirectQueryTableName(schema.table, values.directQueryDefaultSchema).schemaName ===
schemaName
- ? shouldSync
+ ? schema.permission_error
+ ? false
+ : shouldSync
: schema.should_sync,
}))
)
@@ -1350,6 +1358,12 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
continue
}
+ // Unreachable scope → leave off. User fixes permissions before opting in.
+ if (schema.permission_error) {
+ schema.should_sync = false
+ continue
+ }
+
if (schema.sync_type === null) {
showToast = true
schema.should_sync = schema.should_sync_default ?? true
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
index 4fd54a7085e1..7364d8990663 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
@@ -1,5 +1,6 @@
import type { SourceConfig } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
+import type { ExternalDataSourceSyncSchema } from '~/types'
import {
buildKeaFormDefaultFromSourceDetails,
@@ -664,4 +665,127 @@ describe('sourceWizardLogic', () => {
})
})
})
+
+ // Reducer guards for permission_error rows (Stripe scope gating).
+ describe('permission_error sync gating', () => {
+ const stripeSource = {
+ name: 'Stripe',
+ iconPath: '',
+ caption: null,
+ fields: [],
+ } as SourceConfig
+
+ const buildSchema = (overrides: Partial<ExternalDataSourceSyncSchema> = {}): ExternalDataSourceSyncSchema =>
+ ({
+ table: 'Customer',
+ label: null,
+ rows: null,
+ should_sync: false,
+ sync_time_of_day: null,
+ incremental_field: null,
+ incremental_field_type: null,
+ sync_type: null,
+ incremental_fields: [],
+ incremental_available: false,
+ append_available: false,
+ supports_webhooks: true,
+ description: null,
+ should_sync_default: true,
+ primary_key_columns: null,
+ available_columns: [],
+ detected_primary_keys: null,
+ permission_error: null,
+ ...overrides,
+ }) as ExternalDataSourceSyncSchema
+
+ const mountWithSchemas = (
+ schemas: ExternalDataSourceSyncSchema[]
+ ): { logic: ReturnType<typeof sourceWizardLogic>; unmount: () => void } => {
+ const logic = sourceWizardLogic({
+ availableSources: { Stripe: stripeSource },
+ tabId: `perm-test-${Math.random()}`,
+ })
+ const unmount = logic.mount()
+ logic.actions.selectConnector(stripeSource)
+ logic.actions.setDatabaseSchemas(schemas)
+ return { logic, unmount }
+ }
+
+ it('toggleAllTables(selectAll=true) leaves permission_error rows unchecked', () => {
+ const { logic, unmount } = mountWithSchemas([
+ buildSchema({ table: 'Customer' }),
+ buildSchema({ table: 'Charge', permission_error: 'Missing rak_charge_read' }),
+ ])
+
+ try {
+ logic.actions.toggleAllTables(true)
+ const byTable = Object.fromEntries(logic.values.databaseSchema.map((s) => [s.table, s]))
+ expect(byTable['Customer'].should_sync).toBe(true)
+ expect(byTable['Charge'].should_sync).toBe(false)
+ } finally {
+ unmount()
+ }
+ })
+
+ it('toggleAllTables(selectAll=true) with explicit tableNames still skips permission_error rows', () => {
+ const { logic, unmount } = mountWithSchemas([
+ buildSchema({ table: 'Customer' }),
+ buildSchema({ table: 'Charge', permission_error: 'Missing rak_charge_read' }),
+ ])
+
+ try {
+ logic.actions.toggleAllTables(true, ['Customer', 'Charge'])
+ const byTable = Object.fromEntries(logic.values.databaseSchema.map((s) => [s.table, s]))
+ expect(byTable['Customer'].should_sync).toBe(true)
+ expect(byTable['Charge'].should_sync).toBe(false)
+ } finally {
+ unmount()
+ }
+ })
+
+ it('toggleSchemaShouldSync(true) on a permission_error row stays off', () => {
+ const blockedSchema = buildSchema({
+ table: 'Charge',
+ permission_error: 'Missing rak_charge_read',
+ })
+ const { logic, unmount } = mountWithSchemas([blockedSchema])
+
+ try {
+ logic.actions.toggleSchemaShouldSync(blockedSchema, true)
+ expect(logic.values.databaseSchema[0].should_sync).toBe(false)
+ } finally {
+ unmount()
+ }
+ })
+
+ it('toggleSchemaShouldSync(true) on a normal row still flips it on', () => {
+ const okSchema = buildSchema({ table: 'Customer' })
+ const { logic, unmount } = mountWithSchemas([okSchema])
+
+ try {
+ logic.actions.toggleSchemaShouldSync(okSchema, true)
+ expect(logic.values.databaseSchema[0].should_sync).toBe(true)
+ } finally {
+ unmount()
+ }
+ })
+
+ it('toggleDirectQuerySchemaGroup skips permission_error rows in a group', () => {
+ const { logic, unmount } = mountWithSchemas([
+ buildSchema({ table: 'public.customers' }),
+ buildSchema({ table: 'public.charges', permission_error: 'Missing scope' }),
+ buildSchema({ table: 'public.invoices' }),
+ ])
+
+ try {
+ logic.actions.toggleDirectQuerySchemaGroup('public', true)
+ const byTable = Object.fromEntries(logic.values.databaseSchema.map((s) => [s.table, s]))
+ expect(byTable['public.customers'].should_sync).toBe(true)
+ expect(byTable['public.invoices'].should_sync).toBe(true)
+ expect(byTable['public.charges'].should_sync).toBe(false)
+ } finally {
+ unmount()
+ }
+ })
+ })
})
diff --git a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
index 38bbaee9eeba..466d2d8e9e98 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
@@ -74,6 +74,9 @@ export default function SchemaForm(): JSX.Element {
} = useValues(sourceWizardLogic)
const onClickCheckbox = (schema: ExternalDataSourceSyncSchema, checked: boolean): void => {
+ if (schema.permission_error) {
+ return
+ }
if (!isDirectQueryMode && schema.sync_type === null) {
openSyncMethodModal(schema)
return
@@ -99,6 +102,7 @@ export default function SchemaForm(): JSX.Element {
return (
<LemonCheckbox
checked={schema.should_sync}
+ disabledReason={schema.permission_error ?? undefined}
onChange={(checked) => onClickCheckbox(schema, checked)}
/>
)
@@ -111,12 +115,20 @@ export default function SchemaForm(): JSX.Element {
const isSuggested = suggestedTablesMap[schema.table] !== undefined
const tooltip =
suggestedTablesMap[schema.table] ?? 'This table is suggested to be enabled for this source'
+ const isUnavailable = !!schema.permission_error
return (
<div className="flex items-center gap-2">
<span
- className="font-mono cursor-pointer"
- onClick={() => onClickCheckbox(schema, !schema.should_sync)}
+ className={`font-mono ${
+ isUnavailable ? 'text-muted-alt line-through cursor-not-allowed' : 'cursor-pointer'
+ }`}
+ onClick={() => {
+ if (isUnavailable) {
+ return
+ }
+ onClickCheckbox(schema, !schema.should_sync)
+ }}
>
{schema.label || schema.table}
</span>
@@ -125,6 +137,17 @@ export default function SchemaForm(): JSX.Element {
<IconInfo className="text-muted-alt text-base" />
</Tooltip>
)}
+ {isUnavailable && (
+ <Tooltip
+ title={`Source credentials cannot read this table: ${schema.permission_error}. Grant the missing scope in your source provider and reconnect.`}
+ placement="top"
+ >
+ <LemonTag type="warning" className="cursor-help">
+ <IconWarning className="mr-1" />
+ Permission missing
+ </LemonTag>
+ </Tooltip>
+ )}
{isSuggested && (
<Tooltip title={tooltip} placement="top">
<LemonTag type="primary" className="cursor-help">
@@ -262,6 +285,7 @@ export default function SchemaForm(): JSX.Element {
type="primary"
onClick={() => openSyncMethodModal(schema)}
size="small"
+ disabledReason={schema.permission_error ?? undefined}
>
Configure
</LemonButton>
@@ -276,9 +300,10 @@ export default function SchemaForm(): JSX.Element {
type="secondary"
onClick={() => openSyncMethodModal(schema)}
disabledReason={
- !schema.incremental_available && !schema.append_available && !schema.supports_webhooks
+ schema.permission_error ??
+ (!schema.incremental_available && !schema.append_available && !schema.supports_webhooks
? 'Full refresh is the only supported sync method for this table'
- : undefined
+ : undefined)
}
>
{SyncTypeLabelMap[schema.sync_type]}
@@ -316,6 +341,7 @@ export default function SchemaForm(): JSX.Element {
size="small"
type="secondary"
onClick={() => setColumnSelectionSchema(schema)}
+ disabledReason={schema.permission_error ?? undefined}
>
{summary}
</LemonButton>
@@ -410,19 +436,29 @@ export default function SchemaForm(): JSX.Element {
>
<LemonCheckbox
checked={schema.should_sync}
+ disabledReason={
+ schema.permission_error ?? undefined
+ }
onChange={(checked) =>
onClickCheckbox(schema, checked)
}
/>
<div className="flex items-center gap-2 min-w-0">
<span
- className="font-mono cursor-pointer truncate"
- onClick={() =>
+ className={`font-mono truncate ${
+ schema.permission_error
+ ? 'text-muted-alt line-through cursor-not-allowed'
+ : 'cursor-pointer'
+ }`}
+ onClick={() => {
+ if (schema.permission_error) {
+ return
+ }
onClickCheckbox(
schema,
!schema.should_sync
)
- }
+ }}
>
{tableName}
</span>
@@ -431,6 +467,20 @@ export default function SchemaForm(): JSX.Element {
<IconInfo className="text-muted-alt text-base shrink-0" />
</Tooltip>
)}
+ {schema.permission_error && (
+ <Tooltip
+ title={`Source credentials cannot read this table: ${schema.permission_error}. Grant the missing scope in your source provider and reconnect.`}
+ placement="top"
+ >
+ <LemonTag
+ type="warning"
+ className="cursor-help shrink-0"
+ >
+ <IconWarning className="mr-1" />
+ Permission missing
+ </LemonTag>
+ </Tooltip>
+ )}
{isSuggested && (
<Tooltip title={tooltip} placement="top">
<LemonTag