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(billing): guard payment authorization against overlapping requests (#112192)

posthog[bot]2e8807438774
diff --git a/ee/api/billing.py b/ee/api/billing.py
index fd4f4d23091f..0791656fe491 100644
--- a/ee/api/billing.py
+++ b/ee/api/billing.py
@@ -124,6 +124,14 @@ class BillingServiceError(APIException):
default_detail = "Billing could not answer this request. Try again in a moment."
+class PaymentAuthorizationRejected(APIException):
+ """Billing refused to start the payment authorization."""
+
+ status_code = status.HTTP_400_BAD_REQUEST
+ default_code = "payment_authorization_rejected"
+ default_detail = "We could not start the payment setup. Close this window and try again."
+
+
class BillingManagedByProviderError(APIException):
status_code = status.HTTP_400_BAD_REQUEST
default_code = "billing_managed_by_provider"
@@ -998,8 +1006,20 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
organization = self._get_org_required()
billing_manager = self.get_billing_manager()
- with translate_managed_by_provider_refusal():
- res = billing_manager.authorize(organization)
+ try:
+ with translate_managed_by_provider_refusal():
+ res = billing_manager.authorize(organization)
+ except BillingServiceResponseError as e:
+ # The billing body can hold database error text, so the caller gets a controlled message.
+ logger.warning(
+ "billing_authorize_error",
+ organization_id=str(organization.id),
+ upstream_status=e.status_code,
+ body=str(e.body)[:500],
+ )
+ if 400 <= e.status_code < 500:
+ raise PaymentAuthorizationRejected() from e
+ raise BillingServiceError() from e
return Response(res, status=status.HTTP_200_OK)
@extend_schema(
diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.py
index 88b8fcc312ff..86c20d922d00 100644
--- a/ee/api/test/test_billing.py
+++ b/ee/api/test/test_billing.py
@@ -1078,6 +1078,34 @@ class TestActivateBillingAPI(APILicensedTest):
self.assertEqual(response.json(), {"success": True, "products": ["product_analytics"]})
mock_activate_subscription.assert_called_once_with(self.organization, {"products": "all_products:"})
+ @parameterized.expand(
+ [
+ ("billing_refusal", 400, status.HTTP_400_BAD_REQUEST, "payment_authorization_rejected"),
+ ("billing_unauthorized", 401, status.HTTP_400_BAD_REQUEST, "payment_authorization_rejected"),
+ ("billing_not_found", 404, status.HTTP_400_BAD_REQUEST, "payment_authorization_rejected"),
+ ("billing_failure", 500, status.HTTP_502_BAD_GATEWAY, "billing_service_error"),
+ ]
+ )
+ @patch("ee.billing.billing_manager.http_session.post")
+ def test_authorize_hides_the_billing_error_body(
+ self, _name: str, upstream_status: int, expected_status: int, expected_code: str, mock_post
+ ):
+ mock_post.return_value = MagicMock(
+ status_code=upstream_status,
+ json=lambda: {"detail": "duplicate key value violates unique constraint"},
+ text="duplicate key value violates unique constraint",
+ )
+
+ response = self.client.post(
+ "/api/billing/activate/authorize",
+ {"organization_id": str(self.organization.id)},
+ content_type="application/json",
+ )
+
+ self.assertEqual(response.status_code, expected_status)
+ self.assertEqual(response.json()["code"], expected_code)
+ self.assertNotIn("duplicate key", response.content.decode())
+
def test_activate_get_returns_405(self):
url = "/api/billing/activate"
response = self.client.get(url, {"products": "product_1:plan_1"})
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.py
index fcb90c369232..7a835675b586 100644
--- a/ee/billing/billing_manager.py
+++ b/ee/billing/billing_manager.py
@@ -1073,7 +1073,7 @@ class BillingManager:
json=data,
)
- handle_billing_service_error(res)
+ handle_billing_service_error(res, valid_codes=(200, 201))
return res.json()
diff --git a/frontend/src/scenes/billing/paymentEntryLogic.test.ts b/frontend/src/scenes/billing/paymentEntryLogic.test.ts
index a5a3d1081666..09fc79534b86 100644
--- a/frontend/src/scenes/billing/paymentEntryLogic.test.ts
+++ b/frontend/src/scenes/billing/paymentEntryLogic.test.ts
@@ -238,6 +238,129 @@ describe('paymentEntryLogic', () => {
})
})
+ describe('initiateAuthorization', () => {
+ it.each([
+ ['same organization', false, 200],
+ ['another organization', true, 200],
+ ['same organization after a failure', false, 500],
+ ['another organization after a failure', true, 500],
+ ] as const)('initializes only the latest reopened flow for %s', async (_, switchOrganization, oldStatus) => {
+ const oldResponse = deferred<[number, unknown]>()
+ const currentResponse = deferred<[number, unknown]>()
+ let oldRequestPending = true
+ const overlap: boolean[] = []
+ const authorize = jest
+ .fn((_body: unknown) => {
+ overlap.push(oldRequestPending)
+ return currentResponse.promise
+ })
+ .mockImplementationOnce(() => oldResponse.promise)
+ useMocks({
+ post: { '/api/billing/activate/authorize': async ({ request }) => authorize(await request.json()) },
+ })
+ logic = paymentEntryLogic()
+ logic.mount()
+ const originalId = organizationLogic.values.currentOrganization!.id
+ logic.actions.beginPaymentFlow(originalId)
+ logic.actions.showPaymentEntryModal()
+ logic.actions.initiateAuthorization()
+ await waitFor(() => expect(authorize).toHaveBeenCalledTimes(1))
+
+ logic.actions.hidePaymentEntryModal()
+ logic.actions.beginPaymentFlow(OTHER_ORGANIZATION_ID)
+ logic.actions.showPaymentEntryModal()
+ logic.actions.initiateAuthorization()
+ logic.actions.hidePaymentEntryModal()
+ const currentId = switchOrganization ? OTHER_ORGANIZATION_ID : originalId
+ logic.actions.beginPaymentFlow(currentId)
+ logic.actions.showPaymentEntryModal()
+ logic.actions.initiateAuthorization()
+
+ oldRequestPending = false
+ oldResponse.resolve([oldStatus, { clientSecret: 'secret_old' }])
+ try {
+ await waitFor(() => expect(authorize).toHaveBeenCalledTimes(2))
+ expect(overlap).toEqual([false])
+ expect(authorize.mock.calls.map(([body]) => body)).toEqual([
+ { organization_id: originalId },
+ { organization_id: currentId },
+ ])
+ expect(logic.values.clientSecret).toBe(null)
+ expect(logic.values.apiError).toBe(null)
+ expect(logic.values.isLoading).toBe(true)
+ } finally {
+ currentResponse.resolve([200, { clientSecret: 'secret_current' }])
+ await expectLogic(logic).toFinishAllListeners()
+ }
+ expect(logic.values.paymentEntryModalOpen).toBe(true)
+ expect(logic.values.clientSecret).toBe('secret_current')
+ expect(logic.values.apiError).toBe(null)
+ expect(logic.values.isLoading).toBe(false)
+ })
+
+ it.each(['closed', 'unmounted'] as const)(
+ 'does not restart authorization when the replacement flow is %s',
+ async (state) => {
+ const response = deferred<[number, unknown]>()
+ const authorize = jest.fn(() => response.promise)
+ useMocks({ post: { '/api/billing/activate/authorize': authorize } })
+ logic = paymentEntryLogic()
+ logic.mount()
+ logic.actions.beginPaymentFlow(organizationLogic.values.currentOrganization!.id)
+ logic.actions.showPaymentEntryModal()
+ logic.actions.initiateAuthorization()
+ await waitFor(() => expect(authorize).toHaveBeenCalledTimes(1))
+ logic.actions.hidePaymentEntryModal()
+ logic.actions.beginPaymentFlow(OTHER_ORGANIZATION_ID)
+ logic.actions.showPaymentEntryModal()
+ logic.actions.initiateAuthorization()
+ if (state === 'closed') {
+ logic.actions.hidePaymentEntryModal()
+ } else {
+ logic.unmount()
+ }
+ response.resolve([200, { clientSecret: 'secret_old' }])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(authorize).toHaveBeenCalledTimes(1)
+ }
+ )
+
+ it('allows a new authorization attempt after a failure', async () => {
+ const authorize = jest
+ .fn((): [number, unknown] => [200, { clientSecret: 'secret_retry' }])
+ .mockImplementationOnce(() => [500, {}])
+ useMocks({ post: { '/api/billing/activate/authorize': authorize } })
+ logic = paymentEntryLogic()
+ logic.mount()
+ logic.actions.beginPaymentFlow(organizationLogic.values.currentOrganization!.id)
+ logic.actions.showPaymentEntryModal()
+ await expectLogic(logic, () => logic.actions.initiateAuthorization()).toFinishAllListeners()
+ expect(logic.values.apiError).toBe('Failed to initialize payment')
+ await expectLogic(logic, () => logic.actions.initiateAuthorization()).toFinishAllListeners()
+ expect(authorize).toHaveBeenCalledTimes(2)
+ expect(logic.values.clientSecret).toBe('secret_retry')
+ expect(logic.values.apiError).toBe(null)
+ expect(logic.values.isLoading).toBe(false)
+ })
+
+ it('sends one authorize request when the modal asks twice before the first answer', async () => {
+ const authorize = jest.fn(() => [200, { clientSecret: 'secret_test' }] as [number, Record<string, unknown>])
+ useMocks({ post: { '/api/billing/activate/authorize': authorize } })
+ logic = paymentEntryLogic()
+ logic.mount()
+ logic.actions.beginPaymentFlow(organizationLogic.values.currentOrganization!.id)
+
+ await expectLogic(logic, () => {
+ logic.actions.initiateAuthorization()
+ logic.actions.initiateAuthorization()
+ }).toFinishAllListeners()
+
+ expect(authorize).toHaveBeenCalledTimes(1)
+ expect(logic.values.clientSecret).toBe('secret_test')
+ expect(logic.values.apiError).toBe(null)
+ })
+ })
+
describe('startPaymentEntryFlow — billing locked outside PostHog', () => {
it.each<{ name: string; billing: Partial<BillingType> }>([
{
diff --git a/frontend/src/scenes/billing/paymentEntryLogic.ts b/frontend/src/scenes/billing/paymentEntryLogic.ts
index d236a53c34c9..f5c0a2f42aa9 100644
--- a/frontend/src/scenes/billing/paymentEntryLogic.ts
+++ b/frontend/src/scenes/billing/paymentEntryLogic.ts
@@ -489,23 +489,42 @@ export const paymentEntryLogic = kea<paymentEntryLogicType>([
actions.setApiError(PAYMENT_ORGANIZATION_ERROR)
return
}
+ // Two overlapping requests make billing create two Stripe customers, and the second one fails.
+ if (cache.authorizationInFlight) {
+ return
+ }
+ const flow = values.paymentFlow
+ const disposables = cache.disposables
+ cache.authorizationInFlight = true
actions.setClientSecret(null)
actions.setLoading(true)
actions.clearErrors()
- await runPaymentStep(
- () => billingActivateAuthorizeCreate({ organization_id: organizationId }),
- (response) => {
- actions.setClientSecret(response.clientSecret || null)
- actions.setLoading(false)
- },
- (error) => {
- posthog.captureException(
- new Error('payment entry api error - initiate authorization error', { cause: error })
- )
- actions.setApiError('Failed to initialize payment')
- actions.setLoading(false)
+ try {
+ await runPaymentStep(
+ () => billingActivateAuthorizeCreate({ organization_id: organizationId }),
+ (response) => {
+ actions.setClientSecret(response.clientSecret || null)
+ actions.setLoading(false)
+ },
+ (error) => {
+ posthog.captureException(
+ new Error('payment entry api error - initiate authorization error', { cause: error })
+ )
+ actions.setApiError('Failed to initialize payment')
+ actions.setLoading(false)
+ }
+ )
+ } finally {
+ cache.authorizationInFlight = false
+ if (
+ !disposables.isDisposed &&
+ values.paymentEntryModalOpen &&
+ values.paymentFlow &&
+ values.paymentFlow !== flow
+ ) {
+ await asyncActions.initiateAuthorization()
}
- )
+ }
},
confirmPayment: async ({ stripe, elements }) => {
const returnUrl = values.stripeReturnUrl