: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
chore(devex): stop flagging vendor SDK verifiers in the inbound webhook rule (#103815)
Julian Bez8e23e85d426f
diff --git a/.agents/skills/adding-inbound-webhooks/SKILL.md b/.agents/skills/adding-inbound-webhooks/SKILL.mdindex f3d89eb2988b..659063e49fe4 100644--- a/.agents/skills/adding-inbound-webhooks/SKILL.md+++ b/.agents/skills/adding-inbound-webhooks/SKILL.md@@ -19,6 +19,10 @@ Which job are you doing?- No endpoint exists for this third party, or the semgrep rule flagged a hand-rolled verifier: **add a provider**, then add its consumer.- Outbound call to a vendor API, which is the other direction: `/routing-outbound-api-calls`.+Before you migrate a verifier, read what the existing code verifies with.+A verifier the vendor ships in its SDK, or one from a maintained library, stays as it is: it is written by the people who define the scheme, and a reimplementation only adds bugs.+Ingress wraps such a verifier at most. Only a hand-rolled `hmac` check is a migration.+## Add a consumerA product declares its consumers in `products/<product>/backend/webhook_consumers.py`, in a `WEBHOOK_CONSUMERS` sequence of `WebhookConsumer` values from `posthog.ingress.contracts`.diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.py b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.pyindex 7a101a5b8ded..2a89d26bb12c 100644--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.py+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.py@@ -81,12 +81,20 @@ def verify_pandadoc_signature(body: bytes, signature: str, secret: str) -> bool:return hmac.compare_digest(expected.hex(), signature)+# The vendor ships and maintains these verifiers, so they are the right way to check an+# inbound signature, not a violation to migrate away from.def sdk_delegated_view(request: HttpRequest) -> HttpResponse:- # ruleid: inbound-webhooks-go-through-ingress+ # ok: inbound-webhooks-go-through-ingressstripe.WebhookSignature.verify_header(request.body.decode(), "t=1,v1=abc", "secret", tolerance=300)return HttpResponse(status=202)+def sdk_construct_event_view(request: HttpRequest) -> HttpResponse:+ # ok: inbound-webhooks-go-through-ingress+ stripe.Webhook.construct_event(request.body.decode(), "t=1,v1=abc", "secret")+ return HttpResponse(status=202)++def ok_through_ingress() -> Callable[[HttpRequest], HttpResponse]:# ok: inbound-webhooks-go-through-ingressreturn build_webhook_view(build_github_provider("posthog"))diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yamlindex d4b3c9f39f98..27697d3ad869 100644--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml@@ -17,13 +17,17 @@ rules:outside the shared dedup, delivery budget, and delivery metrics, so a wedgedconsumer is invisible and holds the connection open.- The rule fires on three shapes: an `hmac` digest or compare in a module that also- reads one of the known signature headers, `hmac` inside a function named like a- signature verifier, and a vendor SDK call that verifies an inbound signature.- What it misses follows from those three. The header list is closed, so a provider- whose header is not in it is caught only by the other two branches. A verifier with- a name outside the regex, in a module that reads no known header, passes. So does a- vendor SDK the third branch does not name, and a verifier in another language.+ A verifier the vendor ships in its own SDK, such as `stripe.WebhookSignature`, is not+ a finding and stays as it is. It is maintained by the people who define the scheme, so+ replacing it with a copy of our own reintroduces exactly the mistakes above. Ingress+ wraps such a verifier at most, it never reimplements one.++ The rule fires on two shapes: an `hmac` digest or compare in a module that also+ reads one of the known signature headers, and `hmac` inside a function named like a+ signature verifier. What it misses follows from those two. The header list is closed,+ so a provider whose header is not in it is caught only by the other branch. A verifier+ with a name outside the regex, in a module that reads no known header, passes. So does+ a verifier in another language.Suppress a legitimate exception with`# nosemgrep: inbound-webhooks-go-through-ingress -- <reason>`.@@ -93,12 +97,6 @@ rules:- metavariable-regex:metavariable: $VERIFYregex: ^_?((is_|has_)?(verify|valid|check|match)[a-z0-9_]*(signature|webhook|digest)[a-z0-9_]*|(is_|has_)?[a-z0-9_]*(signature|webhook|digest)[a-z0-9_]*_(ok|valid|verified|match)[a-z0-9_]*)$- # A vendor SDK can own the compare, so neither branch above sees any `hmac`.- # These calls only ever verify an inbound signature; nothing signs with them.- - patterns:- - pattern-either:- - pattern: stripe.WebhookSignature.verify_header(...)- - pattern: stripe.Webhook.construct_event(...)paths:include:- /common/**/*.py@@ -117,5 +115,4 @@ rules:# migrates that endpoint removes its line. The paths are the ones on master,# so the rule holds whether or not the migrations land with it.- /ee/api/vercel/vercel_webhooks.py- - /ee/partners/stripe/api/provisioning/signature.py- /products/workflows/backend/api/ses_events_webhook.pydiff --git a/ee/partners/stripe/api/provisioning/signature.py b/ee/partners/stripe/api/provisioning/signature.pyindex eb1ec1e27f65..36a57607ca08 100644--- a/ee/partners/stripe/api/provisioning/signature.py+++ b/ee/partners/stripe/api/provisioning/signature.py@@ -20,9 +20,6 @@ explicit with ``if error := verify_...(request): return error``.from __future__ import annotations-import hmac-import hashlib-from django.conf import settingsfrom django.http.request import RawPostDataException@@ -114,14 +111,6 @@ def verify_stripe_signature(request: Request) -> Response | None:return None-def compute_signature(secret: str, timestamp: int, body: bytes) -> str:- """Compute HMAC-SHA256 signature for a request body. Exposed for testing."""- mac = hmac.new(secret.encode(), digestmod=hashlib.sha256)- mac.update(f"{timestamp}.".encode())- mac.update(body)- return mac.digest().hex()--def _get_raw_body(request: Request) -> bytes | None:"""Get raw request body, returning None if the stream was already consumed."""django_request = getattr(request, "_request", request)diff --git a/ee/partners/stripe/api/provisioning/test/base.py b/ee/partners/stripe/api/provisioning/test/base.pyindex ae7a462d6ae1..e041fa81ff85 100644--- a/ee/partners/stripe/api/provisioning/test/base.py+++ b/ee/partners/stripe/api/provisioning/test/base.py@@ -1,5 +1,7 @@+import hmacimport jsonimport time+import hashlibfrom urllib.parse import urlencodefrom posthog.test.base import APIBaseTest@@ -12,7 +14,6 @@ from rest_framework.test import APIClientfrom posthog.models.oauth import OAuthApplicationfrom ee.partners.stripe.api.provisioning import AUTH_CODE_CACHE_PREFIX-from ee.partners.stripe.api.provisioning.signature import compute_signatureHMAC_SECRET = "test_hmac_secret"TEST_STRIPE_OAUTH_CLIENT_ID = "test_stripe_oauth_client_id"@@ -20,6 +21,14 @@ TEST_STRIPE_OAUTH_CLIENT_ID = "test_stripe_oauth_client_id"BASE_PATH = "/api/partners/stripe"+def compute_signature(secret: str, timestamp: int, body: bytes) -> str:+ """Sign a request body the way Stripe does, so tests can forge a valid header."""+ mac = hmac.new(secret.encode(), digestmod=hashlib.sha256)+ mac.update(f"{timestamp}.".encode())+ mac.update(body)+ return mac.digest().hex()++@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET,STRIPE_POSTHOG_OAUTH_CLIENT_ID=TEST_STRIPE_OAUTH_CLIENT_ID,diff --git a/ee/partners/stripe/api/provisioning/test/test_e2e_flow.py b/ee/partners/stripe/api/provisioning/test/test_e2e_flow.pyindex 90d216ed0ce0..e7eac8f422b3 100644--- a/ee/partners/stripe/api/provisioning/test/test_e2e_flow.py+++ b/ee/partners/stripe/api/provisioning/test/test_e2e_flow.py@@ -6,8 +6,12 @@ from django.utils import timezonefrom posthog.models.user import User-from ee.partners.stripe.api.provisioning.signature import compute_signature-from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, HMAC_SECRET, StripeProvisioningTestBase+from ee.partners.stripe.api.provisioning.test.base import (+ BASE_PATH,+ HMAC_SECRET,+ StripeProvisioningTestBase,+ compute_signature,+)class TestE2EProvisioningFlow(StripeProvisioningTestBase):diff --git a/ee/partners/stripe/api/provisioning/test/test_oauth_token.py b/ee/partners/stripe/api/provisioning/test/test_oauth_token.pyindex 6190dd92ac98..9e42a8fa181a 100644--- a/ee/partners/stripe/api/provisioning/test/test_oauth_token.py+++ b/ee/partners/stripe/api/provisioning/test/test_oauth_token.py@@ -16,8 +16,12 @@ from posthog.models.utils import generate_random_oauth_refresh_tokenfrom products.access_control.backend.models.access_control import AccessControl-from ee.partners.stripe.api.provisioning.signature import compute_signature-from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, HMAC_SECRET, StripeProvisioningTestBase+from ee.partners.stripe.api.provisioning.test.base import (+ BASE_PATH,+ HMAC_SECRET,+ StripeProvisioningTestBase,+ compute_signature,+)TOKEN_URL = f"{BASE_PATH}/oauth/token"diff --git a/ee/partners/stripe/api/provisioning/test/test_signature.py b/ee/partners/stripe/api/provisioning/test/test_signature.pyindex d87db62577b1..214d292f8a2d 100644--- a/ee/partners/stripe/api/provisioning/test/test_signature.py+++ b/ee/partners/stripe/api/provisioning/test/test_signature.py@@ -4,8 +4,12 @@ from django.test import override_settingsfrom parameterized import parameterized-from ee.partners.stripe.api.provisioning.signature import compute_signature-from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, HMAC_SECRET, StripeProvisioningTestBase+from ee.partners.stripe.api.provisioning.test.base import (+ BASE_PATH,+ HMAC_SECRET,+ StripeProvisioningTestBase,+ compute_signature,+)HEALTH_URL = f"{BASE_PATH}/provisioning/health"diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex fee2eb977e8c..f022c125f9ce 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -211,8 +211,7 @@ def _verify_stripe_install_signature(state: str, user_id: str, account_id: str,separators=(",", ":"),)try:- # 300s tolerance matches the Stripe provisioning HMAC check at ee/partners/stripe/api/provisioning/signature.py.- # nosemgrep: inbound-webhooks-go-through-ingress -- this signs a marketplace install redirect, not a webhook delivery, so there is nothing for the dispatcher to fan out+ # 300s tolerance matches the Stripe provisioning check at ee/partners/stripe/api/provisioning/signature.py.stripe.WebhookSignature.verify_header(payload, install_signature, settings.STRIPE_SIGNING_SECRET, tolerance=300)return Trueexcept stripe.SignatureVerificationError:diff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex 60c2dc19f158..d68418bfde01 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -2,6 +2,7 @@General-purpose controls for the webhooks third parties send _in_ to PostHog.A new inbound webhook that needs signature verification or fan-out belongs here as a `<provider>/` incarnation (see [Adding a provider](#adding-a-provider)), never hand-rolled around `hmac` in a view.+A verifier the vendor ships in its SDK is not hand-rolled and is not a migration: it stays, and a scheme here calls it rather than reimplementing the compare.Four lanes:- **`verify/`** — signature schemes. HMAC-SHA256 in the shapes providers actually send (hex or base64, an optional prefix, an optional `v0:{timestamp}:{body}` input with a replay window), the SNS envelope check, and a bearer JWT checked against the issuer's published signing keys.