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: use existing webhook url for support (#57455)

Alex V6313b80e2c04
diff --git a/posthog/urls.py b/posthog/urls.py
index 0e21a291e5e5..daa66ffac883 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -56,7 +56,7 @@ from products.signals.backend import views as signals_views
from products.signals.backend.views import SignalUserAutonomyConfigView as signals_user_autonomy_view
from products.slack_app.backend.api import posthog_code_event_handler, posthog_code_interactivity_handler
from products.surveys.backend.api.survey import public_survey_page
-from products.tasks.backend.webhooks import github_pr_webhook
+from products.tasks.backend.webhooks import github_pr_webhook as _github_pr_webhook
from .utils import opt_slash_path, render_template
from .views import (
@@ -87,6 +87,36 @@ else:
extend_api_router()
+@csrf_exempt
+def github_webhook(request: HttpRequest) -> HttpResponse:
+ """GitHub App webhook fan-out.
+
+ 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.
+ """
+ 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)
+
+
@requires_csrf_token
def handler500(request):
"""
@@ -329,8 +359,8 @@ urlpatterns = [
path("uploaded_media/<str:image_uuid>", uploaded_media.download),
opt_slash_path("slack/interactivity-callback", posthog_code_interactivity_handler),
opt_slash_path("slack/event-callback", posthog_code_event_handler),
- # GitHub webhooks for task lifecycle events
- opt_slash_path("webhooks/github/pr", github_pr_webhook),
+ # GitHub App webhook — fans out to tasks (PRs) and conversations (issues)
+ opt_slash_path("webhooks/github/pr", github_webhook),
# Message preferences
path("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/github_events.py b/products/conversations/backend/api/github_events.py
index 9b2040cf9e3b..4d9cf8077dae 100644
--- a/products/conversations/backend/api/github_events.py
+++ b/products/conversations/backend/api/github_events.py
@@ -1,16 +1,17 @@
-"""GitHub webhook endpoint for Conversations GitHub Issues channel."""
+"""GitHub event dispatch for Conversations GitHub Issues channel.
+
+The entry point is ``dispatch_github_event``, called from the GitHub App
+webhook fan-out in ``posthog.urls.github_webhook`` after signature verification
+and JSON parsing.
+"""
-import hmac
-import json
import hashlib
from typing import Any, cast
from django.http import HttpRequest, HttpResponse
-from django.views.decorators.csrf import csrf_exempt
import structlog
-from posthog.models.instance_setting import get_instance_setting
from posthog.models.integration import Integration
from products.conversations.backend.services.region_routing import is_primary_region, proxy_to_secondary_region
@@ -18,20 +19,6 @@ from products.conversations.backend.tasks import process_github_event
logger = structlog.get_logger(__name__)
-GITHUB_HANDLED_EVENTS = {"issues", "issue_comment"}
-
-
-def _get_github_webhook_secret() -> str | None:
- secret = get_instance_setting("GITHUB_WEBHOOK_SECRET")
- return secret if secret else None
-
-
-def _verify_github_signature(payload: bytes, signature: str | None, secret: str) -> bool:
- if not signature or not signature.startswith("sha256="):
- return False
- expected = "sha256=" + hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
- return hmac.compare_digest(expected, signature)
-
def _team_for_github_installation(installation_id: str) -> tuple[int | None, bool]:
"""Resolve team ID from a GitHub App installation ID.
@@ -55,7 +42,6 @@ def _team_for_github_installation(installation_id: str) -> tuple[int | None, boo
expected_integration_id = settings_dict.get("github_integration_id")
if expected_integration_id is not None and expected_integration_id != integration.id:
continue
- # Require explicit binding — skip if github_integration_id was never set
if expected_integration_id is None:
continue
return integration.team_id, True
@@ -63,35 +49,12 @@ def _team_for_github_installation(installation_id: str) -> tuple[int | None, boo
return None, False
-@csrf_exempt
-def github_issues_webhook(request: HttpRequest) -> HttpResponse:
- """Handle incoming GitHub webhook events for the Issues channel.
+def dispatch_github_event(request: HttpRequest, event_type: str, data: dict[str, Any]) -> HttpResponse:
+ """Route a pre-verified GitHub event to the conversations Celery pipeline.
- Verifies HMAC-SHA256 signature, resolves the team via installation ID,
- checks that the repo is monitored, and dispatches to a Celery task.
+ Called from ``posthog.urls.github_webhook`` after signature verification
+ and JSON parsing are already done.
"""
- if request.method != "POST":
- return HttpResponse(status=405)
-
- secret = _get_github_webhook_secret()
- if not secret:
- logger.warning("github_issues_webhook_no_secret")
- return HttpResponse(status=503)
-
- signature = request.headers.get("X-Hub-Signature-256")
- if not _verify_github_signature(request.body, signature, secret):
- logger.warning("github_issues_webhook_invalid_signature")
- return HttpResponse("Invalid signature", status=403)
-
- event_type = request.headers.get("X-GitHub-Event", "")
- if event_type not in GITHUB_HANDLED_EVENTS:
- return HttpResponse(status=200)
-
- try:
- data: dict[str, Any] = json.loads(request.body)
- except json.JSONDecodeError:
- return HttpResponse("Invalid JSON", status=400)
-
installation_id = str(data.get("installation", {}).get("id", ""))
if not installation_id:
logger.warning("github_issues_webhook_no_installation")
diff --git a/products/conversations/backend/api/tests/test_github_webhook.py b/products/conversations/backend/api/tests/test_github_webhook.py
index 1a7504d666ce..ab663e0f4d36 100644
--- a/products/conversations/backend/api/tests/test_github_webhook.py
+++ b/products/conversations/backend/api/tests/test_github_webhook.py
@@ -6,12 +6,14 @@ from typing import Any
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
-from django.test import Client
+from django.test import RequestFactory
from parameterized import parameterized
from posthog.models.integration import Integration
+from products.conversations.backend.api.github_events import dispatch_github_event
+
def _sign(payload: bytes, secret: str) -> str:
sig = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
@@ -45,10 +47,12 @@ def _issue_event(
WEBHOOK_SECRET = "test-webhook-secret"
-class TestGithubIssuesWebhook(BaseTest):
+class TestDispatchGithubEvent(BaseTest):
+ """Tests for dispatch_github_event called directly (as github_pr_webhook does)."""
+
def setUp(self):
super().setUp()
- self.client = Client()
+ self.factory = RequestFactory()
self.integration = Integration.objects.create(
team=self.team,
@@ -64,63 +68,21 @@ class TestGithubIssuesWebhook(BaseTest):
}
self.team.save()
- def _post_webhook(
- self,
- payload: dict,
- event_type: str = "issues",
- secret: str = WEBHOOK_SECRET,
- delivery_id: str = "delivery-abc",
- signature: str | None = None,
- ):
+ def _dispatch(self, payload: dict, event_type: str = "issues", delivery_id: str = "delivery-abc"):
body = json.dumps(payload).encode()
- headers: dict[str, str] = {
- "X-GitHub-Event": event_type,
- "X-GitHub-Delivery": delivery_id,
- }
- if signature is not None:
- headers["X-Hub-Signature-256"] = signature
- else:
- headers["X-Hub-Signature-256"] = _sign(body, secret)
-
- return self.client.post(
- "/api/conversations/v1/github/events",
- body,
+ request = self.factory.post(
+ "/webhooks/github/pr/",
+ data=body,
content_type="application/json",
- headers=headers,
+ HTTP_X_GITHUB_DELIVERY=delivery_id,
)
-
- @parameterized.expand(
- [
- ("no_secret_returns_503", None, None, "issues", 503),
- ("bad_signature_returns_403", WEBHOOK_SECRET, "sha256=bad", "issues", 403),
- ("unhandled_event_returns_200", WEBHOOK_SECRET, None, "push", 200),
- ]
- )
- def test_error_responses(self, _name, secret_value, forced_sig, event_type, expected_status):
- with patch(
- "products.conversations.backend.api.github_events._get_github_webhook_secret",
- return_value=secret_value,
- ):
- resp = self._post_webhook(_issue_event(), event_type=event_type, signature=forced_sig)
- assert resp.status_code == expected_status
-
- @patch(
- "products.conversations.backend.api.github_events._get_github_webhook_secret",
- return_value=WEBHOOK_SECRET,
- )
- def test_returns_405_for_get(self, _mock):
- resp = self.client.get("/api/conversations/v1/github/events")
- assert resp.status_code == 405
+ return dispatch_github_event(request, event_type, payload)
@patch("products.conversations.backend.api.github_events.process_github_event")
- @patch(
- "products.conversations.backend.api.github_events._get_github_webhook_secret",
- return_value=WEBHOOK_SECRET,
- )
- def test_dispatches_issue_event_to_celery(self, _mock_secret, mock_task):
+ def test_dispatches_issue_event_to_celery(self, mock_task):
mock_task.delay = MagicMock()
payload = _issue_event()
- resp = self._post_webhook(payload)
+ resp = self._dispatch(payload)
assert resp.status_code == 202
mock_task.delay.assert_called_once()
@@ -130,43 +92,37 @@ class TestGithubIssuesWebhook(BaseTest):
assert call_kwargs["repo"] == "org/repo"
@patch("products.conversations.backend.api.github_events.process_github_event")
- @patch(
- "products.conversations.backend.api.github_events._get_github_webhook_secret",
- return_value=WEBHOOK_SECRET,
- )
- def test_falls_back_to_sha256_when_delivery_header_missing(self, _mock_secret, mock_task):
+ def test_falls_back_to_sha256_when_delivery_header_missing(self, mock_task):
mock_task.delay = MagicMock()
payload = _issue_event()
body = json.dumps(payload).encode()
expected_hash = hashlib.sha256(body).hexdigest()[:32]
- self.client.post(
- "/api/conversations/v1/github/events",
- body,
+ request = self.factory.post(
+ "/webhooks/github/pr/",
+ data=body,
content_type="application/json",
- headers={
- "X-GitHub-Event": "issues",
- "X-Hub-Signature-256": _sign(body, WEBHOOK_SECRET),
- },
)
+ dispatch_github_event(request, "issues", payload)
call_kwargs = mock_task.delay.call_args[1]
assert call_kwargs["delivery_id"] == expected_hash
+ def test_no_installation_returns_200(self):
+ payload = _issue_event()
+ del payload["installation"]
+ resp = self._dispatch(payload)
+ assert resp.status_code == 200
+
@parameterized.expand(
[
- # (name, installation_id, settings_override, reason)
("unknown_installation", 99999, {}, "no matching Integration row"),
("github_disabled", 12345, {"github_enabled": False}, "feature disabled"),
("no_integration_binding", 12345, {"github_integration_id": None}, "no explicit binding"),
]
)
@patch("products.conversations.backend.api.github_events.process_github_event")
- @patch(
- "products.conversations.backend.api.github_events._get_github_webhook_secret",
- return_value=WEBHOOK_SECRET,
- )
- def test_no_dispatch(self, _name, installation_id, settings_override, _reason, _mock_secret, mock_task):
+ def test_no_dispatch(self, _name, installation_id, settings_override, _reason, mock_task):
mock_task.delay = MagicMock()
if settings_override:
for key, val in settings_override.items():
@@ -176,6 +132,6 @@ class TestGithubIssuesWebhook(BaseTest):
self.team.conversations_settings[key] = val
self.team.save()
- resp = self._post_webhook(_issue_event(installation_id=installation_id))
+ resp = self._dispatch(_issue_event(installation_id=installation_id))
assert resp.status_code == 200
mock_task.delay.assert_not_called()
diff --git a/products/conversations/backend/api/urls.py b/products/conversations/backend/api/urls.py
index 9906da45aabf..3d9e649ed157 100644
--- a/products/conversations/backend/api/urls.py
+++ b/products/conversations/backend/api/urls.py
@@ -11,7 +11,6 @@ from .email_settings import (
EmailVerifyDomainView,
)
from .external import ExternalTicketView
-from .github_events import github_issues_webhook
from .github_setup import (
GithubConnectView,
GithubCreateIssueView,
@@ -59,7 +58,6 @@ urlpatterns = [
re_path(r"^v1/email/verify-domain/?$", EmailVerifyDomainView.as_view(), name="email-verify-domain"),
re_path(r"^v1/email/send-test/?$", EmailSendTestView.as_view(), name="email-send-test"),
# GitHub Issues channel
- re_path(r"^v1/github/events/?$", github_issues_webhook, name="github-issues-events"),
re_path(r"^v1/github/status/?$", GithubStatusView.as_view(), name="github-status"),
re_path(r"^v1/github/connect/?$", GithubConnectView.as_view(), name="github-connect"),
re_path(r"^v1/github/disconnect/?$", GithubDisconnectView.as_view(), name="github-disconnect"),
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index 82e2bcb8f365..b74a634cfd7a 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -3,12 +3,13 @@ import json
import hashlib
from typing import ClassVar
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.test import TestCase
from rest_framework.test import APIClient
+from posthog.models.integration import Integration
from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -190,13 +191,13 @@ class TestGitHubPRWebhook(TestCase):
mock_capture.assert_not_called()
@patch("products.tasks.backend.webhooks.get_github_webhook_secret")
- def test_non_pr_event_ignored(self, mock_get_secret):
- """Test that non-pull_request events are acknowledged but ignored."""
+ def test_non_pr_non_issue_event_ignored(self, mock_get_secret):
+ """Test that events other than pull_request/issues/issue_comment are acknowledged but ignored."""
mock_get_secret.return_value = self.webhook_secret
- payload = {"action": "created", "issue": {"html_url": "https://github.com/org/repo/issues/1"}}
+ payload = {"action": "created", "ref": "refs/heads/main"}
- response = self._make_webhook_request(payload, event_type="issues")
+ response = self._make_webhook_request(payload, event_type="push")
self.assertEqual(response.status_code, 200)
@@ -385,3 +386,111 @@ class TestFindTaskRun(TestCase):
)
for value in ("", " ", "\t"):
self.assertIsNone(find_task_run(branch="main", repository=value))
+
+
+class TestGitHubWebhookFanout(TestCase):
+ """Verify that issues/issue_comment events on webhooks/github/pr are
+ routed to the conversations dispatch_github_event function."""
+
+ organization: ClassVar[Organization]
+ team: ClassVar[Team]
+ integration: ClassVar[Integration]
+
+ @classmethod
+ def setUpTestData(cls):
+ cls.organization = Organization.objects.create(name="Fanout Org")
+ cls.team = Team.objects.create(organization=cls.organization, name="Fanout Team")
+ cls.integration = Integration.objects.create(
+ team=cls.team,
+ kind="github",
+ integration_id="77777",
+ config={"account": {"name": "myorg"}},
+ )
+ cls.team.conversations_enabled = True
+ cls.team.conversations_settings = {
+ "github_enabled": True,
+ "github_integration_id": cls.integration.id,
+ "github_repos": ["myorg/myrepo"],
+ }
+ cls.team.save()
+
+ def setUp(self):
+ self.client = APIClient()
+ self.webhook_secret = "test-webhook-secret"
+
+ def _make_request(self, payload: dict, event_type: str = "issues", delivery_id: str = "del-1"):
+ payload_bytes = json.dumps(payload).encode("utf-8")
+ signature = generate_github_signature(payload_bytes, self.webhook_secret)
+ return self.client.post(
+ "/webhooks/github/pr/",
+ data=payload_bytes,
+ content_type="application/json",
+ headers={
+ "x-hub-signature-256": signature,
+ "x-github-event": event_type,
+ "x-github-delivery": delivery_id,
+ },
+ )
+
+ @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):
+ mock_secret.return_value = self.webhook_secret
+ mock_task.delay = MagicMock()
+
+ payload = {
+ "action": "opened",
+ "installation": {"id": 77777},
+ "repository": {"full_name": "myorg/myrepo"},
+ "issue": {"number": 42, "title": "Bug", "body": "", "user": {"login": "dev"}},
+ "sender": {"login": "dev"},
+ }
+
+ response = self._make_request(payload, event_type="issues")
+
+ self.assertEqual(response.status_code, 202)
+ mock_task.delay.assert_called_once()
+ call_kwargs = mock_task.delay.call_args[1]
+ self.assertEqual(call_kwargs["event_type"], "issues")
+ self.assertEqual(call_kwargs["team_id"], self.team.id)
+ self.assertEqual(call_kwargs["repo"], "myorg/myrepo")
+
+ @patch("products.conversations.backend.api.github_events.process_github_event")
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ def test_issue_comment_event_dispatched_to_conversations(self, mock_secret, mock_task):
+ mock_secret.return_value = self.webhook_secret
+ mock_task.delay = MagicMock()
+
+ payload = {
+ "action": "created",
+ "installation": {"id": 77777},
+ "repository": {"full_name": "myorg/myrepo"},
+ "issue": {"number": 42, "title": "Bug", "body": "", "user": {"login": "dev"}},
+ "comment": {"id": 999, "body": "Looks good", "user": {"login": "reviewer"}},
+ "sender": {"login": "reviewer"},
+ }
+
+ response = self._make_request(payload, event_type="issue_comment")
+
+ self.assertEqual(response.status_code, 202)
+ mock_task.delay.assert_called_once()
+ self.assertEqual(mock_task.delay.call_args[1]["event_type"], "issue_comment")
+
+ @patch("products.conversations.backend.api.github_events.process_github_event")
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ def test_issues_event_without_matching_team_returns_200(self, mock_secret, mock_task):
+ mock_secret.return_value = self.webhook_secret
+ mock_task.delay = MagicMock()
+
+ payload = {
+ "action": "opened",
+ "installation": {"id": 99999},
+ "repository": {"full_name": "other/repo"},
+ "issue": {"number": 1, "title": "X", "body": "", "user": {"login": "u"}},
+ "sender": {"login": "u"},
+ }
+
+ response = self._make_request(payload, event_type="issues")
+
+ self.assertEqual(response.status_code, 200)
+ mock_task.delay.assert_not_called()