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.

fix(data-warehouse): stop offering webhook setup and tables OAuth cannot reach (#81275)

Tom Owers3a3d940be592
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 23df7efd2fb3..bdf11802a2a0 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6337,6 +6337,10 @@ export interface WebhookInfo {
external_status?: WebhookExternalStatus | null
// Desired provider events not yet on the webhook (manual setup, or created before a new table).
missing_events?: string[]
+ // Set when the connection's credentials can never create the webhook, so only manual setup is
+ // left. Null means "not known to be blocked", which is the answer for any credential whose
+ // grants can't be introspected.
+ auto_creation_blocked_reason?: string | null
}
export interface DataModelingJob {
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx
index 7f76f7ee8738..717c14f8115f 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx
@@ -84,6 +84,7 @@ export function WebhookTab({ id }: { id: string }): JSX.Element {
sourceConfig={sourceConfig}
webhookResult={createWebhookResult}
webhookCreating={webhookCreating}
+ autoCreationBlockedReason={webhookInfo?.auto_creation_blocked_reason}
onCreateWebhook={createWebhook}
formLogic={webhookTabLogic(logicProps)}
formKey="webhookFieldInputs"
@@ -132,6 +133,7 @@ export function WebhookTab({ id }: { id: string }): JSX.Element {
sourceConfig={sourceConfig}
webhookCreating={webhookCreating}
createWebhookResult={createWebhookResult}
+ autoCreationBlockedReason={webhookInfo.auto_creation_blocked_reason}
onCreateWebhook={createWebhook}
/>
)}
@@ -306,6 +308,7 @@ function WebhookRecreateSection({
sourceConfig,
webhookCreating,
createWebhookResult,
+ autoCreationBlockedReason,
onCreateWebhook,
}: {
id: string
@@ -313,6 +316,7 @@ function WebhookRecreateSection({
sourceConfig: any
webhookCreating: boolean
createWebhookResult: WebhookCreateResult | null
+ autoCreationBlockedReason?: string | null
onCreateWebhook: () => void
}): JSX.Element {
return (
@@ -321,6 +325,7 @@ function WebhookRecreateSection({
sourceConfig={sourceConfig}
webhookResult={createWebhookResult}
webhookCreating={webhookCreating}
+ autoCreationBlockedReason={autoCreationBlockedReason}
onCreateWebhook={onCreateWebhook}
formLogic={webhookTabLogic({ id })}
formKey="webhookFieldInputs"
diff --git a/products/data_warehouse/frontend/shared/components/forms/WebhookSetupForm.tsx b/products/data_warehouse/frontend/shared/components/forms/WebhookSetupForm.tsx
index 8036e4b8da26..166a20eecb69 100644
--- a/products/data_warehouse/frontend/shared/components/forms/WebhookSetupForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/WebhookSetupForm.tsx
@@ -34,6 +34,12 @@ interface WebhookSetupFormProps {
webhookCreating: boolean
/** Whether the manual webhook fields form is currently submitting — guards the Save button against double-submission */
webhookFieldsSubmitting?: boolean
+ /**
+ * Why this connection's credentials can never register the webhook, when that's knowable. Set
+ * for OAuth app installations whose granted permissions exclude webhook management: offering
+ * the button there only yields a permission error, so manual setup is the whole flow.
+ */
+ autoCreationBlockedReason?: string | null
onCreateWebhook: () => void
/** kea-forms logic and formKey for the manual webhook field inputs form */
formLogic?: LogicWrapper | BuiltLogic<any>
@@ -51,12 +57,15 @@ export function WebhookSetupForm({
webhookResult,
webhookCreating,
webhookFieldsSubmitting = false,
+ autoCreationBlockedReason,
onCreateWebhook,
formLogic,
formKey,
}: WebhookSetupFormProps): JSX.Element {
const webhookFields = sourceConfig?.webhookFields ?? []
- const manualOnly = sourceConfig?.webhookManualOnly ?? false
+ // A blocked connection is manual-only in practice, so it takes the same path as a source that
+ // never supported auto-creation: generate the URL, then show the manual steps.
+ const manualOnly = (sourceConfig?.webhookManualOnly ?? false) || !!autoCreationBlockedReason
const webhookTablesList =
webhookTables && webhookTables.length > 0 ? (
@@ -87,10 +96,11 @@ export function WebhookSetupForm({
that new data is pushed to PostHog. This means faster syncs and less load on your source.
</p>
{webhookTablesList}
- <LemonBanner type="info">
- {manualOnly
- ? `We'll generate a webhook URL — you'll need to register it manually in your ${sourceName} app settings.`
- : `We'll automatically register the webhook on your ${sourceName} account. No manual configuration is needed.`}
+ <LemonBanner type={autoCreationBlockedReason ? 'warning' : 'info'}>
+ {autoCreationBlockedReason ||
+ (manualOnly
+ ? `We'll generate a webhook URL. You'll need to register it manually in your ${sourceName} app settings.`
+ : `We'll automatically register the webhook on your ${sourceName} account. No manual configuration is needed.`)}
</LemonBanner>
{sourceConfig?.docsUrl && (
<p className="text-sm text-muted">
@@ -170,9 +180,9 @@ export function WebhookSetupForm({
return (
<WebhookSetupCard>
<h3 className="text-lg font-semibold">Manual webhook setup for {sourceName}</h3>
- {!manualOnly && (
+ {(!manualOnly || !!autoCreationBlockedReason) && (
<LemonBanner type="warning">
- {webhookResult?.error || 'Could not create the webhook automatically.'}
+ {autoCreationBlockedReason || webhookResult?.error || 'Could not create the webhook automatically.'}
</LemonBanner>
)}
<p>
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index 115c1ef59742..9871899d73ea 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import uuid
import dataclasses
-from collections.abc import Callable, Iterable
+from collections.abc import Callable, Iterable, Mapping
from datetime import UTC, datetime, timedelta
from typing import Any, cast
from urllib.parse import quote
@@ -3247,10 +3247,29 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
data={"message": "No tables found for this source. Check the credentials and permissions."},
)
+ # Same best-effort per-table scope probe the schema picker runs, so one-shot setup doesn't
+ # enable tables the credentials can only ever 403 on. Transient failure falls back to
+ # "available", which is the pre-probe behavior.
+ try:
+ setup_permissions = source.get_endpoint_permissions(
+ source_config, self.team_id, [schema.name for schema in source_schemas]
+ )
+ except Exception as e:
+ capture_exception(e, {"source_type": source_type, "team_id": self.team_id})
+ setup_permissions = {}
+
+ # Some sources report a probe that couldn't run as a per-table reason rather than raising
+ # (Stripe does this so the picker can render one row per failure). Setup has no such UI: a
+ # blanket denial would silently create a source with every table off. Credentials that
+ # genuinely read nothing are already rejected by validate_credentials above, so read
+ # "everything denied" as an unreliable probe and keep the polling defaults.
+ if setup_permissions and all(setup_permissions.get(schema.name) for schema in source_schemas):
+ setup_permissions = {}
+
# Build the schemas array server-side so the caller never has to. We've already validated
# config + credentials above, so `_create_external_data_source` skips that second gate
# (`skip_credential_validation`) to avoid a duplicate live credential round-trip.
- payload["schemas"] = build_default_schemas(source_schemas)
+ payload["schemas"] = build_default_schemas(source_schemas, permission_errors=setup_permissions)
response = self._create_external_data_source(
request,
@@ -3269,7 +3288,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
if response.status_code == status.HTTP_201_CREATED and isinstance(source, WebhookSource):
webhook_result = self._auto_register_webhook(
- source, source_config, str(response.data["id"]), source_schemas
+ source, source_config, str(response.data["id"]), source_schemas, permission_errors=setup_permissions
)
if webhook_result is not None:
response.data["webhook"] = webhook_result
@@ -3426,6 +3445,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
source_config: Config,
source_id: str,
source_schemas: list[SourceSchema],
+ permission_errors: Mapping[str, str | None] | None = None,
) -> dict | None:
"""Best-effort webhook auto-registration for one-shot setup.
@@ -3437,12 +3457,22 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
"""
# Tables marked `should_sync_default=False` need explicit opt-in even when webhook-capable —
# one-shot setup must not force-enable what the schema picker would leave off (the same
- # contract `build_default_schemas` honors).
- webhook_capable = {s.name for s in source_schemas if s.supports_webhooks and s.should_sync_default}
+ # contract `build_default_schemas` honors). A table the credentials can't read is excluded
+ # for the same reason: a webhook can't deliver rows the connection was denied.
+ denied = {name for name, reason in (permission_errors or {}).items() if reason}
+ webhook_capable = {
+ s.name for s in source_schemas if s.supports_webhooks and s.should_sync_default and s.name not in denied
+ }
if not webhook_capable or source.webhook_template is None:
return None
instance = ExternalDataSource.objects.get(pk=source_id, team_id=self.team_id)
+ # Registration can't succeed on a connection whose grants exclude webhook management, and
+ # one-shot setup has no manual-fallback UI to fall back into: leave the polling defaults.
+ blocked_reason = self._webhook_creation_blocked_reason(source, instance)
+ if blocked_reason is not None:
+ return {"success": False, "webhook_url": None, "error": blocked_reason, "pending_inputs": []}
+
eligible_schemas = list(
ExternalDataSchema.objects.filter(source=instance, team_id=self.team_id, name__in=webhook_capable).exclude(
deleted=True
@@ -4648,6 +4678,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
},
)
+ blocked_reason = self._webhook_creation_blocked_reason(source, instance)
+
hog_function = HogFunction.objects.filter(
team=self.team,
type="warehouse_source_webhook",
@@ -4658,7 +4690,11 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
if not hog_function:
return Response(
status=status.HTTP_200_OK,
- data={"supports_webhooks": True, "exists": False},
+ data={
+ "supports_webhooks": True,
+ "exists": False,
+ "auto_creation_blocked_reason": blocked_reason,
+ },
)
webhook_url = get_webhook_url(hog_function.id)
@@ -4701,9 +4737,22 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
"inputs": webhook_inputs,
"external_status": dataclasses.asdict(external_status) if external_status else None,
"missing_events": missing_events,
+ "auto_creation_blocked_reason": blocked_reason,
},
)
+ def _webhook_creation_blocked_reason(self, source: WebhookSource, instance: ExternalDataSource) -> str | None:
+ """Ask the source whether this connection can never create the provider-side webhook.
+ Best-effort: an unparseable config or a source-side failure leaves the button offered,
+ which is the behavior before the check existed."""
+ if not instance.job_inputs:
+ return None
+ try:
+ return source.webhook_creation_blocked_reason(source.parse_config(instance.job_inputs), self.team_id)
+ except Exception as e:
+ capture_exception(e)
+ return None
+
@action(methods=["POST"], detail=True)
def create_webhook(self, request: Request, *args: Any, **kwargs: Any) -> Response:
instance: ExternalDataSource = self.get_object()
@@ -4723,6 +4772,11 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
data={"message": "This source type does not support webhooks"},
)
+ # A connection known to lack the grant can't be fixed by trying. The hog function is still
+ # minted below so manual setup has a URL to paste; only the doomed provider round-trip (one
+ # call per repository, for GitHub) is skipped.
+ blocked_reason = self._webhook_creation_blocked_reason(source, instance)
+
effective_api_version = source.resolve_api_version(instance.api_version)
try:
config = source.parse_config(instance.job_inputs)
@@ -4764,6 +4818,17 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
data={"message": hog_fn_result.error},
)
+ if blocked_reason is not None:
+ return Response(
+ status=status.HTTP_200_OK,
+ data={
+ "success": False,
+ "webhook_url": hog_fn_result.webhook_url,
+ "error": blocked_reason,
+ "pending_inputs": [],
+ },
+ )
+
result = create_and_register_webhook(
source, config, hog_fn_result, self.team_id, api_version=effective_api_version
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index 07c887918a44..e64cfed52ef7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
@@ -464,6 +464,20 @@ class WebhookSource(_BaseSource[ConfigType], Generic[ConfigType]):
"""
raise NotImplementedError()
+ def webhook_creation_blocked_reason(self, config: ConfigType, team_id: int) -> str | None:
+ """Why this connection can never create the provider-side webhook, or ``None``.
+
+ Some connections are known ahead of time to lack the grant `create_webhook` needs — an
+ OAuth app installation can only hold permissions the app itself requests, so no amount of
+ reconnecting will earn it. Returning a reason lets the UI offer the manual setup steps
+ instead of a button whose only outcome is a permission error.
+
+ ``None`` means "not known to be blocked", not "will succeed": it is the answer for every
+ credential whose grants can't be introspected (API keys, tokens), so a real denial still
+ surfaces from `create_webhook`.
+ """
+ return None
+
def get_desired_webhook_events(self, config: ConfigType, eligible_schema_names: list[str]) -> list[str] | None:
"""Events the webhook should subscribe to. ``None`` when the source has no
provider-side subscription to drift (e.g. Slack); such sources skip reconciliation."""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py
index 7f423dfe08e8..234de902a12f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py
@@ -101,7 +101,9 @@ def build_default_sync_settings(source_schema: SourceSchema) -> dict[str, Any]:
return settings
-def build_default_schemas(source_schemas: list[SourceSchema]) -> list[dict]:
+def build_default_schemas(
+ source_schemas: list[SourceSchema], permission_errors: Mapping[str, str | None] | None = None
+) -> list[dict]:
"""Build a default ``schemas`` payload for one-shot source creation.
Enables every discovered table the source marks as default-on, with each table's sync
@@ -112,10 +114,15 @@ def build_default_schemas(source_schemas: list[SourceSchema]) -> list[dict]:
``should_sync_default=False`` also start disabled: sources use it for tables whose sync
needs grants beyond what source creation validated, and the schema picker already honors
it, so one-shot setup must not force-enable what the picker would leave off.
+
+ ``permission_errors`` maps table name to the reason its credentials can't read it (the same
+ per-table probe the schema picker renders). A table with a reason starts disabled however it
+ is otherwise defaulted: enabling it would queue a sync that can only ever 403.
"""
+ denied = {name for name, reason in (permission_errors or {}).items() if reason}
schemas: list[dict] = []
for source_schema in source_schemas:
- if source_schema.webhook_only or not source_schema.should_sync_default:
+ if source_schema.webhook_only or not source_schema.should_sync_default or source_schema.name in denied:
schemas.append({"name": source_schema.name, "should_sync": False})
continue
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py
index f9fd4ded82d4..00e2c8580373 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py
@@ -119,6 +119,23 @@ class TestBuildDefaultSchemas:
)
assert schemas == [{"name": "teams", "should_sync": False}]
+ @parameterized.expand(
+ [
+ ("denied", "Requires the Issues permission", False),
+ ("reachable", None, True),
+ ("blank_reason_is_not_a_denial", "", True),
+ ]
+ )
+ def test_permission_error_leaves_table_disabled(self, _name: str, reason: str | None, expected_sync: bool) -> None:
+ # One-shot setup used to enable every default-on table regardless of the per-table scope
+ # probe the schema picker already honors, so an OAuth connection missing a grant queued
+ # syncs that could only ever 403.
+ schemas = build_default_schemas(
+ [SourceSchema(name="issues", supports_incremental=False, supports_append=False)],
+ permission_errors={"issues": reason},
+ )
+ assert schemas[0]["should_sync"] is expected_sync
+
def test_incremental_lookback_default_flows_through(self) -> None:
# Sources whose recent rows get restated upstream (e.g. Google Ads stats tables) set a
# default lookback; dropping it here would freeze restated rows at first-imported values.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
index 2d84b98035de..4b9e1bae1ca6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
@@ -50,12 +50,14 @@ GITHUB_BASE_URL = "https://api.github.com"
# source's resolved pin; this constant is only the fallback for callers outside a source instance.
GITHUB_DEFAULT_API_VERSION = "2022-11-28"
-# Managing repo webhooks needs the `admin:repo_hook` scope on a classic token, or the
-# "Repository webhooks: read and write" permission on a fine-grained token. Name both so
-# the error/setup guidance doesn't mislead whichever token type the user connected.
+# Managing repo webhooks needs the `admin:repo_hook` scope on a classic token, the "Repository
+# webhooks: read and write" permission on a fine-grained token, or the same permission on an app
+# installation. Name all three so the guidance doesn't mislead whichever way the user connected —
+# an app installation in particular can't be fixed by editing a token.
_WEBHOOK_PERMISSION_HINT = (
- "the `admin:repo_hook` scope (classic token) or the "
- '"Repository webhooks: read and write" permission (fine-grained token)'
+ "the `admin:repo_hook` scope (classic token), the "
+ '"Repository webhooks: read and write" permission (fine-grained token), '
+ "or repository webhook access on the GitHub app installation"
)
@@ -1573,7 +1575,7 @@ def create_repo_webhook(
return WebhookCreationResult(
success=False,
error=(
- f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT} needed to create a repository webhook. "
+ f"Your GitHub connection lacks {_WEBHOOK_PERMISSION_HINT} needed to create a repository webhook. "
"Add it and reconnect, or set up the webhook manually following the steps below."
),
)
@@ -1603,7 +1605,7 @@ def ensure_repo_webhook(
return WebhookCreationResult(
success=False,
error=(
- f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT} needed to create a repository webhook. "
+ f"Your GitHub connection lacks {_WEBHOOK_PERMISSION_HINT} needed to create a repository webhook. "
"Add it and reconnect, or set up the webhook manually following the steps below."
),
)
@@ -1646,7 +1648,7 @@ def ensure_repo_webhook(
return WebhookCreationResult(
success=False,
error=(
- f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT} needed to update the repository webhook. "
+ f"Your GitHub connection lacks {_WEBHOOK_PERMISSION_HINT} needed to update the repository webhook. "
"Add it and reconnect, or set up the webhook manually following the steps below."
),
)
@@ -1733,7 +1735,7 @@ def delete_repo_webhook(
if error == "permission":
return WebhookDeletionResult(
success=False,
- error=f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT}. Please delete the webhook manually.",
+ error=f"Your GitHub connection lacks {_WEBHOOK_PERMISSION_HINT}. Please delete the webhook manually.",
)
if error is not None:
return WebhookDeletionResult(success=False, error=f"Failed to delete webhook: {error}")
@@ -1757,7 +1759,7 @@ def delete_repo_webhook(
if _is_repo_hook_permission_error(response):
return WebhookDeletionResult(
success=False,
- error=f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT}. Please delete the webhook manually.",
+ error=f"Your GitHub connection lacks {_WEBHOOK_PERMISSION_HINT}. Please delete the webhook manually.",
)
return WebhookDeletionResult(
success=False, error=f"Failed to delete webhook: {response.status_code} {response.text}"
@@ -1768,7 +1770,7 @@ def _webhook_update_permission_result(events: list[str]) -> WebhookSyncResult:
return WebhookSyncResult(
success=False,
error=(
- f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT} needed to update the repository "
+ f"Your GitHub connection lacks {_WEBHOOK_PERMISSION_HINT} needed to update the repository "
f"webhook. Add it and reconnect, or add these events to the webhook manually: {', '.join(events)}."
),
)
@@ -1853,7 +1855,7 @@ def get_repo_webhook_info(
if error == "permission":
return ExternalWebhookInfo(
exists=False,
- error=f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT} needed to read repository webhooks.",
+ error=f"Your GitHub connection lacks {_WEBHOOK_PERMISSION_HINT} needed to read repository webhooks.",
)
if error is not None:
return ExternalWebhookInfo(exists=False, error=f"Failed to check webhook status: {error}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
index a9d23c53dc52..a52517b57b75 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
@@ -220,7 +220,11 @@ class GithubSource(
6. Under **Which events would you like to trigger this webhook?**, choose **Let me select individual events** and tick **Workflow jobs**, **Workflow runs**, **Pull request reviews**, **Deployments**, and **Deployment statuses**
7. Click **Add webhook**
-If automatic creation failed, your token needs webhook permissions — the **admin:repo_hook** scope on a classic token, or **Repository webhooks: read and write** on a fine-grained token. Add it and reconnect, or set the webhook up manually using the steps above.""",
+If automatic creation failed with a permissions error, the fix depends on how you connected:
+
+- **Classic personal access token**: add the **admin:repo_hook** scope, then reconnect the source.
+- **Fine-grained personal access token**: add **Repository webhooks: read and write**, then reconnect the source.
+- **GitHub app**: an installation only holds what the app itself requests, so you cannot add this permission yourself. Use the manual steps above, or reconnect the source with a personal access token.""",
webhookFields=cast(
list[FieldType],
[
@@ -477,6 +481,20 @@ If automatic creation failed, your token needs webhook permissions — the **adm
except Exception:
return None
+ def webhook_creation_blocked_reason(self, config: GithubSourceConfig, team_id: int) -> str | None:
+ # Creating a repo hook needs write on repository_hooks. An installation only ever holds what
+ # the GitHub app requests, so when the persisted permission set says otherwise the button
+ # can only 403 — send the user straight to the manual steps instead. Unknown permissions
+ # (token connections, rows predating persistence) fail open, as everywhere else.
+ held = self._installation_permissions(config, team_id)
+ if held is None or held.get("repository_hooks") == "write":
+ return None
+ return (
+ "This GitHub app installation cannot manage repository webhooks, so PostHog cannot "
+ "create the webhook for you. Set it up manually using the steps below, or reconnect "
+ "the source with a personal access token that has the admin:repo_hook scope."
+ )
+
@staticmethod
def _missing_permission_reason(required_permission: str) -> str:
# Rendered inside SchemaForm's tooltip wrapper ("Source credentials cannot read this
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py
index bc18f69d2f0c..425c1b415656 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py
@@ -244,7 +244,10 @@ class StripeSource(
Once created, copy the **Signing secret** from the webhook details page and add it to your source configuration for signature verification.
-If automatic creation failed due to a permissions error and you're using a restricted API key (not OAuth), your key needs **Write** access on **Webhook endpoints**. You can update this in your [Stripe API keys settings](https://dashboard.stripe.com/apikeys).""",
+If automatic creation failed with a permissions error, the fix depends on how you connected:
+
+- **Restricted API key**: give the key **Write** access on **Webhook endpoints** in your [Stripe API keys settings](https://dashboard.stripe.com/apikeys), then reconnect the source.
+- **OAuth**: disconnect and reconnect your Stripe account, then accept the permissions PostHog asks for. If the error stays, use the manual steps above.""",
webhookFields=cast(
list[FieldType],
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
index 97b8f0bb7ba6..2d0f4eff53ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
@@ -1,4 +1,5 @@
import functools
+from pathlib import Path
from types import SimpleNamespace
from typing import Any, cast
@@ -6,6 +7,8 @@ import pytest
from unittest import mock
from unittest.mock import MagicMock, patch
+from django.conf import settings
+
import orjson
import stripe as stripe_lib
from parameterized import parameterized
@@ -69,7 +72,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.set
NON_PARTITIONED_ENDPOINTS,
WEBHOOK_ONLY_ENDPOINTS,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import PERMISSIONS, StripeSource
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe import (
DEFAULT_LIMIT,
SUBSCRIPTION_PAGE_LIMIT,
@@ -1395,3 +1398,20 @@ class TestCreateWebhookPermissionErrorCopy:
assert result.success is False
assert expected_phrase in (result.error or "")
+
+
+class TestStripeAppManifestCoversSourcePermissions:
+ # Regression test: PERMISSIONS drives the pre-filled restricted-key form, while the Stripe app
+ # manifest drives what an OAuth connection is granted. The two drifted twice (rak_webhook_write
+ # in April, rak_coupon_read in July), each time leaving OAuth users unable to create a webhook
+ # or import coupons while the key path worked. The manifest is the checked-in source of truth
+ # for the OAuth grant, so it must cover every scope the source asks a key for.
+ def test_every_source_permission_is_requested_by_the_app(self):
+ manifest_path = Path(settings.BASE_DIR) / "services" / "stripe-app" / "stripe-app.json"
+ granted = {entry["permission"] for entry in orjson.loads(manifest_path.read_bytes())["permissions"]}
+
+ # A restricted-key scope is the app permission name with a `rak_` prefix.
+ required = {permission.removeprefix("rak_") for permission in PERMISSIONS}
+
+ assert required, "PERMISSIONS is empty, so this assertion would pass vacuously"
+ assert required - granted == set()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py
index fa0eae45d7ac..9ad8f1cc2832 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py
@@ -1425,6 +1425,33 @@ def _pat_config() -> GithubSourceConfig:
)
+class TestGithubWebhookCreationBlocked:
+ # An app installation only ever holds what the GitHub app itself requests, so an installation
+ # without repository_hooks write can never create a repo webhook. Offering the button anyway
+ # sent users through a 403 whose suggested fix (edit your token scopes) they couldn't apply.
+ @parameterized.expand(
+ [
+ ("write_permission_allows_creation", {"repository_hooks": "write", "contents": "read"}, False),
+ ("read_permission_blocks_creation", {"repository_hooks": "read"}, True),
+ ("absent_permission_blocks_creation", {"contents": "read"}, True),
+ # Unknown grants (token connections, rows predating persistence) fail open: the create
+ # attempt is the only way to find out, and a real denial still surfaces from GitHub.
+ ("unknown_permissions_fail_open", None, False),
+ ]
+ )
+ def test_blocked_reason_tracks_installation_permissions(
+ self, _name: str, held: dict[str, str] | None, expect_blocked: bool
+ ) -> None:
+ source = GithubSource()
+ config = _pat_config()
+ with mock.patch.object(GithubSource, "_installation_permissions", return_value=held):
+ reason = source.webhook_creation_blocked_reason(config, team_id=1)
+
+ assert (reason is not None) is expect_blocked
+ if expect_blocked:
+ assert "cannot manage repository webhooks" in (reason or "")
+
+
class TestGithubWebhookSource:
"""The WebhookSource surface: event mapping, schema flags, and the create/
delete/info round-trips that mint and reconcile the repo webhook."""
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 3b25b50c7d46..53fe871d1f50 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -11513,6 +11513,51 @@ class TestExternalDataSourceSetup(APIBaseTest):
customer = schemas.get(name=STRIPE_CUSTOMER_RESOURCE_NAME)
assert customer.sync_type in ("incremental", "append", "full_refresh")
+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.ensure_person_join")
+ @patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_setup_leaves_unreadable_tables_disabled(self, _mock_validate, _mock_sync_views, _mock_person_join):
+ # One-shot setup used to enable every default-on table regardless of the per-table scope
+ # probe, so an OAuth connection whose grant excludes a resource queued a sync that could
+ # only ever 403. The picker already honored the probe; setup did not.
+ denied = {STRIPE_CUSTOMER_RESOURCE_NAME: "Requires the customer_read permission"}
+ with patch.object(
+ StripeSource,
+ "get_endpoint_permissions",
+ side_effect=lambda config, team_id, endpoints, **kwargs: {name: denied.get(name) for name in endpoints},
+ ):
+ response = self._setup_stripe()
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ schemas = ExternalDataSchema.objects.filter(source_id=response.json()["id"])
+ assert schemas.get(name=STRIPE_CUSTOMER_RESOURCE_NAME).should_sync is False
+ # Every other readable table still gets the normal polling default.
+ assert schemas.filter(should_sync=True).exists()
+
+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.ensure_person_join")
+ @patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_setup_ignores_a_probe_that_denies_every_table(self, _mock_validate, _mock_sync_views, _mock_person_join):
+ # Stripe reports a probe it couldn't run as a per-table reason rather than raising, so an
+ # unreachable provider marks everything denied. Setup has no UI to show that, and honoring
+ # it would silently create a source with nothing enabled.
+ with patch.object(
+ StripeSource,
+ "get_endpoint_permissions",
+ side_effect=lambda config, team_id, endpoints, **kwargs: dict.fromkeys(endpoints, "Connection error"),
+ ):
+ response = self._setup_stripe()
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ schemas = ExternalDataSchema.objects.filter(source_id=response.json()["id"])
+ assert schemas.filter(should_sync=True).exists()
+
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
return_value=(False, "Missing Stripe API key"),