: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
feat: github webhook (#57476)
Alex Vc8e54df8bd39
diff --git a/posthog/urls.py b/posthog/urls.pyindex daa66ffac883..4316a8ef52c5 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -56,7 +56,6 @@ from products.signals.backend import views as signals_viewsfrom products.signals.backend.views import SignalUserAutonomyConfigView as signals_user_autonomy_viewfrom products.slack_app.backend.api import posthog_code_event_handler, posthog_code_interactivity_handlerfrom products.surveys.backend.api.survey import public_survey_page-from products.tasks.backend.webhooks import github_pr_webhook as _github_pr_webhookfrom .utils import opt_slash_path, render_templatefrom .views import (@@ -89,32 +88,44 @@ else:@csrf_exemptdef github_webhook(request: HttpRequest) -> HttpResponse:- """GitHub App webhook fan-out.+ """Unified GitHub App webhook dispatcher.- Routes issues/issue_comment events to conversations and everything else- (pull_request, etc.) to the tasks PR webhook. Both handlers perform their- own signature verification using the shared GITHUB_WEBHOOK_SECRET.+ Verifies the HMAC-SHA256 signature once, parses JSON once, then routes+ by ``X-GitHub-Event`` to the appropriate product handler."""- if request.method == "POST":- event_type = request.headers.get("X-GitHub-Event")- if event_type in ("issues", "issue_comment"):- import json-- from products.conversations.backend.api.github_events import dispatch_github_event- from products.tasks.backend.webhooks import get_github_webhook_secret, verify_github_signature-- secret = get_github_webhook_secret()- if not secret:- return HttpResponse("Webhook not configured", status=500)- signature = request.headers.get("X-Hub-Signature-256")- if not verify_github_signature(request.body, signature, secret):- return HttpResponse("Invalid signature", status=403)- try:- payload = json.loads(request.body)- except json.JSONDecodeError:- return HttpResponse("Invalid JSON", status=400)- return dispatch_github_event(request, event_type, payload)- return _github_pr_webhook(request)+ import json++ from products.tasks.backend.webhooks import get_github_webhook_secret, verify_github_signature++ if request.method != "POST":+ return HttpResponse(status=405)++ secret = get_github_webhook_secret()+ if not secret:+ return HttpResponse("Webhook not configured", status=500)++ signature = request.headers.get("X-Hub-Signature-256")+ if not verify_github_signature(request.body, signature, secret):+ return HttpResponse("Invalid signature", status=403)++ try:+ payload = json.loads(request.body)+ except json.JSONDecodeError:+ return HttpResponse("Invalid JSON", status=400)++ event_type = request.headers.get("X-GitHub-Event", "")++ if event_type in ("issues", "issue_comment"):+ from products.conversations.backend.api.github_events import dispatch_github_event++ return dispatch_github_event(request, event_type, payload)++ if event_type == "pull_request":+ from products.tasks.backend.webhooks import handle_pull_request_event++ return handle_pull_request_event(payload)++ return HttpResponse(status=200)@requires_csrf_token@@ -361,6 +372,7 @@ urlpatterns = [opt_slash_path("slack/event-callback", posthog_code_event_handler),# GitHub App webhook — fans out to tasks (PRs) and conversations (issues)opt_slash_path("webhooks/github/pr", github_webhook),+ opt_slash_path("webhooks/github", github_webhook),# Message preferencespath("messaging-preferences/<str:token>/", preferences_page, name="message_preferences"),opt_slash_path("messaging-preferences/update", update_preferences, name="message_preferences_update"),diff --git a/products/conversations/backend/api/tests/test_github_webhook.py b/products/conversations/backend/api/tests/test_github_webhook.pyindex ab663e0f4d36..991c533be95c 100644--- a/products/conversations/backend/api/tests/test_github_webhook.py+++ b/products/conversations/backend/api/tests/test_github_webhook.py@@ -48,7 +48,7 @@ WEBHOOK_SECRET = "test-webhook-secret"class TestDispatchGithubEvent(BaseTest):- """Tests for dispatch_github_event called directly (as github_pr_webhook does)."""+ """Tests for dispatch_github_event called directly (as github_webhook does)."""def setUp(self):super().setUp()diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex b74a634cfd7a..5e063e14efc5 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patchfrom django.test import TestCase+from parameterized import parameterizedfrom rest_framework.test import APIClientfrom posthog.models.integration import Integration@@ -389,17 +390,36 @@ class TestFindTaskRun(TestCase):class TestGitHubWebhookFanout(TestCase):- """Verify that issues/issue_comment events on webhooks/github/pr are- routed to the conversations dispatch_github_event function."""+ """Verify that the unified ``github_webhook`` dispatcher routes events+ to the correct product handler. Tests both ``/webhooks/github/pr/``+ (legacy) and ``/webhooks/github/`` (new unified URL)."""organization: ClassVar[Organization]team: ClassVar[Team]+ user: ClassVar[User]+ task: ClassVar[Task]+ task_run: ClassVar[TaskRun]integration: ClassVar[Integration]@classmethoddef setUpTestData(cls):cls.organization = Organization.objects.create(name="Fanout Org")cls.team = Team.objects.create(organization=cls.organization, name="Fanout Team")+ cls.user = User.objects.create(email="[email protected]", distinct_id="fanout-1")+ cls.task = Task.objects.create(+ team=cls.team,+ created_by=cls.user,+ title="Fanout Task",+ description="",+ origin_product=Task.OriginProduct.USER_CREATED,+ repository="myorg/myrepo",+ )+ cls.task_run = TaskRun.objects.create(+ task=cls.task,+ team=cls.team,+ status=TaskRun.Status.COMPLETED,+ output={"pr_url": "https://github.com/myorg/myrepo/pull/99"},+ )cls.integration = Integration.objects.create(team=cls.team,kind="github",@@ -418,11 +438,13 @@ class TestGitHubWebhookFanout(TestCase):self.client = APIClient()self.webhook_secret = "test-webhook-secret"- def _make_request(self, payload: dict, event_type: str = "issues", delivery_id: str = "del-1"):+ def _make_request(+ self, payload: dict, event_type: str = "issues", delivery_id: str = "del-1", url: str = "/webhooks/github/pr/"+ ):payload_bytes = json.dumps(payload).encode("utf-8")signature = generate_github_signature(payload_bytes, self.webhook_secret)return self.client.post(- "/webhooks/github/pr/",+ url,data=payload_bytes,content_type="application/json",headers={@@ -432,9 +454,15 @@ class TestGitHubWebhookFanout(TestCase):},)+ @parameterized.expand(+ [+ ("legacy_url", "/webhooks/github/pr/"),+ ("unified_url", "/webhooks/github/"),+ ]+ )@patch("products.conversations.backend.api.github_events.process_github_event")@patch("products.tasks.backend.webhooks.get_github_webhook_secret")- def test_issues_event_dispatched_to_conversations(self, mock_secret, mock_task):+ def test_issues_event_dispatched_to_conversations(self, _name, url, mock_secret, mock_task):mock_secret.return_value = self.webhook_secretmock_task.delay = MagicMock()@@ -446,7 +474,7 @@ class TestGitHubWebhookFanout(TestCase):"sender": {"login": "dev"},}- response = self._make_request(payload, event_type="issues")+ response = self._make_request(payload, event_type="issues", url=url)self.assertEqual(response.status_code, 202)mock_task.delay.assert_called_once()@@ -494,3 +522,58 @@ class TestGitHubWebhookFanout(TestCase):self.assertEqual(response.status_code, 200)mock_task.delay.assert_not_called()++ @parameterized.expand(+ [+ ("legacy_url", "/webhooks/github/pr/"),+ ("unified_url", "/webhooks/github/"),+ ]+ )+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_pull_request_routed(self, _name, url, mock_capture, mock_secret):+ mock_secret.return_value = self.webhook_secret++ payload = {+ "action": "closed",+ "pull_request": {+ "html_url": "https://github.com/myorg/myrepo/pull/99",+ "merged": True,+ },+ }++ response = self._make_request(payload, event_type="pull_request", url=url)++ self.assertEqual(response.status_code, 200)+ mock_capture.assert_called_once()+ self.assertEqual(mock_capture.call_args[1]["event"], "pr_merged")++ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")+ def test_unified_url_unknown_event_returns_200(self, mock_secret):+ mock_secret.return_value = self.webhook_secret++ payload = {"action": "created", "ref": "refs/heads/main"}+ response = self._make_request(payload, event_type="push", url="/webhooks/github/")++ self.assertEqual(response.status_code, 200)++ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")+ def test_unified_url_bad_signature_returns_403(self, mock_secret):+ mock_secret.return_value = self.webhook_secret++ payload_bytes = json.dumps({"action": "opened"}).encode("utf-8")+ response = self.client.post(+ "/webhooks/github/",+ data=payload_bytes,+ content_type="application/json",+ headers={+ "x-hub-signature-256": "sha256=invalid",+ "x-github-event": "issues",+ },+ )++ self.assertEqual(response.status_code, 403)++ def test_unified_url_get_returns_405(self):+ response = self.client.get("/webhooks/github/")+ self.assertEqual(response.status_code, 405)diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex 5bdea517a9fa..ee1da6eeb408 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -1,10 +1,8 @@import hmac-import jsonimport uuidimport hashlib-from django.http import HttpRequest, HttpResponse-from django.views.decorators.csrf import csrf_exempt+from django.http import HttpResponseimport structlog@@ -71,51 +69,11 @@ def get_github_webhook_secret() -> str | None:return secret if secret else None-@csrf_exempt-def github_pr_webhook(request: HttpRequest) -> HttpResponse:- """- Handle GitHub pull_request webhook events.-- This endpoint:- 1. Validates the HMAC-SHA256 signature from GitHub- 2. Parses pull_request events (opened, closed, merged)- 3. Finds TaskRun by matching pr_url in output field- 4. Emits console log events and analytics-- Expected events:- - pull_request.opened → log "PR created"- - pull_request.closed with merged=true → log "PR merged"- - pull_request.closed with merged=false → log "PR closed"- """- if request.method != "POST":- return HttpResponse(status=405)-- webhook_secret = get_github_webhook_secret()- if not webhook_secret:- logger.error(- "github_pr_webhook_no_secret",- message="GITHUB_WEBHOOK_SECRET not configured",- )- return HttpResponse("Webhook not configured", status=500)-- signature = request.headers.get("X-Hub-Signature-256")- if not verify_github_signature(request.body, signature, webhook_secret):- logger.warning(- "github_pr_webhook_invalid_signature",- has_signature=bool(signature),- )- return HttpResponse("Invalid signature", status=403)-- try:- payload = json.loads(request.body)- except json.JSONDecodeError:- return HttpResponse("Invalid JSON", status=400)-- event_type = request.headers.get("X-GitHub-Event")- if event_type != "pull_request":- # Not a PR event, acknowledge but don't process, shouldnt happen becuase of github app permissions- return HttpResponse(status=200)+def handle_pull_request_event(payload: dict) -> HttpResponse:+ """Process a pre-verified pull_request webhook event.+ Called from ``posthog.urls.github_webhook`` (unified dispatcher).+ """action = payload.get("action")pull_request = payload.get("pull_request", {})pr_url = pull_request.get("html_url")@@ -136,7 +94,6 @@ def github_pr_webhook(request: HttpRequest) -> HttpResponse:event_action = "closed"analytics_event = "pr_closed"else:- # Other actions (reopened, edited, etc.) - acknowledge but don't processlogger.debug("github_pr_webhook_ignored_action", action=action, pr_url=pr_url)return HttpResponse(status=200)