: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(legal-documents): verify the PandaDoc webhook through ingress (#100876)
Julian Beze26f2915878d
diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yamlindex 9cebe2dcf9bb..89968e9ed395 100644--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml@@ -123,6 +123,5 @@ rules:- /products/conversations/backend/api/slack_events.py- /products/conversations/backend/mailgun.py- /products/conversations/backend/support_slack.py- - /products/legal_documents/backend/logic/pandadoc.py- /products/user_interviews/backend/presentation/webhooks.py- /products/workflows/backend/api/ses_events_webhook.pydiff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex fa59f6c1168f..d9b56200eade 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -122,7 +122,7 @@ Ingress carries both as general controls, so the next endpoint gets them withoutAdd a `<provider>/` subpackage with a `provider.py` holding three things (see `github/` for the full shape, `vapi/` for a small one):- `SPECS` — one `ProviderSpec` per app, naming the event types the app is subscribed to. The registry validates consumers against these.-- A `WebhookProvider` subclass — its `scheme()` (from `verify/`), its `deliveries()` (how to read event type, delivery id and context off the request), and any status codes its protocol fixes. The defaults are 403 on a bad signature, 500 when unconfigured, and 202 on success.+- A `WebhookProvider` subclass — its `scheme()` (from `verify/`), its `deliveries()` (how to read event type, delivery id and context off the request), and any status codes its protocol fixes. The defaults are 403 on a bad signature, 500 when unconfigured, and 202 on success, with a short body naming the reason on the two rejections. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well.- A `build_<provider>_provider(...)` function returning that provider, which the URLconf hands to `build_webhook_view()`.Add the module to `_INCARNATION_MODULES` in `posthog/ingress/providers.py`, so the registry finds its specs and any core consumers.diff --git a/posthog/ingress/pandadoc/README.md b/posthog/ingress/pandadoc/README.mdindex 1c4838e7f07a..2376777a5d8a 100644--- a/posthog/ingress/pandadoc/README.md+++ b/posthog/ingress/pandadoc/README.md@@ -29,9 +29,10 @@ The secret is the Django setting `PANDADOC_WEBHOOK_SECRET`.PandaDoc batches several events into one body, so one request becomes one delivery per event, and all of them draw from the one request budget.A bad signature answers 404 instead of 403, so a prober cannot tell a wrong secret from an unknown route.+A missing secret answers 404 too, and neither rejection carries a body, because the reason would hand back what the status code withholds.## Consumers-No product registers a PandaDoc consumer yet.-The legal documents endpoint moves to ingress in its own PR.+`legal_documents_signatures`, declared in `products/legal_documents/backend/webhook_consumers.py`.+It records signatures for the document signing flow.See the [Endpoints table](../README.md#endpoints).diff --git a/posthog/ingress/pandadoc/provider.py b/posthog/ingress/pandadoc/provider.pyindex 28ccad072213..78e40ebc530f 100644--- a/posthog/ingress/pandadoc/provider.py+++ b/posthog/ingress/pandadoc/provider.py@@ -6,7 +6,7 @@ signature answers 404 by design, so an attacker cannot tell a wrong secret fromroute."""-from collections.abc import Mapping, Sequence+from collections.abc import Callable, Mapping, Sequencefrom typing import Anyfrom django.conf import settings@@ -31,8 +31,14 @@ class PandaDocProvider(WebhookProvider):provider = "pandadoc"app = "default"invalid_signature_status = 404-- def __init__(self) -> None:+ # A missing secret answers like an unknown route too, so an operator mistake does not hand a+ # prober the "this endpoint exists" the 404 above exists to withhold.+ unconfigured_status = 404+ # A body naming the reason would hand back what the two 404s above withhold.+ explains_rejections = False++ def __init__(self, *, enabled: Callable[[], bool] | None = None) -> None:+ self._enabled = enabledself._scheme = HmacSha256(secret_getter=_pandadoc_secret,signature_header=PANDADOC_SIGNATURE_HEADER,@@ -42,6 +48,10 @@ class PandaDocProvider(WebhookProvider):return self._schemedef verify(self, request: HttpRequest) -> VerificationOutcome:+ # A deployment that does not run the integration answers 404 before it reads anything off+ # the request, so the route stays indistinguishable from one that was never registered.+ if self._enabled is not None and not self._enabled():+ return VerificationOutcome.INVALID# Read through the scheme's own case-insensitive lookup, because Django normalizes a# header name to title case and an exact-case match would never find this one.# Presence decides, not truthiness: an empty header is a signature that fails, never a@@ -76,5 +86,7 @@ class PandaDocProvider(WebhookProvider):return tuple(deliveries)-def build_pandadoc_provider() -> PandaDocProvider:- return PandaDocProvider()+def build_pandadoc_provider(*, enabled: Callable[[], bool] | None = None) -> PandaDocProvider:+ """Whether a deployment serves this endpoint at all is the endpoint owner's call, so it is+ passed in rather than decided here."""+ return PandaDocProvider(enabled=enabled)diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.pyindex 97a7d4a56d54..557b253f7bf1 100644--- a/posthog/ingress/providers.py+++ b/posthog/ingress/providers.py@@ -40,6 +40,9 @@ class WebhookProvider(ABC):invalid_signature_status: int = 403unconfigured_status: int = 500success_status: int = 202+ # An incarnation that answers 404 to withhold the endpoint's existence sets this False, so the+ # body does not name the reason the status code was chosen to hide.+ explains_rejections: bool = True@abstractmethoddef scheme(self) -> SignatureScheme:diff --git a/posthog/ingress/test/test_pandadoc.py b/posthog/ingress/test/test_pandadoc.pyindex e94fc67e4589..d14e245f2024 100644--- a/posthog/ingress/test/test_pandadoc.py+++ b/posthog/ingress/test/test_pandadoc.py@@ -41,6 +41,18 @@ class TestPandaDocProvider(SimpleTestCase):self.assertEqual(build_pandadoc_provider().verify(request), expected)+ def test_a_disabled_deployment_rejects_a_correctly_signed_body(self) -> None:+ request = RequestFactory().post(+ "/webhooks/pandadoc/",+ data=BODY,+ content_type="application/json",+ headers={"X-PandaDoc-Signature": _signature()},+ )++ provider = build_pandadoc_provider(enabled=lambda: False)++ self.assertEqual(provider.verify(request), VerificationOutcome.INVALID)+def test_a_missing_secret_is_not_configured_rather_than_a_bad_signature(self) -> None:request = RequestFactory().post("/webhooks/pandadoc/", data=BODY, content_type="application/json")diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.pyindex bd40550a86f0..31ad3bd3a7d3 100644--- a/posthog/ingress/test/test_views.py+++ b/posthog/ingress/test/test_views.py@@ -5,6 +5,8 @@ from unittest.mock import Mock, patchfrom django.test import RequestFactory, SimpleTestCase, override_settings+from parameterized import parameterized+from posthog.ingress.github.provider import build_github_providerfrom posthog.ingress.pandadoc.provider import build_pandadoc_providerfrom posthog.ingress.slack.provider import build_slack_provider@@ -57,6 +59,7 @@ class TestWebhookView(SimpleTestCase):response = self._github_view()(request)self.assertEqual(response.status_code, 403)+ self.assertEqual(response.content, b"Invalid signature")self.dispatcher.dispatch.assert_not_called()def test_an_unparseable_body_is_400(self) -> None:@@ -114,6 +117,29 @@ class TestWebhookView(SimpleTestCase):response = build_webhook_view(build_github_provider("posthog"))(request)self.assertEqual(response.status_code, 500)+ self.assertEqual(response.content, b"Webhook not configured")++ @parameterized.expand(+ [+ ("a_bad_signature", SECRET),+ ("a_missing_secret", ""),+ ]+ )+ def test_a_provider_that_withholds_its_existence_answers_an_empty_body(self, _name: str, secret: str) -> None:+ body = b'[{"event":"document_state_changed"}]'+ request = self.factory.post(+ "/webhooks/pandadoc/",+ data=body,+ content_type="application/json",+ headers={"X-PandaDoc-Signature": "0" * 64},+ )++ with override_settings(PANDADOC_WEBHOOK_SECRET=secret):+ response = build_webhook_view(build_pandadoc_provider())(request)++ self.assertEqual(response.status_code, 404)+ self.assertEqual(response.content, b"")+ self.dispatcher.dispatch.assert_not_called()def test_slack_url_verification_echoes_the_challenge_before_dispatch(self) -> None:body = json.dumps({"type": "url_verification", "challenge": "abc123"}).encode()diff --git a/posthog/ingress/views.py b/posthog/ingress/views.pyindex 3e44fabb7e9d..47988586afbd 100644--- a/posthog/ingress/views.py+++ b/posthog/ingress/views.py@@ -34,10 +34,12 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Httif outcome is VerificationOutcome.NOT_CONFIGURED:logger.error("ingress_webhook_not_configured", provider=provider.provider, app=provider.app)observe_delivery(provider=provider.provider, app=provider.app, outcome="not_configured")- return HttpResponse("Webhook not configured", status=provider.unconfigured_status)+ reason = "Webhook not configured" if provider.explains_rejections else ""+ return HttpResponse(reason, status=provider.unconfigured_status)if outcome is not VerificationOutcome.VERIFIED:observe_delivery(provider=provider.provider, app=provider.app, outcome="invalid_signature")- return HttpResponse("Invalid signature", status=provider.invalid_signature_status)+ reason = "Invalid signature" if provider.explains_rejections else ""+ return HttpResponse(reason, status=provider.invalid_signature_status)try:# RecursionError: deeply nested JSON must answer 400, not 500.diff --git a/posthog/urls.py b/posthog/urls.pyindex 4641ce5a1dad..1aa7f392b765 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -143,7 +143,7 @@ urlpatterns = [opt_slash_path("api/revoke_leaked_key", leaked_key.PublicLeakedKeyReport.as_view()),path("api/legal_documents/pandadoc",- csrf_exempt(legal_document_pandadoc_webhook),+ legal_document_pandadoc_webhook,name="legal_document_pandadoc_webhook",),path(diff --git a/products/legal_documents/backend/facade/api.py b/products/legal_documents/backend/facade/api.pyindex c2ce42950b0e..4e76414db849 100644--- a/products/legal_documents/backend/facade/api.py+++ b/products/legal_documents/backend/facade/api.py@@ -19,15 +19,16 @@ from django.utils import timezoneimport structlogfrom posthog.exceptions_capture import capture_exception+from posthog.ingress.contracts import WebhookDeliveryfrom posthog.models.organization import Organizationfrom posthog.ph_client import ph_scoped_capturefrom .. import logic-from ..logic import SIGNED_BAA_ANNOTATION as SIGNED_BAA_ANNOTATION-from ..logic.pandadoc import (- PandaDocError,- verify_webhook_signature as _verify_pandadoc_webhook_signature,+from ..logic import (+ SIGNED_BAA_ANNOTATION as SIGNED_BAA_ANNOTATION,+ webhooks,)+from ..logic.pandadoc import PandaDocErrorfrom ..models import LegalDocumentfrom . import contractsfrom .enums import LegalDocumentStatus@@ -107,11 +108,6 @@ def annotate_signed_baa(queryset: QuerySet[Organization]) -> QuerySet[Organizatireturn logic.annotate_signed_baa(queryset)-def verify_pandadoc_webhook_signature(*, secret: str, body: bytes, signature: str) -> bool:- """Passthrough so the presentation layer never reaches past the facade."""- return _verify_pandadoc_webhook_signature(secret=secret, body=body, signature=signature)--def exists_for_organization_and_type(organization_id: UUID, document_type: str) -> bool:return logic.exists_for_organization_and_type(organization_id, document_type)@@ -208,69 +204,9 @@ def create_document(data: contracts.CreateLegalDocumentInput) -> contracts.Legalreturn _to_dto(document)-def mark_envelope_ready_by_pandadoc_document_id(- *,- pandadoc_document_id: str,- template_id: str,-) -> contracts.LegalDocumentDTO | None:- """- Entry point from the PandaDoc `document.draft` webhook — the envelope- finished template processing and is ready to send. Dispatch the signing- email.-- Idempotent: if the envelope has already been dispatched (row is already- signed, or the send call fails because PandaDoc has moved past draft)- we quietly skip.- """- document = logic.get_by_pandadoc_document_id(pandadoc_document_id)- if document is None:- return None- if not logic.template_id_matches_document(document, template_id):- return None- if document.status == LegalDocumentStatus.SIGNED:- # Envelope already completed — the draft event is a late/replayed- # delivery; nothing left for us to do.- return _to_dto(document)- logic.send_pandadoc_envelope(document)- return _to_dto(document)---def mark_signed_by_pandadoc_document_id(- *,- pandadoc_document_id: str,- template_id: str,-) -> contracts.LegalDocumentDTO | None:- """- Entry point from the PandaDoc `document.completed` webhook. The caller must- have already verified the HMAC signature on the raw body; this function:-- - Looks up the row by the PandaDoc document uuid (no IDOR surface: unknown ids 404).- - Double-checks the template matches the stored document variant, to guard- against misconfigured PandaDoc templates flipping the wrong row.- - Flips status to signed, fires analytics and BAA side effects, and schedules- the signed-PDF archive as a retried background job.-- The signature is recorded as soon as the webhook lands — it is never gated- on the PDF archival, which used to leave the row stuck when a download or- upload failed. Idempotent: an already-signed row returns its DTO without- re-firing side effects.- """- document = logic.get_by_pandadoc_document_id(pandadoc_document_id)- if document is None:- return None- if not logic.template_id_matches_document(document, template_id):- return None- if document.status == LegalDocumentStatus.SIGNED:- return _to_dto(document)- return _to_dto(_mark_signed_and_schedule_archive(document))---def _mark_signed_and_schedule_archive(document: LegalDocument) -> LegalDocument:- document = logic.mark_document_signed(document)- logic.apply_baa_signed_side_effects(document)- logic.fire_legal_document_signed_event(document)- _schedule_pdf_archive(document)- return document+def accept_pandadoc_event(delivery: WebhookDelivery) -> None:+ """The inbound PandaDoc webhook enters legal_documents here, so its consumer needs no internal import."""+ webhooks.accept_pandadoc_event(delivery)def _try_mark_signed_and_schedule_archive(@@ -287,20 +223,10 @@ def _try_mark_signed_and_schedule_archive(return Falselogic.apply_baa_signed_side_effects(document)logic.fire_legal_document_signed_event(document, capture=capture)- _schedule_pdf_archive(document, delay_seconds=delay_seconds)+ logic.schedule_pdf_archive(document, delay_seconds=delay_seconds)return True-def _schedule_pdf_archive(document: LegalDocument, delay_seconds: int = 0) -> None:- # Local import breaks the facade ⇄ tasks import cycle (tasks import the facade).- from ..tasks.tasks import archive_signed_legal_document_pdf # noqa: PLC0415-- document_id = str(document.id)- transaction.on_commit(- lambda: archive_signed_legal_document_pdf.apply_async(args=[document_id], countdown=delay_seconds)- )--def archive_signed_pdf(document_id: UUID) -> None:"""Pull the signed PDF from PandaDoc and write it to object storage, then mark@@ -451,7 +377,7 @@ def reconcile_pending_signatures() -> contracts.LegalDocumentReconcileResult:archives_requeued = 0for document in logic.list_signed_documents_missing_pdf(exclude_ids=signed_this_run):try:- _schedule_pdf_archive(document, delay_seconds=scheduled_archives)+ logic.schedule_pdf_archive(document, delay_seconds=scheduled_archives)archives_requeued += 1scheduled_archives += 1except Exception as exc:diff --git a/products/legal_documents/backend/logic/__init__.py b/products/legal_documents/backend/logic/__init__.pyindex 7704d6759944..ac5e0b6bde1f 100644--- a/products/legal_documents/backend/logic/__init__.py+++ b/products/legal_documents/backend/logic/__init__.py@@ -12,6 +12,7 @@ from datetime import timedeltafrom uuid import UUIDfrom django.conf import settings+from django.db import transactionfrom django.db.models import Exists, OuterRef, QuerySetfrom django.utils import timezone@@ -71,7 +72,7 @@ def template_id_matches_document(document: LegalDocument, template_id: str) -> b"""expected = _pandadoc_template_id_for(document.document_type)# If the env var isn't configured we skip the check rather than block every- # webhook — verify_webhook_signature already proves provenance.+ # webhook, because the HMAC check on the raw body already proves provenance.return not expected or expected == template_id@@ -160,12 +161,6 @@ def create_document()-def mark_document_signed(document: LegalDocument) -> LegalDocument:- document.status = LegalDocument.Status.SIGNED- document.save(update_fields=["status", "updated_at"])- return document--def try_mark_signed_if_pending(document: LegalDocument) -> bool:"""Conditional UPDATE that re-asserts the row was still `submitted_for_signature`@@ -174,6 +169,9 @@ def try_mark_signed_if_pending(document: LegalDocument) -> bool:concurrent `document.completed` webhook may have already signed the row.Losing that race must skip the caller's side effects (BAA opt-out email)rather than re-fire them, so the caller only proceeds when this returns True.++ The inbound webhook takes the same route: PandaDoc sends no delivery id, so+ ingress cannot dedup and two deliveries reach the handler as equals."""updated = LegalDocument.objects.filter(id=document.id, status=LegalDocument.Status.SUBMITTED_FOR_SIGNATURE).update(status=LegalDocument.Status.SIGNED, updated_at=timezone.now()@@ -187,7 +185,18 @@ def mark_signed_pdf_stored(document: LegalDocument) -> LegalDocument:return document-# PandaDoc status string for a fully-signed envelope. Mirrors the webhook layer.+def schedule_pdf_archive(document: LegalDocument, delay_seconds: int = 0) -> None:+ # Local import breaks the logic ⇄ tasks import cycle (tasks import the facade,+ # which imports this module).+ from ..tasks.tasks import archive_signed_legal_document_pdf # noqa: PLC0415++ document_id = str(document.id)+ transaction.on_commit(+ lambda: archive_signed_legal_document_pdf.apply_async(args=[document_id], countdown=delay_seconds)+ )+++# PandaDoc status string for a fully-signed envelope.PANDADOC_COMPLETED_STATUS = "document.completed"# PandaDoc status string for an envelope stuck before its signing email ever wentdiff --git a/products/legal_documents/backend/logic/pandadoc.py b/products/legal_documents/backend/logic/pandadoc.pyindex 88313a47b92b..6cc9947631dd 100644--- a/products/legal_documents/backend/logic/pandadoc.py+++ b/products/legal_documents/backend/logic/pandadoc.py@@ -7,14 +7,11 @@ We hit these endpoints:POST /public/v1/documents/{id}/send -> email the signing envelopePATCH /public/v1/documents/{id}/status -> move an envelope to voided (no longer signable)-Plus one helper for verifying the HMAC signature on inbound webhooks. Keeping-this file free of Django/DRF imports so it's straightforward to unit test.+Keeping this file free of Django/DRF imports so it's straightforward to unit test."""from __future__ import annotations-import hmac-import hashlibfrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom dataclasses import dataclass@@ -314,17 +311,3 @@ class PandaDocClient:def _serialize_recipient(r: PandaDocRecipient) -> dict[str, Any]:return {"email": r.email, "role": str(r.role)}---def verify_webhook_signature(*, secret: str, body: bytes, signature: str) -> bool:- """- PandaDoc signs webhooks with HMAC-SHA256 of the raw body using the shared secret- configured in the PandaDoc dashboard. They expose the hex digest as a query parameter- (`?signature=...`) and as the `X-PandaDoc-Signature` header on modern deliveries.-- Both the header and query-param forms are accepted — we just compare constants.- """- if not secret or not signature:- return False- expected = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()- return hmac.compare_digest(expected, signature)diff --git a/products/legal_documents/backend/logic/webhooks.py b/products/legal_documents/backend/logic/webhooks.pynew file mode 100644index 000000000000..a2f318105be3--- /dev/null+++ b/products/legal_documents/backend/logic/webhooks.py@@ -0,0 +1,108 @@+"""Inbound PandaDoc deliveries for the signing flow.++Reached from the facade after ingress verified the HMAC over the raw body and split a batched+body into one delivery per event. No HTTP in here: ingress owns the request and the receipt, so+a state PandaDoc sends that means nothing here is a log line rather than a status code.+"""++from __future__ import annotations++from typing import Any++import structlog++from posthog.ingress.contracts import WebhookDelivery++from .. import logic+from ..models import LegalDocument++logger = structlog.get_logger(__name__)+++def _mark_envelope_ready(*, pandadoc_document_id: str, template_id: str) -> LegalDocument | None:+ """The envelope finished template processing and is ready to send, so dispatch the signing email.++ Idempotent: if the envelope has already been dispatched (row is already signed, or the send+ call fails because PandaDoc has moved past draft) we quietly skip.+ """+ document = logic.get_by_pandadoc_document_id(pandadoc_document_id)+ if document is None:+ return None+ if not logic.template_id_matches_document(document, template_id):+ return None+ if document.status == LegalDocument.Status.SIGNED:+ # The envelope already completed, so this draft event is a late or replayed delivery+ # with nothing left to do.+ return document+ logic.send_pandadoc_envelope(document)+ return document+++def _mark_signed(*, pandadoc_document_id: str, template_id: str) -> LegalDocument | None:+ """Record the signature for a completed envelope.++ - Looks up the row by the PandaDoc document uuid (no IDOR surface: unknown ids are a no-op).+ - Double-checks the template matches the stored document variant, to guard against+ misconfigured PandaDoc templates flipping the wrong row.+ - Claims the row with a conditional flip to signed, then fires analytics and BAA side+ effects and schedules the signed-PDF archive as a retried background job.++ The signature is recorded as soon as the delivery lands. It is never gated on the PDF+ archival, which used to leave the row stuck when a download or upload failed. Idempotent:+ a delivery that does not win the claim returns the row without re-firing side effects.+ """+ document = logic.get_by_pandadoc_document_id(pandadoc_document_id)+ if document is None:+ return None+ if not logic.template_id_matches_document(document, template_id):+ return None+ # PandaDoc sends no delivery id, so ingress cannot dedup. Two `document.completed` deliveries+ # can both read the row as pending, and only this conditional update decides which one owns+ # the side effects.+ if not logic.try_mark_signed_if_pending(document):+ current = logic.get_by_pandadoc_document_id(pandadoc_document_id)+ if current is None:+ return None+ if current.status == LegalDocument.Status.SIGNED:+ logger.info("pandadoc_webhook_already_signed", pandadoc_document_id=pandadoc_document_id)+ else:+ logger.warning(+ "pandadoc_webhook_completed_for_unexpected_status",+ pandadoc_document_id=pandadoc_document_id,+ status=current.status,+ )+ return current+ # The side effects read the status off the instance the update never touched.+ document.status = LegalDocument.Status.SIGNED+ logic.apply_baa_signed_side_effects(document)+ logic.fire_legal_document_signed_event(document)+ logic.schedule_pdf_archive(document)+ return document+++def accept_pandadoc_event(delivery: WebhookDelivery) -> None:+ """Apply one verified PandaDoc delivery to the document it names."""+ data: Any = delivery.payload.get("data") or {}+ if isinstance(data, list):+ data = data[0] if data else {}+ if not isinstance(data, dict):+ return++ event_status = data.get("status")+ pandadoc_document_id = data.get("id") or ""+ template_id = (data.get("template") or {}).get("id") if isinstance(data.get("template"), dict) else ""++ if not pandadoc_document_id:+ logger.warning("pandadoc_webhook_event_missing_id", status=event_status)+ return++ if event_status == logic.PANDADOC_DRAFT_STATUS:+ document = _mark_envelope_ready(pandadoc_document_id=pandadoc_document_id, template_id=template_id or "")+ elif event_status == logic.PANDADOC_COMPLETED_STATUS:+ document = _mark_signed(pandadoc_document_id=pandadoc_document_id, template_id=template_id or "")+ else:+ logger.info("pandadoc_webhook_state_ignored", status=event_status, pandadoc_document_id=pandadoc_document_id)+ return++ if document is None:+ logger.info("pandadoc_webhook_no_matching_document", pandadoc_document_id=pandadoc_document_id)diff --git a/products/legal_documents/backend/presentation/webhook.py b/products/legal_documents/backend/presentation/webhook.pyindex 60baf1864e75..8f742679ca13 100644--- a/products/legal_documents/backend/presentation/webhook.py+++ b/products/legal_documents/backend/presentation/webhook.py@@ -1,132 +1,22 @@-import json+"""The inbound PandaDoc webhook for legal documents.-from django.conf import settings+Ingress verifies the HMAC over the raw body and fans each batched event out to+`legal_documents_signatures` in `webhook_consumers.py`. A bad signature answers 404 rather+than 403, so an attacker cannot tell a wrong secret from an unknown route.-import structlog-from drf_spectacular.utils import OpenApiTypes, extend_schema-from rest_framework import status-from rest_framework.decorators import api_view, authentication_classes, permission_classes-from rest_framework.request import Request-from rest_framework.response import Response+There is no per-IP throttle: PandaDoc delivers from a small shared pool of egress IPs, so+keying on them drops legitimate deliveries, and the HMAC check already proves provenance.+"""from posthog.cloud_utils import is_cloud, is_dev_mode-from posthog.exceptions_capture import capture_exception+from posthog.ingress.pandadoc.provider import build_pandadoc_provider+from posthog.ingress.views import build_webhook_view-from ..facade import api-logger = structlog.get_logger(__name__)+def _pandadoc_integration_is_served() -> bool:+ # Self-hosted deployments do not run the PandaDoc integration, and the endpoint must never+ # leak that it exists. Dev mode keeps it on for local testing.+ return is_cloud() or is_dev_mode()-# PandaDoc state-change events we care about. Everything else is ignored.-_PANDADOC_STATE_CHANGED_EVENT = "document_state_changed"--# `draft` fires once PandaDoc has finished processing the template and the-# envelope is ready to be sent to the signer — this is our cue to dispatch-# the signing email.-_PANDADOC_DRAFT_STATUS = "document.draft"-# `completed` fires once every recipient has signed.-_PANDADOC_COMPLETED_STATUS = "document.completed"---@extend_schema(- tags=["legal_documents"],- operation_id="legal_document_pandadoc_webhook",- request=OpenApiTypes.OBJECT,- responses={200: OpenApiTypes.OBJECT, 204: OpenApiTypes.OBJECT, 400: OpenApiTypes.OBJECT, 404: OpenApiTypes.OBJECT},- description=(- "PandaDoc webhook receiver. Authenticates via HMAC-SHA256 over the raw "- "body. Handles two `document_state_changed` events: `document.draft` "- "dispatches the signing email, and `document.completed` records the "- "signature and schedules the signed-PDF archive as a background job. "- "Returns 200 when an event applied, 204 when the request is valid but "- "the document doesn't live on this cloud instance (PandaDoc fans the "- "webhook out to every instance, only one of which owns the row), "- "404 on a bad signature, 400 on an unparseable body. No per-IP throttle: "- "PandaDoc delivers from a small shared pool of egress IPs, so keying on "- "them drops legitimate deliveries; the HMAC check already proves "- "provenance."- ),-)-@api_view(["POST"])-@authentication_classes([])-@permission_classes([])-def legal_document_pandadoc_webhook(request: Request) -> Response:- if not (is_cloud() or is_dev_mode()):- # Self-hosted deployments don't run the PandaDoc integration — never- # leak that this endpoint exists. Dev mode keeps it on for local testing.- return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)-- raw_body = request.body or b""- signature = request.headers.get("X-PandaDoc-Signature") or request.query_params.get("signature") or ""- if not api.verify_pandadoc_webhook_signature(- secret=settings.PANDADOC_WEBHOOK_SECRET, body=raw_body, signature=signature- ):- # Return 404 (not 403) so an attacker can't distinguish "wrong secret"- # from "unknown route" via timing or status code.- return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)-- try:- events = json.loads(raw_body.decode("utf-8"))- except (ValueError, UnicodeDecodeError) as exc:- logger.warning("pandadoc_webhook_invalid_body", error=str(exc))- capture_exception(exc)- return Response({"detail": "Invalid body."}, status=status.HTTP_400_BAD_REQUEST)-- # PandaDoc batches multiple events in a single webhook delivery.- if not isinstance(events, list):- events = [events]-- processed_any = False-- for event in events:- if not isinstance(event, dict):- continue- if event.get("event") != _PANDADOC_STATE_CHANGED_EVENT:- continue- data = event.get("data") or {}- if isinstance(data, list):- data = data[0] if data else {}- if not isinstance(data, dict):- continue-- event_status = data.get("status")- pandadoc_document_id = data.get("id") or ""- template_id = (data.get("template") or {}).get("id") if isinstance(data.get("template"), dict) else ""-- if not pandadoc_document_id:- logger.warning("pandadoc_webhook_event_missing_id", status=event_status)- continue-- if event_status == _PANDADOC_DRAFT_STATUS:- # Envelope just finished template processing — dispatch the send.- dto = api.mark_envelope_ready_by_pandadoc_document_id(- pandadoc_document_id=pandadoc_document_id,- template_id=template_id or "",- )- if dto is None:- logger.info("pandadoc_webhook_no_matching_document", pandadoc_document_id=pandadoc_document_id)- continue- processed_any = True- continue-- if event_status == _PANDADOC_COMPLETED_STATUS:- # Record the signature and schedule the PDF archive as a background- # job — the signature is never gated on the download succeeding.- dto = api.mark_signed_by_pandadoc_document_id(- pandadoc_document_id=pandadoc_document_id,- template_id=template_id or "",- )- if dto is None:- logger.info("pandadoc_webhook_no_matching_document", pandadoc_document_id=pandadoc_document_id)- continue- processed_any = True- continue-- logger.info("pandadoc_webhook_state_ignored", status=event_status, pandadoc_document_id=pandadoc_document_id)-- if processed_any:- return Response({"status": "ok"}, status=status.HTTP_200_OK)-- # Nothing applied to this instance — 2xx so PandaDoc doesn't retry, since- # the sibling instance that owns the row will handle its own copy.- return Response(status=status.HTTP_204_NO_CONTENT)+legal_document_pandadoc_webhook = build_webhook_view(build_pandadoc_provider(enabled=_pandadoc_integration_is_served))diff --git a/products/legal_documents/backend/tests/test_api.py b/products/legal_documents/backend/tests/test_api.pyindex 206d100782e8..991bc6a943d0 100644--- a/products/legal_documents/backend/tests/test_api.py+++ b/products/legal_documents/backend/tests/test_api.py@@ -1,7 +1,7 @@import hmacimport jsonimport hashlib-from contextlib import contextmanager+from contextlib import contextmanager, nullcontextfrom datetime import timedeltafrom typing import Any@@ -575,7 +575,7 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):):with self.captureOnCommitCallbacks(execute=True):response = self._post_raw(body, self._sign(body))- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)self.document.refresh_from_db()self.assertEqual(self.document.status, "signed")self.assertTrue(self.document.signed_pdf_stored)@@ -589,8 +589,8 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):def test_archive_failure_leaves_row_signed_but_unarchived(self) -> None:# The whole point of the decoupling: a PDF download failure no longer- # blocks the signature. The row is signed and the webhook returns 200;- # only signed_pdf_stored stays False for the reconciliation sweep to fix.+ # blocks the signature. The row is signed and the webhook still accepts the+ # delivery; only signed_pdf_stored stays False for the reconciliation sweep to fix.from products.legal_documents.backend.logic import pandadoc as pandadoc_modulebody = json.dumps(self._completed_payload()).encode("utf-8")@@ -607,7 +607,7 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):with self.assertRaises(Retry), self.captureOnCommitCallbacks(execute=True):response = self._post_raw(body, self._sign(body))- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)stream_mock.assert_called_once_with(document_id="doc_123")write_mock.assert_not_called()self.document.refresh_from_db()@@ -619,16 +619,17 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):with self._override():response = self._post_raw(body, "not-the-right-signature")self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(response.content, b"")self.document.refresh_from_db()self.assertEqual(self.document.status, "submitted_for_signature")- def test_unknown_document_id_returns_204(self) -> None:+ def test_unknown_document_id_is_accepted(self) -> None:# Sibling cloud instance scenario: signature is valid but the document# belongs to a different instance. 2xx so PandaDoc doesn't retry.body = json.dumps(self._completed_payload(pandadoc_document_id="unknown")).encode("utf-8")with self._override():response = self._post_raw(body, self._sign(body))- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)@parameterized.expand([("document.sent",), ("document.viewed",), ("document.error",)])def test_uninteresting_state_event_is_noop(self, event_status: str) -> None:@@ -638,10 +639,10 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):body = json.dumps(payload).encode("utf-8")with (self._override(),- patch("products.legal_documents.backend.presentation.webhook.logger") as logger_mock,+ patch("products.legal_documents.backend.logic.webhooks.logger") as logger_mock,):response = self._post_raw(body, self._sign(body))- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)self.document.refresh_from_db()self.assertEqual(self.document.status, "submitted_for_signature")logger_mock.info.assert_any_call(@@ -655,7 +656,7 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.send_document") as send_mock,):response = self._post_raw(body, self._sign(body))- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)send_mock.assert_called_once()self.assertEqual(send_mock.call_args.kwargs["document_id"], "doc_123")@@ -671,8 +672,8 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):),):response = self._post_raw(body, self._sign(body))- # Endpoint still 2xx — we don't want PandaDoc to retry.- self.assertEqual(response.status_code, status.HTTP_200_OK)+ # Endpoint still 2xx, because we don't want PandaDoc to retry.+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)def test_draft_event_for_already_signed_document_is_a_noop(self) -> None:self.document.status = "signed"@@ -684,7 +685,7 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.send_document") as send_mock,):response = self._post_raw(body, self._sign(body))- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)send_mock.assert_not_called()def test_template_mismatch_does_not_flip_row(self) -> None:@@ -693,7 +694,7 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):body = json.dumps(self._completed_payload(template_id=self.BAA_TEMPLATE_ID)).encode("utf-8")with self._override():response = self._post_raw(body, self._sign(body))- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)self.document.refresh_from_db()self.assertEqual(self.document.status, "submitted_for_signature")@@ -703,7 +704,28 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):response = self._post_raw(body, self._sign(body))self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- def test_replayed_completed_event_skips_side_effects(self) -> None:+ @contextmanager+ def _read_the_row_before_the_other_delivery_committed(self):+ # Only the first read is stale, so the handler's re-read after a lost claim sees the row.+ stale = LegalDocument.objects.get(id=self.document.id)+ stale.status = LegalDocument.Status.SUBMITTED_FOR_SIGNATURE+ original = logic.get_by_pandadoc_document_id+ pending_reads = [stale]++ def lookup(pandadoc_document_id: str) -> LegalDocument | None:+ return pending_reads.pop(0) if pending_reads else original(pandadoc_document_id)++ with patch("products.legal_documents.backend.logic.get_by_pandadoc_document_id", side_effect=lookup):+ yield++ @parameterized.expand(+ [+ ("a_later_replay", False),+ # PandaDoc sends no delivery id, so nothing upstream collapses the two.+ ("a_concurrent_delivery_that_read_the_row_as_pending", True),+ ]+ )+ def test_a_second_completed_event_skips_side_effects(self, _name: str, stale_read: bool) -> None:@contextmanagerdef fake_stream_cm(*, document_id): # noqa: ARG001yield object()@@ -719,26 +741,29 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):patch("products.legal_documents.backend.logic.object_storage.write_stream"),):first = self._post_raw(body, self._sign(body))- self.assertEqual(first.status_code, status.HTTP_200_OK)+ self.assertEqual(first.status_code, status.HTTP_202_ACCEPTED)self.document.refresh_from_db()self.assertEqual(self.document.status, "signed")- # Replay: must not re-stream the PDF, re-upload, or re-fire analytics.- # PandaDoc retries / cross-instance fan-out both land here.+ # Second delivery: must not re-stream the PDF, re-upload, re-fire analytics, or re-apply+ # the BAA side effects. PandaDoc retries / cross-instance fan-out both land here.replay_body = json.dumps(self._completed_payload()).encode("utf-8")with (self._override(),+ self._read_the_row_before_the_other_delivery_committed() if stale_read else nullcontext(),patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.stream_document") as stream_spy,patch("products.legal_documents.backend.logic.object_storage.write_stream") as write_spy,patch("products.legal_documents.backend.logic.fire_legal_document_signed_event") as event_spy,+ patch("products.legal_documents.backend.logic.apply_baa_signed_side_effects") as baa_spy,):response = self._post_raw(replay_body, self._sign(replay_body))- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)stream_spy.assert_not_called()write_spy.assert_not_called()event_spy.assert_not_called()+ baa_spy.assert_not_called()def _swap_to_baa_document(self) -> None:"""The default fixture is a DPA. For BAA-side-effect tests, retarget it."""@@ -775,7 +800,7 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):with self._override(), self._fake_pdf_pipeline():response = self._post_raw(body, self._sign(body))- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)self.organization.refresh_from_db()self.assertFalse(getattr(self.organization, flag))@@ -789,7 +814,7 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):with self._override(), self._fake_pdf_pipeline():response = self._post_raw(body, self._sign(body))- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)self.organization.refresh_from_db()self.assertTrue(getattr(self.organization, flag))@@ -809,7 +834,7 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):):response = self._post_raw(body, self._sign(body))- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)email_cls.assert_called_once()kwargs = email_cls.call_args.kwargsself.assertEqual(kwargs["template_name"], "baa_signed_ai_disabled")@@ -833,7 +858,7 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):):response = self._post_raw(body, self._sign(body))- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)email_cls.assert_not_called()self.organization.refresh_from_db()# Opt-out still happens even when there are no owners to notify.diff --git a/products/legal_documents/backend/tests/test_pandadoc.py b/products/legal_documents/backend/tests/test_pandadoc.pyindex 6685412b9657..bfe076074361 100644--- a/products/legal_documents/backend/tests/test_pandadoc.py+++ b/products/legal_documents/backend/tests/test_pandadoc.py@@ -1,6 +1,3 @@-import hmac-import hashlib-from unittest.mock import MagicMock, patchfrom django.test import TestCase, override_settings@@ -188,19 +185,6 @@ class TestPandaDocClient(TestCase):with self.assertRaises(pandadoc.PandaDocError):client.send_document(document_id="doc_123", subject="s", message="m")- def test_verify_webhook_signature_accepts_valid_hmac(self) -> None:- secret = "shhh"- body = b'{"event": "document_state_changed"}'- signature = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()- self.assertTrue(pandadoc.verify_webhook_signature(secret=secret, body=body, signature=signature))-- def test_verify_webhook_signature_rejects_bad_hmac(self) -> None:- self.assertFalse(pandadoc.verify_webhook_signature(secret="shhh", body=b"{}", signature="0" * 64))-- def test_verify_webhook_signature_rejects_empty_inputs(self) -> None:- self.assertFalse(pandadoc.verify_webhook_signature(secret="", body=b"{}", signature="abc"))- self.assertFalse(pandadoc.verify_webhook_signature(secret="k", body=b"{}", signature=""))-def test_serialize_recipient_emits_flat_email_and_role_for_each_role(self) -> None:# Both the Client signer and the PostHog CC serialize to the same# minimal shape; tokens carry all template content.diff --git a/products/legal_documents/backend/webhook_consumers.py b/products/legal_documents/backend/webhook_consumers.pynew file mode 100644index 000000000000..b28701f88285--- /dev/null+++ b/products/legal_documents/backend/webhook_consumers.py@@ -0,0 +1,25 @@+"""Legal documents' consumer on the PandaDoc endpoint.++The registry imports this module on the first delivery, so it stays cheap: the handler defers+the facade import, which drags the models and the PandaDoc client in.+"""++from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery+from posthog.ingress.pandadoc.provider import PANDADOC_EVENT_TYPES+++def _run_legal_documents(delivery: WebhookDelivery) -> None:+ from products.legal_documents.backend.facade.api import accept_pandadoc_event # noqa: PLC0415++ accept_pandadoc_event(delivery)+++WEBHOOK_CONSUMERS = (+ WebhookConsumer(+ name="legal_documents_signatures",+ provider="pandadoc",+ app="default",+ event_types=PANDADOC_EVENT_TYPES,+ handler=_run_legal_documents,+ ),+)diff --git a/products/legal_documents/turbo.json b/products/legal_documents/turbo.jsonindex a765b03ee90e..5ad97403d074 100644--- a/products/legal_documents/turbo.json+++ b/products/legal_documents/turbo.json@@ -6,6 +6,7 @@"backend/facade/**","backend/presentation/**","backend/routes.py",+ "backend/webhook_consumers.py","backend/tasks/**","backend/models.py","backend/migrations/**"