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): validate nested Stripe resources via parent endpoint (#57215)

Daniel RC61a6e00ba242
diff --git a/posthog/temporal/data_imports/sources/stripe/source.py b/posthog/temporal/data_imports/sources/stripe/source.py
index b46cba41b5fa..b62c81aba6b3 100644
--- a/posthog/temporal/data_imports/sources/stripe/source.py
+++ b/posthog/temporal/data_imports/sources/stripe/source.py
@@ -109,7 +109,7 @@ class StripeSource(
name=SchemaExternalDataSourceType.STRIPE,
caption=f"Connect your Stripe account to automatically sync your Stripe data into PostHog. You can choose between OAuth (recommended) or legacy RAK Stripe keys. If you choose the latter, you will need your [Stripe account ID]({STRIPE_ACCOUNT_URL}), and create a [restricted API key]({STRIPE_API_KEYS_URL})",
permissionsCaption="""Currently, **read permissions are required** for the following resources:
- - Under the **Core** resource type, select *read* for **Balance transaction sources**, **Charges**, **Customers**, **Disputes**, **Payouts**, and **Products**
+ - Under the **Core** resource type, select *read* for **Balance transaction sources**, **Charges**, **Customers**, **Disputes**, **Payment methods**, **Payouts**, and **Products**
- Under the **Billing** resource type, select *read* for **Credit notes**, **Invoices**, **Prices**, and **Subscriptions**
- Under the **Connect** resource type, select *read* for the **entire resource**
- Under the **Webhooks** resource type, select *write* for **Webhook endpoints** (required for automatic webhook creation)
@@ -226,7 +226,12 @@ If automatic creation failed due to a permissions error and you're using a restr
"403 Client Error: Forbidden for url: https://api.stripe.com": "Your Stripe credentials do not have permissions to access endpoint. Please check your configuration and permissions in Stripe, then try again.",
"Expired API Key provided": "Your Stripe API key has expired. Please create a new key and reconnect.",
"Invalid API Key provided": None,
- "PermissionError": "Your Stripe credentials do not have permissions to access endpoint. Please check your configuration and permissions in Stripe, then try again.",
+ # Surface Stripe's raw permission message — it names the specific scope that's missing
+ # (e.g. "Having the 'rak_payment_method_read' permission would allow this request to
+ # continue"), which is more actionable than a generic "check your permissions" toast.
+ # `_clean_stripe_error_message` collapses the redacted-key asterisk run before the
+ # message reaches this layer, so it stays toast-sized.
+ "PermissionError": None,
# Deterministic credential/config errors from _get_api_key and OAuthMixin
"Missing Stripe API key": "Stripe API key is not configured. Please update the source configuration.",
"Missing Stripe integration ID": "Stripe integration ID is not configured. Please reconnect your Stripe account.",
diff --git a/posthog/temporal/data_imports/sources/stripe/stripe.py b/posthog/temporal/data_imports/sources/stripe/stripe.py
index 741c330f78a3..046c2a34c3c6 100644
--- a/posthog/temporal/data_imports/sources/stripe/stripe.py
+++ b/posthog/temporal/data_imports/sources/stripe/stripe.py
@@ -1,7 +1,8 @@
import os
+import re
import dataclasses
from collections.abc import Callable
-from typing import Any, Optional, Union, get_args, get_type_hints
+from typing import Any, Optional, Union, cast, get_args, get_type_hints
import orjson
import stripe as stripe_lib
@@ -57,6 +58,29 @@ def _tracked_stripe_http_client() -> RequestsClient:
return RequestsClient(session=make_tracked_session())
+def _clean_stripe_error_message(msg: str) -> str:
+ """Collapse the long redacted middle of a restricted API key ('rk_live_********...****gbeftZ')
+ so the error message stays short enough to render in a frontend toast. The prefix and
+ suffix Stripe leaves visible are enough to identify the key in support escalations."""
+ # Stripe redacts ~80 chars with `*`. Anything 5+ in a row is the redaction, never legitimate.
+ return re.sub(r"\*{5,}", "***", msg)
+
+
+def _call_stripe(method: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
+ """Invoke a Stripe SDK list method and rewrite any StripeError it raises with a cleaned
+ message — primarily collapsing the long asterisk run from redacted restricted keys.
+
+ Re-raises the same exception class (so framework-level non-retryable error matching on
+ `"PermissionError"` etc. continues to work) but with a shorter, frontend-friendly message
+ that still preserves the actionable detail Stripe surfaces (which scope is missing).
+ """
+ try:
+ return method(*args, **kwargs)
+ except stripe_lib.StripeError as e:
+ cleaned = _clean_stripe_error_message(str(e))
+ raise type(e)(message=cleaned) from e
+
+
def _stripe_base_addresses() -> BaseAddresses:
# Redirect Stripe API calls to a local mock (e.g. STRIPE_API_BASE=http://localhost:12111)
# when running the stripe-mock dev service. No-op in production where the var is unset.
@@ -76,6 +100,7 @@ class StripeNestedResource:
nested_parent_param: str
parent_id: str
parent: StripeResource
+ parent_name: str = ""
params: dict[str, Any] = dataclasses.field(default_factory=dict)
@@ -84,26 +109,19 @@ class StripeResumeConfig:
starting_after: str
-def get_rows(
- api_key: str,
- endpoint: str,
- account_id: Optional[str],
- db_incremental_field_last_value: Optional[Any],
- db_incremental_field_earliest_value: Optional[Any],
- logger: FilteringBoundLogger,
- resumable_source_manager: ResumableSourceManager[StripeResumeConfig],
- should_use_incremental_field: bool = False,
-):
- client = StripeClient(
- api_key,
- stripe_account=account_id,
- stripe_version="2024-09-30.acacia",
- max_network_retries=2,
- base_addresses=_stripe_base_addresses(),
- http_client=_tracked_stripe_http_client(),
- )
- default_params = {"limit": DEFAULT_LIMIT}
- resources: dict[str, Union[StripeResource, StripeNestedResource]] = {
+def _build_resources(
+ client: StripeClient, logger: Optional[FilteringBoundLogger] = None
+) -> dict[str, Union[StripeResource, StripeNestedResource]]:
+ """Single source of truth for the resources we sync from Stripe and how they relate.
+
+ Used by both get_rows (for the actual sync) and validate_credentials (for permission
+ checks). Nested resources carry their parent on `.parent`, so callers can derive the
+ nested→parent linkage without restating it elsewhere.
+
+ `logger` is only consumed by InvoiceListWithAllLines; pass None when the caller doesn't
+ need the wrapped invoice expansion (e.g. validation, which just probes the list endpoint).
+ """
+ return {
ACCOUNT_RESOURCE_NAME: StripeResource(method=client.accounts.list),
BALANCE_TRANSACTION_RESOURCE_NAME: StripeResource(method=client.balance_transactions.list),
CHARGE_RESOURCE_NAME: StripeResource(method=client.charges.list),
@@ -111,7 +129,11 @@ def get_rows(
DISPUTE_RESOURCE_NAME: StripeResource(method=client.disputes.list),
INVOICE_ITEM_RESOURCE_NAME: StripeResource(method=client.invoice_items.list),
INVOICE_RESOURCE_NAME: StripeResource(
- method=lambda params: InvoiceListWithAllLines(client, params, logger) # type: ignore
+ method=(
+ (lambda params: InvoiceListWithAllLines(client, params, logger)) # type: ignore
+ if logger is not None
+ else client.invoices.list
+ )
),
PAYOUT_RESOURCE_NAME: StripeResource(method=client.payouts.list),
PRICE_RESOURCE_NAME: StripeResource(method=client.prices.list, params={"expand[]": "data.tiers"}),
@@ -124,15 +146,39 @@ def get_rows(
nested_parent_param="customer",
parent_id="id",
parent=StripeResource(method=client.customers.list),
+ parent_name=CUSTOMER_RESOURCE_NAME,
),
CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME: StripeNestedResource(
method=client.customers.payment_methods.list,
nested_parent_param="customer",
parent_id="id",
parent=StripeResource(method=client.customers.list),
+ parent_name=CUSTOMER_RESOURCE_NAME,
),
}
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ account_id: Optional[str],
+ db_incremental_field_last_value: Optional[Any],
+ db_incremental_field_earliest_value: Optional[Any],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[StripeResumeConfig],
+ should_use_incremental_field: bool = False,
+):
+ client = StripeClient(
+ api_key,
+ stripe_account=account_id,
+ stripe_version="2024-09-30.acacia",
+ max_network_retries=2,
+ base_addresses=_stripe_base_addresses(),
+ http_client=_tracked_stripe_http_client(),
+ )
+ default_params = {"limit": DEFAULT_LIMIT}
+ resources = _build_resources(client, logger=logger)
+
batcher = Batcher(logger=logger)
resource = resources.get(endpoint, None)
@@ -159,11 +205,13 @@ def get_rows(
logger.debug(f"Stripe: resuming from object id: {resume_config.starting_after}")
if isinstance(resource, StripeNestedResource):
- stripe_parent_objects = resource.parent.method(
- params={**default_params, **resource.parent.params, **resume_params}
+ stripe_parent_objects = _call_stripe(
+ resource.parent.method,
+ params={**default_params, **resource.parent.params, **resume_params},
)
for obj in stripe_parent_objects.auto_paging_iter():
- stripe_nested_objects = resource.method(
+ stripe_nested_objects = _call_stripe(
+ resource.method,
**{resource.nested_parent_param: obj[resource.parent_id]},
params={**default_params, **resource.params},
)
@@ -182,7 +230,9 @@ def get_rows(
last_cur = py_table.column(resource.nested_parent_param)[-1].as_py()
resumable_source_manager.save_state(StripeResumeConfig(starting_after=last_cur))
else:
- stripe_objects = resource.method(params={**default_params, **resource.params, **resume_params})
+ stripe_objects = _call_stripe(
+ resource.method, params={**default_params, **resource.params, **resume_params}
+ )
for obj in stripe_objects.auto_paging_iter():
batcher.batch(obj)
@@ -212,12 +262,13 @@ def get_rows(
f"Stripe: iterating earliest objects from resource: created[lt] = {db_incremental_field_earliest_value}"
)
- stripe_objects = resource.method(
+ stripe_objects = _call_stripe(
+ resource.method,
params={
**default_params,
**resource.params,
f"created[lt]": db_incremental_field_earliest_value,
- }
+ },
)
yield from stripe_objects.auto_paging_iter()
@@ -225,12 +276,13 @@ def get_rows(
if db_incremental_field_last_value is not None:
logger.debug(f"Stripe: iterating latest objects from resource: created[gt] = {db_incremental_field_last_value}")
- stripe_objects = resource.method(
+ stripe_objects = _call_stripe(
+ resource.method,
params={
**default_params,
**resource.params,
f"created[gt]": db_incremental_field_last_value,
- }
+ },
)
for obj in stripe_objects.auto_paging_iter():
if obj[incremental_field_name] <= db_incremental_field_last_value:
@@ -356,50 +408,63 @@ def validate_credentials(api_key: str, table_name: Optional[str] = None) -> bool
"""
client = StripeClient(api_key, base_addresses=_stripe_base_addresses(), http_client=_tracked_stripe_http_client())
- # Test access to all resources we're pulling
- resources_to_check = [
- {"name": ACCOUNT_RESOURCE_NAME, "method": client.accounts.list, "params": {"limit": 1}},
- {"name": BALANCE_TRANSACTION_RESOURCE_NAME, "method": client.balance_transactions.list, "params": {"limit": 1}},
- {"name": CHARGE_RESOURCE_NAME, "method": client.charges.list, "params": {"limit": 1}},
- {"name": CUSTOMER_RESOURCE_NAME, "method": client.customers.list, "params": {"limit": 1}},
- {"name": DISPUTE_RESOURCE_NAME, "method": client.disputes.list, "params": {"limit": 1}},
- {"name": INVOICE_ITEM_RESOURCE_NAME, "method": client.invoice_items.list, "params": {"limit": 1}},
- {"name": INVOICE_RESOURCE_NAME, "method": client.invoices.list, "params": {"limit": 1}},
- {"name": PAYOUT_RESOURCE_NAME, "method": client.payouts.list, "params": {"limit": 1}},
- {"name": PRICE_RESOURCE_NAME, "method": client.prices.list, "params": {"limit": 1}},
- {"name": PRODUCT_RESOURCE_NAME, "method": client.products.list, "params": {"limit": 1}},
- {"name": SUBSCRIPTION_RESOURCE_NAME, "method": client.subscriptions.list, "params": {"limit": 1}},
- {"name": REFUND_RESOURCE_NAME, "method": client.refunds.list, "params": {"limit": 1}},
- {"name": CREDIT_NOTE_RESOURCE_NAME, "method": client.credit_notes.list, "params": {"limit": 1}},
- ]
+ # 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
missing_permissions: dict[str, str] = {}
errors: dict[str, str] = {}
- if table_name:
- resources_to_check = [r for r in resources_to_check if r.get("name") == table_name]
-
- if table_name and len(resources_to_check) == 0:
+ if table_name is not None and table_name not in all_resources:
raise StripePermissionError({table_name: f"{table_name} does not exist"})
- for resource in resources_to_check:
- resource_name = str(resource["name"])
+ 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)
+ ]
+
+ for display_name, resource in resources_to_check:
try:
- resource["method"](params=resource["params"]) # type: ignore
+ # 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(str(e)) from e
+ 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.
- missing_permissions[resource_name] = getattr(e, "user_message", None) or str(e)
+ 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[resource_name] = str(e)
+ 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
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 79855c17e6fc..88ee08ff1488 100644
--- a/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py
+++ b/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py
@@ -9,13 +9,21 @@ import stripe as stripe_lib
from posthog.models.integration import Integration
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from posthog.temporal.data_imports.sources.generated_configs import StripeSourceConfig
-from posthog.temporal.data_imports.sources.stripe.constants import ACCOUNT_RESOURCE_NAME
+from posthog.temporal.data_imports.sources.stripe.constants import (
+ ACCOUNT_RESOURCE_NAME,
+ CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,
+ CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,
+)
from posthog.temporal.data_imports.sources.stripe.source import StripeSource
from posthog.temporal.data_imports.sources.stripe.stripe import (
StripeAuthenticationError,
+ StripeNestedResource,
StripePermissionError,
+ StripeResource,
StripeResumeConfig,
StripeValidationError,
+ _build_resources,
+ _clean_stripe_error_message,
validate_credentials,
)
from posthog.temporal.tests.data_imports.conftest import run_external_data_job_workflow
@@ -403,6 +411,100 @@ def test_validate_credentials_mixed_403_and_unknown_raises_validation_error_with
assert list(e.value.missing_permissions.keys()) == ["Subscription"]
+ "nested_table_name",
+ [CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME, CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME],
+)
+def test_validate_credentials_nested_resource_validates_via_parent(nested_table_name):
+ """Nested resources can't be listed without a parent customer ID. Validating them
+ must proxy to the Customer endpoint instead of raising a fake "<resource> does not exist"
+ error — which used to surface as "Stripe credentials lack permissions for CustomerPaymentMethod"
+ every time the user toggled the sync method on a nested table."""
+ mock_client = mock.MagicMock()
+ 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)
+
+ assert result is True
+ # The parent's list endpoint is the one we actually call.
+ mock_client.customers.list.assert_called_once_with(params={"limit": 1})
+
+
+ "nested_table_name",
+ [CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME, CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME],
+)
+def test_validate_credentials_nested_resource_surfaces_parent_permission_error(nested_table_name):
+ """If the parent (Customer) scope is missing, the error must name both the nested table
+ the user toggled and the parent that actually gates the permission — `Nested (Parent)` —
+ so the message is unambiguous about which Stripe scope to grant."""
+ mock_client = mock.MagicMock()
+ 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),
+ pytest.raises(StripePermissionError) as e,
+ ):
+ validate_credentials("api_key", nested_table_name)
+
+ assert list(e.value.missing_permissions.keys()) == [f"{nested_table_name} (Customer)"]
+
+
+def test_clean_stripe_error_message_collapses_redacted_key():
+ """Stripe's permission errors quote the restricted key with ~80 redacted middle chars
+ (`rk_live_***********...***********gbeftZ`). The unedited message is too long for a
+ toast — collapse the asterisk run while keeping the visible prefix/suffix that lets
+ users identify which key was used."""
+ raw = (
+ "Request req_DzMMiyPa4cynLi: The provided key 'rk_live_"
+ + ("*" * 80)
+ + "gbeftZ' does not have the required permissions for this endpoint on account "
+ + "'acct_1HIMDDEuIatRXSdz'. Having the 'rak_payment_method_read' permission would "
+ + "allow this request to continue."
+ )
+
+ cleaned = _clean_stripe_error_message(raw)
+
+ assert "*" * 80 not in cleaned
+ assert "***" in cleaned # we keep a short marker
+ assert "rk_live_***gbeftZ" in cleaned
+ # Critically, the actionable detail must survive the cleanup.
+ assert "rak_payment_method_read" in cleaned
+
+
+def test_clean_stripe_error_message_passthrough_when_no_redaction():
+ """No redacted run in the message → return unchanged."""
+ msg = "Request req_xxx: Some non-permission error without redaction."
+ assert _clean_stripe_error_message(msg) == msg
+
+
+def test_validate_credentials_nested_resources_have_registered_parents():
+ """Invariant: every StripeNestedResource's `parent_name` must point at a key that is
+ also registered as a top-level StripeResource in _build_resources. validate_credentials
+ does a direct dict lookup on parent_name, so a miss would crash rather than render a
+ useful error. Catch the misconfiguration here in CI rather than at runtime.
+
+ Important: this test does NOT compare method identity. Stripe's SDK exposes endpoints
+ via property descriptors that return a fresh bound method on every attribute access
+ (`id(client.customers.list) == id(client.customers.list)` is False). MagicMock caches
+ attribute access and made identity checks falsely pass — so the linkage is carried
+ explicitly via the `parent_name` string instead.
+ """
+ mock_client = mock.MagicMock()
+ resources = _build_resources(mock_client, logger=None)
+
+ for name, resource in resources.items():
+ if isinstance(resource, StripeNestedResource):
+ assert resource.parent_name, f"Nested resource {name!r} must declare a parent_name."
+ parent_entry = resources.get(resource.parent_name)
+ assert isinstance(parent_entry, StripeResource), (
+ f"Nested resource {name!r} declares parent_name={resource.parent_name!r}, but no "
+ f"top-level StripeResource with that name is registered in _build_resources. "
+ f"validate_credentials would crash trying to resolve it."
+ )
+
+
def test_validate_credentials_with_missing_table_name():
mock_client = mock.MagicMock()