:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse-sources): keep the latest Stripe webhook event on a tie (#98651)
Daniel RC2f508756e549
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.pyindex 56391ee0ecdd..82a7c440b1f7 100644--- a/products/data_warehouse/backend/facade/api.py+++ b/products/data_warehouse/backend/facade/api.py@@ -49,6 +49,7 @@ _LAZY = {"get_or_create_webhook_hog_function": "logic.external_data_source.webhooks","get_webhook_url": "logic.external_data_source.webhooks","reconcile_webhook_events": "logic.external_data_source.webhooks",+ "store_webhook_extra_inputs": "logic.external_data_source.webhooks","WebhookConsumerConfig": "logic.webhook_consumer.config","WebhookS3Sink": "logic.webhook_consumer.consumer","get_managed_warehouse_data_status": "logic.managed_warehouse_data_status",diff --git a/products/data_warehouse/backend/logic/external_data_source/webhooks.py b/products/data_warehouse/backend/logic/external_data_source/webhooks.pyindex 6396221c0563..308a39c556d9 100644--- a/products/data_warehouse/backend/logic/external_data_source/webhooks.py+++ b/products/data_warehouse/backend/logic/external_data_source/webhooks.py@@ -127,6 +127,20 @@ def get_or_create_webhook_hog_function()+def store_webhook_extra_inputs(hog_function_id: str, team_id: int, extra_inputs: dict[str, Any]) -> None:+ """Write provider-returned webhook inputs (the signing secret) onto the receiving HogFunction.++ The values a provider hands back on create are unrecoverable, so every caller has to persist+ them the same way. `save` re-splits the secret inputs into `encrypted_inputs`.+ """+ hog_function = HogFunction.objects.get(id=hog_function_id, team_id=team_id)+ hog_function.inputs = {+ **(hog_function.inputs or {}),+ **{key: {"value": value} for key, value in extra_inputs.items()},+ }+ hog_function.save(update_fields=["inputs", "encrypted_inputs"])++def create_and_register_webhook(source: WebhookSource,config: Config,@@ -142,13 +156,7 @@ def create_and_register_webhook()if result.success and result.extra_inputs:- hog_function = HogFunction.objects.get(id=hog_fn_result.hog_function_id, team_id=team_id)- assert hog_function.inputs is not None- hog_function.inputs = {- **hog_function.inputs,- **{key: {"value": value} for key, value in result.extra_inputs.items()},- }- hog_function.save(update_fields=["inputs", "encrypted_inputs"])+ store_webhook_extra_inputs(hog_fn_result.hog_function_id, team_id, result.extra_inputs)return WebhookSetupResult(success=result.success,diff --git a/products/warehouse_sources/backend/management/commands/repin_stripe_webhook_api_version.py b/products/warehouse_sources/backend/management/commands/repin_stripe_webhook_api_version.pynew file mode 100644index 000000000000..8f4613c78e03--- /dev/null+++ b/products/warehouse_sources/backend/management/commands/repin_stripe_webhook_api_version.py@@ -0,0 +1,243 @@+from typing import Any, cast++from django.core.management.base import BaseCommand, CommandError, CommandParser++import structlog++from posthog.dataclasses import frozen++from products.cdp.backend.facade.models import HogFunction+from products.data_warehouse.backend.facade.api import get_webhook_url, store_webhook_extra_inputs+from products.warehouse_sources.backend.facade.source_management import SourceRegistry+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.stripe import StripeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSource+from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe import WebhookRepin+from products.warehouse_sources.backend.types import ExternalDataSourceType++logger = structlog.get_logger(__name__)+++@frozen+class _RepinCandidate:+ source_model: ExternalDataSource+ hog_function: HogFunction+ config: StripeSourceConfig+ webhook_url: str+ current_api_version: str | None+ target_api_version: str+++class Command(BaseCommand):+ help = (+ "Pin the Stripe API version on webhook endpoints that were created without one. An unpinned "+ "endpoint delivers at the Stripe account's default version, so its payloads can carry a "+ "different shape from the version the source reads, and the fields that moved between "+ "versions land as NULL. Stripe accepts api_version on create only, so each endpoint is "+ "replaced: the command creates a pinned endpoint on the same URL, stores its signing secret, "+ "then deletes the old endpoint. Both endpoints receive every event while both exist, and one "+ "copy always verifies against the stored secret, so no event is lost."+ )++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument(+ "--live-run",+ action="store_true",+ help="Actually replace the endpoints. Without this flag the command only reports (dry-run).",+ )+ parser.add_argument(+ "--team-id",+ type=int,+ default=None,+ help="Only consider sources belonging to this team",+ )+ parser.add_argument(+ "--source-id",+ action="append",+ default=None,+ help="Target these source ids explicitly. Repeatable.",+ )+ parser.add_argument(+ "--limit",+ type=int,+ default=None,+ help=(+ "Only scan the first N Stripe sources. Each one costs a Stripe API call even in a "+ "dry run, so use this for a first batch."+ ),+ )++ def handle(self, *args: Any, **options: Any) -> None:+ live_run = options["live_run"]+ source = cast(StripeSource, SourceRegistry.get_source(ExternalDataSourceType.STRIPE))++ if options["limit"] is not None and options["limit"] < 1:+ raise CommandError("--limit must be at least 1.")++ candidates = self._find_candidates(+ source, team_id=options["team_id"], source_ids=options["source_id"], limit=options["limit"]+ )++ if not candidates:+ self.stdout.write(self.style.WARNING("No Stripe webhook endpoint needs repinning."))+ return++ self.stdout.write(f"Found {len(candidates)} Stripe webhook endpoint(s) on the wrong API version:\n")+ for candidate in candidates:+ self.stdout.write(+ f" source={candidate.source_model.id} team={candidate.source_model.team_id} "+ f"endpoint_version={candidate.current_api_version or 'unpinned'} "+ f"target={candidate.target_api_version}"+ )++ if not live_run:+ self.stdout.write(+ self.style.WARNING(+ f"\nDry run: {len(candidates)} endpoint(s) would be replaced. Pass --live-run to execute."+ )+ )+ return++ self._replace(source, candidates)++ def _find_candidates(+ self, source: StripeSource, *, team_id: int | None, source_ids: list[str] | None, limit: int | None+ ) -> list[_RepinCandidate]:+ sources = ExternalDataSource.objects.filter(+ source_type=ExternalDataSourceType.STRIPE,+ deleted=False,+ ).order_by("created_at")++ if team_id is not None:+ sources = sources.filter(team_id=team_id)+ if source_ids:+ sources = sources.filter(id__in=source_ids)+ if limit is not None:+ sources = sources[:limit]++ candidates: list[_RepinCandidate] = []++ for source_model in sources:+ hog_function = HogFunction.objects.filter(+ team_id=source_model.team_id,+ type="warehouse_source_webhook",+ inputs__source_id__value=str(source_model.id),+ deleted=False,+ ).first()+ if hog_function is None or not source_model.job_inputs:+ continue++ webhook_url = get_webhook_url(str(hog_function.id))+ target_api_version = source.resolve_api_version(source_model.api_version)++ try:+ config = source.parse_config(source_model.job_inputs)+ info = source.get_external_webhook_info(config, webhook_url, source_model.team_id)+ except Exception as e:+ self.stdout.write(+ self.style.WARNING(f"Skipped source={source_model.id}: could not read the endpoint ({e})")+ )+ continue++ if not info.exists or info.api_version == target_api_version:+ continue++ # The Stripe app is structurally denied `webhook_write`, so the replacement create can+ # only 403 for an app-connected source. Report it as needing a manual fix in Stripe+ # rather than queueing a candidate that fails on every run.+ if config.auth_method.selection == "oauth":+ self.stdout.write(+ self.style.WARNING(+ f"Manual fix needed for source={source_model.id} team={source_model.team_id}: "+ f"an app-connected source cannot create a webhook endpoint. Recreate it in Stripe "+ f"on {info.api_version or 'no version'} → {target_api_version}."+ )+ )+ continue++ candidates.append(+ _RepinCandidate(+ source_model=source_model,+ hog_function=hog_function,+ config=config,+ webhook_url=webhook_url,+ current_api_version=info.api_version,+ target_api_version=target_api_version,+ )+ )++ return candidates++ def _replace(self, source: StripeSource, candidates: list[_RepinCandidate]) -> None:+ replaced = 0+ failed = 0+ orphaned = 0++ for candidate in candidates:+ source_model = candidate.source_model+ repin = source.create_pinned_webhook_replacement(+ candidate.config,+ candidate.webhook_url,+ source_model.team_id,+ api_version=source_model.api_version,+ )++ if repin.status != "replaced" or not repin.signing_secret or not repin.replaced_endpoint_id:+ failed += 1+ reason = repin.error or f"the endpoint is now {repin.status}"+ self.stdout.write(self.style.ERROR(f"Failed source={source_model.id}: {reason}"))+ self._report_stray_endpoint(source_model, repin)+ continue++ try:+ # Store the secret before the delete. Until this write lands only the old endpoint's+ # deliveries verify, and after it lands only the new endpoint's do, so every event+ # has one copy that verifies as long as both endpoints exist.+ store_webhook_extra_inputs(+ str(candidate.hog_function.id),+ source_model.team_id,+ {"signing_secret": repin.signing_secret},+ )+ except Exception as e:+ # The replacement is live in Stripe and its secret is stored nowhere, so name it+ # here rather than letting the traceback end the run with the id only in Stripe.+ failed += 1+ self.stdout.write(self.style.ERROR(f"Failed source={source_model.id}: {e}"))+ self._report_stray_endpoint(source_model, repin)+ continue++ deletion = source.delete_webhook_endpoint(+ candidate.config, repin.replaced_endpoint_id, source_model.team_id+ )+ if not deletion.success:+ orphaned += 1+ self.stdout.write(+ self.style.WARNING(+ f"Replaced source={source_model.id} but could not delete the old endpoint "+ f"{repin.replaced_endpoint_id}: {deletion.error}. Delete it in Stripe, because "+ f"its deliveries now fail the signature check."+ )+ )++ replaced += 1+ logger.info(+ "Repinned Stripe webhook endpoint",+ source_id=str(source_model.id),+ team_id=source_model.team_id,+ previous_api_version=repin.previous_api_version,+ api_version=candidate.target_api_version,+ )++ self.stdout.write(+ self.style.SUCCESS(f"\nDone. Replaced: {replaced}, Failed: {failed}, Old endpoint left behind: {orphaned}")+ )++ def _report_stray_endpoint(self, source_model: ExternalDataSource, repin: WebhookRepin) -> None:+ if not repin.created_endpoint_id:+ return+ self.stdout.write(+ self.style.WARNING(+ f" Stripe endpoint {repin.created_endpoint_id} exists for source={source_model.id} "+ f"and nothing holds its signing secret. Delete it in Stripe."+ )+ )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.pyindex be06c1dd352e..b29e1a6a62bc 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@@ -6,6 +6,8 @@ from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar, Union, castimport structlog+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerif TYPE_CHECKING:@@ -504,7 +506,7 @@ class WebhookDeletionResult:error: str | None = None+@frozenclass ExternalWebhookInfo:"""Info about an external webhook on the source (e.g. Stripe webhook endpoint)."""@@ -514,6 +516,11 @@ class ExternalWebhookInfo:status: str | None = Nonedescription: str | None = Nonecreated_at: str | None = None+ # The vendor API version the endpoint delivers at, for the providers that pin one per+ # endpoint. None means the provider has no such concept or the endpoint carries no pin, in+ # which case the provider renders payloads at the account default and the shape can drift+ # away from the version this source reads.+ api_version: str | None = Noneerror: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.pyindex 99e6ddbf23d1..573be2844dd8 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@@ -64,10 +64,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.strStripeResumeConfig,StripeTransientError,StripeValidationError,+ WebhookRepin,_all_known_webhook_events,check_endpoint_permissions as check_stripe_endpoint_permissions,+ create_pinned_webhook_replacement,create_webhook,delete_webhook,+ delete_webhook_endpoint,get_external_webhook_info,stripe_source,update_webhook_events,@@ -539,6 +542,26 @@ If automatic creation failed with a permissions error, the fix depends on how yoapi_key = self._get_api_key(config, team_id)return delete_webhook(api_key, config.stripe_account_id, webhook_url)+ def create_pinned_webhook_replacement(+ self, config: StripeSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookRepin:+ """Step one of moving an unpinned endpoint onto this source's API version.+ The caller must store the returned signing secret before it calls+ `delete_webhook_endpoint` for the replaced endpoint."""+ api_key = self._get_api_key(config, team_id)+ return create_pinned_webhook_replacement(+ api_key,+ config.stripe_account_id,+ webhook_url,+ api_version=self.resolve_api_version(api_version),+ )++ def delete_webhook_endpoint(+ self, config: StripeSourceConfig, endpoint_id: str, team_id: int+ ) -> WebhookDeletionResult:+ api_key = self._get_api_key(config, team_id)+ return delete_webhook_endpoint(api_key, config.stripe_account_id, endpoint_id)+def source_for_pipeline(self,config: StripeSourceConfig,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.pyindex b881d34b4b03..7e862f683a84 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py@@ -1110,7 +1110,11 @@ def _webhook_table_transformer(table: pa.Table) -> pa.Table:ts = event_created if isinstance(event_created, int) else 0existing = best_by_id.get(obj_id)- if existing is None or ts > existing[0]:+ # Later rows win ties. `created` is a whole second and one Stripe operation emits several+ # events for an object inside it, so the only finer order the batch holds is the row order,+ # a best-effort proxy for arrival order. Keeping the first row let a pre-payment snapshot+ # outrank the payment event that followed it in the same second.+ if existing is None or ts >= existing[0]:best_by_id[obj_id] = (ts, obj)rows = [_scrub_client_secrets(obj) for _, obj in best_by_id.values()]@@ -1717,6 +1721,7 @@ def get_external_webhook_info(api_key: str, stripe_account_id: str | None, webhostatus=endpoint.status,description=endpoint.description,created_at=str(endpoint.created) if endpoint.created else None,+ api_version=endpoint.api_version,)return ExternalWebhookInfo(exists=False)@@ -1728,3 +1733,119 @@ def get_external_webhook_info(api_key: str, stripe_account_id: str | None, webhoerror="Your Stripe API key doesn't have permission to read webhooks. Add the 'Read' permission for 'Webhook endpoints' to your API key.",)return ExternalWebhookInfo(exists=False, error=f"Failed to check webhook status: {error_str}")+++@frozen+class WebhookRepin:+ """Outcome of repinning a webhook endpoint's API version by replacement."""++ status: Literal["replaced", "already_pinned", "no_endpoint", "failed"]+ previous_api_version: str | None = None+ signing_secret: str | None = dataclasses.field(default=None, repr=False)+ replaced_endpoint_id: str | None = None+ # Set as soon as Stripe creates the replacement, including on the failure that follows it.+ # Stripe returns the signing secret once, at create, so a caller that loses this id can no+ # longer identify the endpoint it must delete, and the endpoint keeps failing signature checks.+ created_endpoint_id: str | None = None+ error: str | None = None+++def create_pinned_webhook_replacement(+ api_key: str,+ stripe_account_id: str | None,+ webhook_url: str,+ *,+ api_version: str,+) -> WebhookRepin:+ """Add a second endpoint on `webhook_url` that is pinned to `api_version`, and return its secret.++ Stripe accepts `api_version` on create only. `POST /v1/webhook_endpoints/{id}` has no such+ parameter, so an endpoint created before we pinned the version can only be moved onto a+ version by replacement.++ This leaves the old endpoint in place on purpose. Stripe delivers every event to both+ endpoints while both exist, and the receiving hog function verifies against the one signing+ secret it stores, so the caller must store the new secret first and delete the old endpoint+ after (`delete_webhook_endpoint`). Each event in that window still has one copy that+ verifies. Deleting first would drop every event until the replacement exists, and Stripe+ only replays a dropped event on a manual resend.+ """+ try:+ client = StripeClient(+ api_key,+ stripe_account=stripe_account_id,+ stripe_version=api_version,+ max_network_retries=2,+ base_addresses=_stripe_base_addresses(),+ http_client=_tracked_stripe_http_client(),+ )++ endpoints = client.webhook_endpoints.list(params={"limit": 100})+ endpoint = next((e for e in endpoints.auto_paging_iter() if e.url == webhook_url), None)++ if endpoint is None:+ return WebhookRepin(status="no_endpoint")++ if endpoint.api_version == api_version:+ return WebhookRepin(status="already_pinned", previous_api_version=endpoint.api_version)++ # Carry the live subscription over, including any event the user added by hand. Only a+ # missing list falls back, because an empty one that fell back would subscribe the+ # replacement to every event the user had turned off.+ enabled_events = endpoint.enabled_events if endpoint.enabled_events is not None else _all_known_webhook_events()++ replacement = client.webhook_endpoints.create(+ params={+ "url": webhook_url,+ "enabled_events": enabled_events, # type: ignore[typeddict-item]+ "description": endpoint.description or "PostHog data warehouse webhook",+ "api_version": api_version, # type: ignore[typeddict-item]+ }+ )++ if not replacement.secret:+ return WebhookRepin(+ status="failed",+ created_endpoint_id=replacement.id,+ error=(+ f"Stripe created endpoint {replacement.id} without returning a signing secret. "+ "Delete it in Stripe, because nothing can verify its deliveries."+ ),+ )++ return WebhookRepin(+ status="replaced",+ previous_api_version=endpoint.api_version,+ signing_secret=replacement.secret,+ replaced_endpoint_id=endpoint.id,+ created_endpoint_id=replacement.id,+ )+ except Exception as e:+ error_str = _clean_stripe_error_message(str(e))+ if "permission" in error_str.lower() or "403" in error_str or "forbidden" in error_str.lower():+ error_str = (+ f"{error_str} (the API key needs the 'Write' permission for 'Webhook endpoints'; "+ "an app-connected source can never have it)"+ )+ return WebhookRepin(status="failed", error=error_str)+++def delete_webhook_endpoint(api_key: str, stripe_account_id: str | None, endpoint_id: str) -> WebhookDeletionResult:+ """Delete one endpoint by id.++ `delete_webhook` matches on URL, which is ambiguous while a replacement shares the URL with+ the endpoint it replaces.+ """+ try:+ client = StripeClient(+ api_key,+ stripe_account=stripe_account_id,+ stripe_version="2024-09-30.acacia",+ max_network_retries=2,+ base_addresses=_stripe_base_addresses(),+ http_client=_tracked_stripe_http_client(),+ )+ client.webhook_endpoints.delete(endpoint_id)+ return WebhookDeletionResult(success=True)+ except Exception as e:+ return WebhookDeletionResult(success=False, error=_clean_stripe_error_message(str(e)))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.pyindex 50e70cd02dce..791d40113e48 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@@ -1261,6 +1261,38 @@ class TestCustomerPaymentMethodHistory:assert HISTORY_EVENT_ID_COLUMN not in row+class TestWebhookUpsertCollapse:+ @parameterized.expand(+ [+ # One Stripe operation stamps every event it emits with the same whole second, so a+ # payment's invoice.updated and invoice.paid tie on `created`. The batch holds the+ # rows in arrival order, so the last row carries the newer state. Keeping the first+ # row left the invoice at `open` in the warehouse while Stripe showed `paid`, and+ # the sync still reported success.+ ("tie broken by arrival order", [(1700000100, "open"), (1700000100, "paid")], "paid"),+ # A redelivery can arrive after a newer event, so a plain last-row-wins rule would+ # reinstate the older state.+ ("older event delivered last", [(1700000100, "paid"), (1700000050, "open")], "paid"),+ ]+ )+ def test_latest_state_per_object_wins(+ self, _name: str, deliveries: list[tuple[int, str]], expected_status: str+ ) -> None:+ events = table_from_py_list(+ [+ _event_row(+ f"evt_{index}",+ "invoice.updated",+ event_created,+ {"id": "in_1", "object": "invoice", "created": 1700000000, "status": status},+ )+ for index, (event_created, status) in enumerate(deliveries)+ ]+ )+ rows = stripe_module._webhook_table_transformer(events).to_pylist()+ assert [row["status"] for row in rows] == [expected_status]++class TestEndpointCatalogWiring:def setup_method(self):self.resources = stripe_module._build_resources(MagicMock(), logger=None)@@ -1543,6 +1575,103 @@ class TestCreateWebhookLimitErrorCopy:assert "manually" in (result.error or "")+class TestRepinWebhookApiVersion:+ _URL = "https://example.com/webhook"++ def _endpoint(self, api_version: str | None) -> SimpleNamespace:+ return SimpleNamespace(+ id="we_old",+ url=self._URL,+ api_version=api_version,+ enabled_events=["invoice.paid", "customer.created"],+ description="PostHog data warehouse webhook",+ )++ def _client(self, mock_client_cls: MagicMock, endpoint: SimpleNamespace) -> MagicMock:+ client = mock_client_cls.return_value+ client.webhook_endpoints.list.return_value = _list_object([endpoint])+ client.webhook_endpoints.create.return_value = SimpleNamespace(id="we_new", secret="whsec_new")+ return client++ @parameterized.expand(+ [+ ("subscription is copied", ["invoice.paid", "customer.created"], ["invoice.paid", "customer.created"]),+ # An endpoint with nothing enabled must not come back subscribed to every Stripe event.+ ("nothing enabled stays empty", [], []),+ ]+ )+ def test_replacement_is_pinned_and_keeps_the_old_endpoint(+ self, _name: str, enabled_events: list[str], expected_events: list[str]+ ):+ # Stripe takes api_version on create only, so the endpoint has to be replaced. The old+ # endpoint must survive this call: its deliveries are the only ones that verify until the+ # caller stores the new signing secret.+ with patch.object(stripe_module, "StripeClient") as mock_client_cls:+ endpoint = self._endpoint(None)+ endpoint.enabled_events = enabled_events+ client = self._client(mock_client_cls, endpoint)++ repin = stripe_module.create_pinned_webhook_replacement(+ api_key="sk_test_123",+ stripe_account_id=None,+ webhook_url=self._URL,+ api_version=STRIPE_API_VERSION_ACACIA,+ )++ params = client.webhook_endpoints.create.call_args.kwargs["params"]+ assert params["api_version"] == STRIPE_API_VERSION_ACACIA+ assert params["url"] == self._URL+ assert params["enabled_events"] == expected_events+ client.webhook_endpoints.delete.assert_not_called()++ assert repin.status == "replaced"+ assert repin.signing_secret == "whsec_new"+ assert repin.replaced_endpoint_id == "we_old"++ @parameterized.expand(+ [+ # A second run must not rotate the signing secret of an endpoint that is already on+ # the version, and a source whose endpoint was removed in Stripe has nothing to repin.+ ("already pinned", STRIPE_API_VERSION_ACACIA, "https://example.com/webhook", "already_pinned"),+ ("no endpoint on this url", None, "https://example.com/other", "no_endpoint"),+ ]+ )+ def test_no_replacement_without_drift(self, _name: str, api_version: str | None, url: str, expected: str):+ with patch.object(stripe_module, "StripeClient") as mock_client_cls:+ endpoint = self._endpoint(api_version)+ endpoint.url = url+ client = self._client(mock_client_cls, endpoint)++ repin = stripe_module.create_pinned_webhook_replacement(+ api_key="sk_test_123",+ stripe_account_id=None,+ webhook_url=self._URL,+ api_version=STRIPE_API_VERSION_ACACIA,+ )++ assert repin.status == expected+ client.webhook_endpoints.create.assert_not_called()++ def test_a_replacement_without_a_secret_is_a_failure_that_names_the_endpoint(self):+ # Stripe returns the signing secret once, at create. A replacement whose secret never+ # arrived can never verify a delivery, and reporting it as replaced would delete the+ # working endpoint and leave only the unusable one.+ with patch.object(stripe_module, "StripeClient") as mock_client_cls:+ client = self._client(mock_client_cls, self._endpoint(None))+ client.webhook_endpoints.create.return_value = SimpleNamespace(id="we_new", secret=None)++ repin = stripe_module.create_pinned_webhook_replacement(+ api_key="sk_test_123",+ stripe_account_id=None,+ webhook_url=self._URL,+ api_version=STRIPE_API_VERSION_ACACIA,+ )++ assert repin.status == "failed"+ assert repin.created_endpoint_id == "we_new"+ client.webhook_endpoints.delete.assert_not_called()++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_writediff --git a/products/warehouse_sources/backend/tests/management/test_repin_stripe_webhook_api_version.py b/products/warehouse_sources/backend/tests/management/test_repin_stripe_webhook_api_version.pynew file mode 100644index 000000000000..1e7d5176025d--- /dev/null+++ b/products/warehouse_sources/backend/tests/management/test_repin_stripe_webhook_api_version.py@@ -0,0 +1,167 @@+import uuid+from types import SimpleNamespace++import pytest+from unittest.mock import patch++from django.core.management import call_command++from posthog.api.test.test_organization import create_organization+from posthog.api.test.test_team import create_team++from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ WebhookDeletionResult,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import STRIPE_API_VERSION_ACACIA+from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSource+from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe import WebhookRepin++pytestmark = [pytest.mark.django_db]++COMMAND = "repin_stripe_webhook_api_version"+DRIFTED_KEY = "sk_test_drifted"+++def team():+ return create_team(organization=create_organization("test org"))+++def _create_source_with_webhook(+ team, secret_key: str, auth_method: str = "api_key"+) -> tuple[ExternalDataSource, HogFunction]:+ source = ExternalDataSource.objects.create(+ team=team,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ source_type="Stripe",+ job_inputs={"stripe_secret_key": secret_key, "auth_method": auth_method},+ )+ hog_function = HogFunction.objects.create(+ team=team,+ type="warehouse_source_webhook",+ name="Stripe warehouse source webhook",+ hog="// test code",+ enabled=True,+ inputs_schema=[+ {"key": "signing_secret", "type": "string", "secret": True},+ {"key": "schema_mapping", "type": "json"},+ {"key": "source_id", "type": "string"},+ ],+ inputs={+ "signing_secret": {"value": "whsec_old"},+ "schema_mapping": {"value": {"invoice": str(uuid.uuid4())}},+ "source_id": {"value": str(source.id)},+ },+ )+ return source, hog_function+++def _stored_secret(hog_function_id) -> str | None:+ stored = HogFunction.objects.get(id=hog_function_id)+ return ((stored.encrypted_inputs or {}).get("signing_secret") or {}).get("value")+++def _parse_config(job_inputs) -> SimpleNamespace:+ return SimpleNamespace(+ stripe_secret_key=job_inputs["stripe_secret_key"],+ auth_method=SimpleNamespace(selection=job_inputs.get("auth_method", "api_key")),+ )+++def _webhook_info(config, webhook_url, team_id, api_version=None) -> ExternalWebhookInfo:+ drifted = config.stripe_secret_key == DRIFTED_KEY+ return ExternalWebhookInfo(+ exists=True,+ url=webhook_url,+ api_version=None if drifted else STRIPE_API_VERSION_ACACIA,+ )+++class TestRepinStripeWebhookApiVersion:+ def test_dry_run_does_not_touch_stripe_or_the_signing_secret(self, team):+ _, hog_function = _create_source_with_webhook(team, DRIFTED_KEY)++ with (+ patch.object(StripeSource, "parse_config", side_effect=_parse_config),+ patch.object(StripeSource, "get_external_webhook_info", side_effect=_webhook_info),+ patch.object(StripeSource, "create_pinned_webhook_replacement") as create,+ ):+ call_command(COMMAND)++ create.assert_not_called()+ assert _stored_secret(hog_function.id) == "whsec_old"++ def test_stores_the_new_secret_before_deleting_the_replaced_endpoint(self, team):+ _, drifted_hog_function = _create_source_with_webhook(team, DRIFTED_KEY)+ _, pinned_hog_function = _create_source_with_webhook(team, "sk_test_pinned")++ secret_when_deleted: list[str | None] = []++ def record_secret(config, endpoint_id, team_id) -> WebhookDeletionResult:+ secret_when_deleted.append(_stored_secret(drifted_hog_function.id))+ return WebhookDeletionResult(success=True)++ with (+ patch.object(StripeSource, "parse_config", side_effect=_parse_config),+ patch.object(StripeSource, "get_external_webhook_info", side_effect=_webhook_info),+ patch.object(+ StripeSource,+ "create_pinned_webhook_replacement",+ return_value=WebhookRepin(+ status="replaced",+ previous_api_version=None,+ signing_secret="whsec_new",+ replaced_endpoint_id="we_old",+ ),+ ) as create,+ patch.object(StripeSource, "delete_webhook_endpoint", side_effect=record_secret),+ ):+ call_command(COMMAND, live_run=True)++ # Stripe delivers to both endpoints until the old one goes, so the new secret has to be+ # stored first. Deleting first would leave every delivery failing the signature check.+ assert secret_when_deleted == ["whsec_new"]+ assert _stored_secret(drifted_hog_function.id) == "whsec_new"+ assert create.call_count == 1+ assert _stored_secret(pinned_hog_function.id) == "whsec_old"++ def test_app_connected_source_is_never_queued_for_replacement(self, team, capsys):+ _create_source_with_webhook(team, DRIFTED_KEY, auth_method="oauth")++ with (+ patch.object(StripeSource, "parse_config", side_effect=_parse_config),+ patch.object(StripeSource, "get_external_webhook_info", side_effect=_webhook_info),+ patch.object(StripeSource, "create_pinned_webhook_replacement") as create,+ ):+ call_command(COMMAND, live_run=True)++ create.assert_not_called()+ assert "Manual fix needed" in capsys.readouterr().out++ def test_a_replacement_without_a_secret_names_the_endpoint_it_left_behind(self, team, capsys):+ _, hog_function = _create_source_with_webhook(team, DRIFTED_KEY)++ with (+ patch.object(StripeSource, "parse_config", side_effect=_parse_config),+ patch.object(StripeSource, "get_external_webhook_info", side_effect=_webhook_info),+ patch.object(+ StripeSource,+ "create_pinned_webhook_replacement",+ return_value=WebhookRepin(+ status="failed",+ created_endpoint_id="we_new",+ error="Stripe returned no signing secret",+ ),+ ),+ patch.object(StripeSource, "delete_webhook_endpoint") as delete,+ ):+ call_command(COMMAND, live_run=True)++ # The endpoint is live in Stripe and its secret is unrecoverable, so the run has to name it.+ assert "we_new" in capsys.readouterr().out+ delete.assert_not_called()+ assert _stored_secret(hog_function.id) == "whsec_old"