: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(billing): sign provider webhook forwarding (#59023)
Abhischek2253798c9aa1
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.pyindex 7499ab617424..a1e3a0e81143 100644--- a/ee/billing/billing_manager.py+++ b/ee/billing/billing_manager.py@@ -1,4 +1,5 @@import json+import timefrom datetime import UTC, datetime, timedeltafrom enum import Enumfrom typing import Any, Optional, cast@@ -20,6 +21,7 @@ from posthog.models import Organizationfrom posthog.models.organization import OrganizationMembership, OrganizationUsageInfofrom posthog.models.user import User+from ee.api.agentic_provisioning.signature import compute_signaturefrom ee.billing.billing_types import BillingProvider, BillingStatusfrom ee.billing.quota_limiting import set_org_usage_summary, update_org_billing_quotasfrom ee.models import License@@ -27,6 +29,10 @@ from ee.settings import BILLING_SERVICE_URLlogger = structlog.get_logger(__name__)+BILLING_PROVIDER_WEBHOOK_SIGNATURE_HEADER = "X-PostHog-Billing-Provider-Signature"+BILLING_PROVIDER_WEBHOOK_TIMESTAMP_HEADER = "X-PostHog-Billing-Provider-Timestamp"+BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION = "sha256"+class BillingAPIErrorCodes(Enum):OPEN_INVOICES_ERROR = "open_invoices_error"@@ -116,6 +122,19 @@ def build_billing_token(return encoded_jwt+def build_billing_provider_webhook_signature_headers(body: bytes) -> dict[str, str]:+ secret = getattr(settings, "BILLING_PROVIDER_WEBHOOK_SECRET", "")+ if not secret:+ raise ValueError("BILLING_PROVIDER_WEBHOOK_SECRET is not configured")++ timestamp = int(time.time())+ digest = compute_signature(secret, timestamp, body)+ return {+ BILLING_PROVIDER_WEBHOOK_SIGNATURE_HEADER: f"{BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION}={digest}",+ BILLING_PROVIDER_WEBHOOK_TIMESTAMP_HEADER: str(timestamp),+ }++def handle_billing_service_error(res: requests.Response, valid_codes=(200, 201, 404, 401)) -> None:if res.status_code not in valid_codes:logger.error(f"Billing service returned bad status code: {res.status_code}, body: {res.text}")@@ -738,14 +757,25 @@ class BillingManager:Pure passthrough - no transformation of event data.Raises exception on failure (causes webhook endpoint to return 500, triggering provider retry)."""- res = requests.post(- f"{BILLING_SERVICE_URL}/api/webhooks/billing-provider",- headers=self.get_auth_headers(organization),- json={+ body = json.dumps(+ {"event_type": event_type,"event_data": event_data,"billing_provider": billing_provider,},+ allow_nan=False,+ separators=(",", ":"),+ ).encode("utf-8")+ headers = {+ **self.get_auth_headers(organization),+ **build_billing_provider_webhook_signature_headers(body),+ "Content-Type": "application/json",+ }++ res = requests.post(+ f"{BILLING_SERVICE_URL}/api/webhooks/billing-provider",+ headers=headers,+ data=body,timeout=30,)diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.pyindex 5e00cdf2e8b0..7f40af46cb6d 100644--- a/ee/billing/test/test_billing_manager.py+++ b/ee/billing/test/test_billing_manager.py@@ -1,10 +1,16 @@+import hmacimport json+import math+import hashlibimport datetime+from types import SimpleNamespacefrom typing import Any, castfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from django.test import SimpleTestCase, override_settings+import jwtimport requestsfrom parameterized import parameterized@@ -14,7 +20,14 @@ from posthog.cloud_utils import TEST_clear_instance_license_cachefrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.user import User-from ee.billing.billing_manager import BillingManager, _get_user_organization_role, build_billing_token+from ee.billing.billing_manager import (+ BILLING_PROVIDER_WEBHOOK_SIGNATURE_HEADER,+ BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION,+ BILLING_PROVIDER_WEBHOOK_TIMESTAMP_HEADER,+ BillingManager,+ _get_user_organization_role,+ build_billing_token,+)from ee.billing.billing_types import BillingProvider, BillingStatus, Productfrom ee.models.license import License, LicenseManager@@ -409,6 +422,88 @@ class TestBillingManager(BaseTest):assert "Open invoices must be resolved first" in str(context.exception)+class TestBillingProviderWebhookSigning(SimpleTestCase):+ def setUp(self):+ self.license = SimpleNamespace(key="license_id::license_secret")+ self.organization = cast(Organization, SimpleNamespace(id="org_123", name="Test Org"))++ @override_settings(BILLING_PROVIDER_WEBHOOK_SECRET="test_webhook_secret")+ @patch("ee.billing.billing_manager.time.time", return_value=1700000000)+ @patch(+ "ee.billing.billing_manager.requests.post",+ return_value=MagicMock(status_code=200, ok=True, text="", json=MagicMock(return_value={"status": "ok"})),+ )+ def test_handle_billing_provider_webhook_signs_forwarded_body(+ self, billing_post_request_mock: MagicMock, mock_time: MagicMock+ ):+ BillingManager(self.license).handle_billing_provider_webhook(+ event_type="marketplace.invoice.paid",+ event_data={"installationId": "icfg_123", "invoiceId": "mi_123"},+ organization=self.organization,+ billing_provider="vercel",+ )++ billing_post_request_mock.assert_called_once()+ call_kwargs = billing_post_request_mock.call_args.kwargs+ body = call_kwargs["data"]+ expected_body = (+ b'{"event_type":"marketplace.invoice.paid",'+ b'"event_data":{"installationId":"icfg_123","invoiceId":"mi_123"},'+ b'"billing_provider":"vercel"}'+ )+ expected_signature = hmac.new(+ b"test_webhook_secret",+ b"1700000000." + expected_body,+ hashlib.sha256,+ ).hexdigest()++ assert body == expected_body+ assert call_kwargs["headers"][BILLING_PROVIDER_WEBHOOK_TIMESTAMP_HEADER] == "1700000000"+ assert (+ call_kwargs["headers"][BILLING_PROVIDER_WEBHOOK_SIGNATURE_HEADER]+ == f"{BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION}={expected_signature}"+ )+ assert call_kwargs["headers"]["Content-Type"] == "application/json"+ assert "Authorization" in call_kwargs["headers"]++ @override_settings(BILLING_PROVIDER_WEBHOOK_SECRET="")+ @patch("ee.billing.billing_manager.requests.post")+ def test_handle_billing_provider_webhook_requires_signature_secret(self, billing_post_request_mock: MagicMock):+ with self.assertRaises(ValueError) as context:+ BillingManager(self.license).handle_billing_provider_webhook(+ event_type="marketplace.invoice.paid",+ event_data={"installationId": "icfg_123", "invoiceId": "mi_123"},+ organization=self.organization,+ billing_provider="vercel",+ )++ assert "BILLING_PROVIDER_WEBHOOK_SECRET" in str(context.exception)+ billing_post_request_mock.assert_not_called()++ @parameterized.expand(+ [+ ("nan", math.nan),+ ("infinity", math.inf),+ ("negative_infinity", -math.inf),+ ]+ )+ @override_settings(BILLING_PROVIDER_WEBHOOK_SECRET="test_webhook_secret")+ @patch("ee.billing.billing_manager.requests.post")+ def test_handle_billing_provider_webhook_rejects_non_finite_numbers(+ self, _name: str, non_finite_number: float, billing_post_request_mock: MagicMock+ ):+ with self.assertRaises(ValueError) as context:+ BillingManager(self.license).handle_billing_provider_webhook(+ event_type="marketplace.invoice.paid",+ event_data={"installationId": "icfg_123", "amount": non_finite_number},+ organization=self.organization,+ billing_provider="vercel",+ )++ assert "Out of range float values are not JSON compliant" in str(context.exception)+ billing_post_request_mock.assert_not_called()++class TestBuildBillingToken(BaseTest):def setUp(self):super().setUp()diff --git a/ee/settings.py b/ee/settings.pyindex 5c335a0a2665..077538e15468 100644--- a/ee/settings.py+++ b/ee/settings.py@@ -145,6 +145,7 @@ HARMONIC_BASE_URL = get_from_env("HARMONIC_BASE_URL", "https://api.harmonic.ai",# Vercel IntegrationVERCEL_CLIENT_INTEGRATION_ID = get_from_env("VERCEL_CLIENT_INTEGRATION_ID", "", type_cast=str)VERCEL_CLIENT_INTEGRATION_SECRET = get_from_env("VERCEL_CLIENT_INTEGRATION_SECRET", "", type_cast=str)+BILLING_PROVIDER_WEBHOOK_SECRET = get_from_env("BILLING_PROVIDER_WEBHOOK_SECRET", "", type_cast=str)# SCIM Configuration# django-scim2 requires these settings