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.

feat(error-tracking): link GitHub descriptions to issues (#103630)

Hugues Pouillotffe44973cf26
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 34521ae95806..dafe132be026 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -64,20 +64,20 @@ Three duties fall on the incarnation rather than on `BearerJwt`, and none is enf
## Endpoints
-| Provider | Path | App | Consumers | Product code |
-| ------------ | ------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
-| `github` | `/webhooks/github`, `/webhooks/github/pr` | `posthog` | `installation_lifecycle`, `installation_repositories` (core), `conversations`, `loops`, `tasks_pr_backstop`, `tasks_pr_review`, `workflows` | `products/{tasks,conversations,workflows}/backend/webhook_consumers.py` |
-| `github` | `/webhooks/stamphog/github` | `stamphog` | `stamphog_review` | `products/stamphog/backend/webhook_consumers.py` |
-| `slack` | `/api/conversations/v1/slack/events` | `supporthog` | `conversations_slack` | `products/conversations/backend/webhook_consumers.py` |
-| `slack` | `/api/conversations/v1/slack/interactivity` | `supporthog_interactivity` | `conversations_slack_interactivity` | `products/conversations/backend/webhook_consumers.py` |
-| `teams` | `/api/conversations/v1/teams/events` | `supporthog` | `conversations_teams` | `products/conversations/backend/webhook_consumers.py` |
-| `pandadoc` | `/api/legal_documents/pandadoc` | `default` | `legal_documents_signatures` | `products/legal_documents/backend/webhook_consumers.py` |
-| `vapi` | `/api/user_interviews/vapi_webhook/` | `default` | `user_interviews_vapi` | `products/user_interviews/backend/webhook_consumers.py` |
-| `mailgun` | `/api/conversations/v1/email/inbound` | `inbound` | `conversations_email_inbound` | `products/conversations/backend/webhook_consumers.py` |
-| `mailgun` | `/api/conversations/v1/email/outbound` | `outbound` | `conversations_email_outbound` | `products/conversations/backend/webhook_consumers.py` |
-| `mailgun` | `/api/conversations/v1/email/capture` | `capture` | `conversations_email_capture` | `products/conversations/backend/webhook_consumers.py` |
-| `sns` | `/webhooks/workflows/ses-events` | `default` | `workflows_ses_events` | `products/workflows/backend/webhook_consumers.py` |
-| `customerio` | `/api/projects/<team_id>/messaging/customerio/webhook/` | none | none, it is the DRF adapter path | `products/messaging/backend/api/customerio_webhook.py` |
+| Provider | Path | App | Consumers | Product code |
+| ------------ | ------------------------------------------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
+| `github` | `/webhooks/github`, `/webhooks/github/pr` | `posthog` | `installation_lifecycle`, `installation_repositories` (core), `conversations`, `error_tracking_external_references`, `loops`, `tasks_pr_backstop`, `tasks_pr_review`, `workflows` | `products/{tasks,conversations,error_tracking,workflows}/backend/webhook_consumers.py` |
+| `github` | `/webhooks/stamphog/github` | `stamphog` | `stamphog_review` | `products/stamphog/backend/webhook_consumers.py` |
+| `slack` | `/api/conversations/v1/slack/events` | `supporthog` | `conversations_slack` | `products/conversations/backend/webhook_consumers.py` |
+| `slack` | `/api/conversations/v1/slack/interactivity` | `supporthog_interactivity` | `conversations_slack_interactivity` | `products/conversations/backend/webhook_consumers.py` |
+| `teams` | `/api/conversations/v1/teams/events` | `supporthog` | `conversations_teams` | `products/conversations/backend/webhook_consumers.py` |
+| `pandadoc` | `/api/legal_documents/pandadoc` | `default` | `legal_documents_signatures` | `products/legal_documents/backend/webhook_consumers.py` |
+| `vapi` | `/api/user_interviews/vapi_webhook/` | `default` | `user_interviews_vapi` | `products/user_interviews/backend/webhook_consumers.py` |
+| `mailgun` | `/api/conversations/v1/email/inbound` | `inbound` | `conversations_email_inbound` | `products/conversations/backend/webhook_consumers.py` |
+| `mailgun` | `/api/conversations/v1/email/outbound` | `outbound` | `conversations_email_outbound` | `products/conversations/backend/webhook_consumers.py` |
+| `mailgun` | `/api/conversations/v1/email/capture` | `capture` | `conversations_email_capture` | `products/conversations/backend/webhook_consumers.py` |
+| `sns` | `/webhooks/workflows/ses-events` | `default` | `workflows_ses_events` | `products/workflows/backend/webhook_consumers.py` |
+| `customerio` | `/api/projects/<team_id>/messaging/customerio/webhook/` | none | none, it is the DRF adapter path | `products/messaging/backend/api/customerio_webhook.py` |
The owner of the third-party App registration owns the route.
The customer-facing GitHub App is shared across products, so its two endpoints are declared in `posthog/urls.py`.
diff --git a/posthog/ingress/github/README.md b/posthog/ingress/github/README.md
index ce3023547841..e8c10a9f8d9b 100644
--- a/posthog/ingress/github/README.md
+++ b/posthog/ingress/github/README.md
@@ -44,8 +44,13 @@ See [Regional forwarding](../README.md#regional-forwarding) for the lane the pro
## Consumers
- `posthog/ingress/github/provider.py` registers `installation_lifecycle` and `installation_repositories` on the `posthog` app.
-- `products/{tasks,conversations,workflows}/backend/webhook_consumers.py` register the product consumers on the `posthog` app.
+- `products/{tasks,conversations,error_tracking,workflows}/backend/webhook_consumers.py` register the product consumers on the `posthog` app.
- `products/stamphog/backend/webhook_consumers.py` registers `stamphog_review` on the `stamphog` app.
+The Error Tracking consumer handles opened and edited issues and pull requests from repository owners, members, and collaborators.
+It scans descriptions for direct issue links and fingerprint permalinks on the configured PostHog site, then queues team-scoped tasks.
+Repeated links and deliveries reuse an existing reference.
+Removing a link from a later description does not remove the reference.
+
The [Endpoints table](../README.md#endpoints) lists the consumer names per event type.
PR analytics shared by those consumers live in `posthog/github/`, see its README.
diff --git a/posthog/models/integration/external_issues.py b/posthog/models/integration/external_issues.py
index 1502de779e0a..b1d7c19eb1cc 100644
--- a/posthog/models/integration/external_issues.py
+++ b/posthog/models/integration/external_issues.py
@@ -47,7 +47,8 @@ def external_issue_url(integration: model.Integration, external_context: dict[st
if "/" in str(repository)
else f"{GitHubIntegration(integration).organization()}/{repository}"
)
- return f"https://github.com/{repository_path}/issues/{number}"
+ resource_path = "pull" if context.get("resource_type") == "pull_request" else "issues"
+ return f"https://github.com/{repository_path}/{resource_path}/{number}"
if integration.kind == model.Integration.IntegrationKind.GITLAB:
issue_id = context.get("issue_id")
diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.py
index 3d92659e89ff..a32402172bc6 100644
--- a/posthog/models/integration/github.py
+++ b/posthog/models/integration/github.py
@@ -34,6 +34,10 @@ _GITHUB_REF_RE = re.compile(r"^[A-Za-z0-9._\-/]+$")
_GITHUB_COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,40}$")
+# GitHub's own login rule: alphanumerics and single hyphens, never leading or trailing. Keeps a
+# crafted login out of the collaborator-permission URL path.
+_GITHUB_LOGIN_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
+
# Upper bound on the diff text we return, to keep a pathological diff (generated/vendored
# files) from bloating the JSON response and worker memory. ~1 MB of text.
_MAX_DIFF_CHARS = 1_000_000
@@ -416,6 +420,32 @@ class GitHubIntegration(GitHubIntegrationBase):
status_code=response.status_code,
)
+ def get_collaborator_permission(self, repository: str, username: str) -> str:
+ """The user's effective permission on the repo: ``admin``, ``write``, ``read`` or ``none``.
+
+ GitHub's legacy ``permission`` field folds ``maintain`` into ``write`` and ``triage`` into
+ ``read``, which is the granularity a "can this person change the repo" gate needs. A 404
+ means no access at all. Every other non-200 raises, so a caller can fail closed rather than
+ read a blank response as a denial.
+ """
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+ if not _is_safe_github_repo_path(repo_path) or not _GITHUB_LOGIN_RE.fullmatch(username):
+ raise GitHubIntegrationError(f"GitHubIntegration: unsafe collaborator lookup for {repo_path}")
+
+ response = self.api_request(
+ "GET",
+ f"/repos/{repo_path}/collaborators/{username}/permission",
+ endpoint="/repos/{owner}/{repo}/collaborators/{username}/permission",
+ )
+ if response.status_code == 404:
+ return "none"
+ if response.status_code != 200:
+ raise GitHubIntegrationError(
+ f"GitHubIntegration: failed to read {username} permission on {repo_path}: {response.text[:300]}",
+ status_code=response.status_code,
+ )
+ return response.json().get("permission") or "none"
+
def _get_issue_by_number(self, repo_path: str, repository_name: str, issue_number: int) -> dict[str, Any] | None:
response = self.api_request(
"GET",
diff --git a/posthog/urls.py b/posthog/urls.py
index 6da70e9a6bbc..09b87a1941f8 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -352,7 +352,7 @@ urlpatterns = [
opt_slash_path("slack/event-callback", posthog_code_event_handler),
opt_slash_path("slack/command-callback", slack_app_command_handler),
opt_slash_path("slack/workspace/claims", slack_workspace_claims_view),
- # GitHub App webhook — ingress fans it out to the tasks, conversations and workflows consumers.
+ # GitHub App webhook — ingress fans it out to the registered product consumers.
# It stays in core because the App is shared: no single product owns its registration.
opt_slash_path("webhooks/github/pr", github_app_webhook),
opt_slash_path("webhooks/github", github_app_webhook),
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index c3fb8e982de0..90c67656d3c6 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -17,7 +17,7 @@ from products.access_control.backend.models.role import RoleMembership
from .. import logic, weekly_digest, weekly_digest_delivery
from ..indexed_embedding import EMBEDDING_TABLES
-from ..logic import external_references, rules
+from ..logic import external_references, github_external_references, rules
from ..models import (
ErrorTrackingIssue,
override_error_tracking_issue_fingerprint as override_error_tracking_issue_fingerprint,
@@ -702,6 +702,16 @@ def is_supported_external_issue_provider(kind: str) -> bool:
return external_references.is_supported_external_issue_provider(kind=kind)
+def prepare_github_external_reference_jobs(
+ event_type: str, payload: dict[str, Any]
+) -> list[contracts.GitHubExternalReferenceJob]:
+ return github_external_references.prepare_jobs(event_type, payload)
+
+
+def link_github_external_reference(job: contracts.GitHubExternalReferenceJob) -> bool:
+ return github_external_references.link_reference(job)
+
+
def get_issue_values(team_id: int, key: str | None, value: str | None) -> list[str]:
return logic.get_issue_values(team_id=team_id, key=key, value=value)
diff --git a/products/error_tracking/backend/facade/contracts.py b/products/error_tracking/backend/facade/contracts.py
index 9f95626b6f34..77cc6377814d 100644
--- a/products/error_tracking/backend/facade/contracts.py
+++ b/products/error_tracking/backend/facade/contracts.py
@@ -73,6 +73,23 @@ class ErrorTrackingExternalReference:
title: str
+@dataclass(frozen=True)
+class GitHubExternalReferenceJob:
+ team_id: int
+ installation_id: str
+ repository_full_name: str
+ number: int
+ title: str
+ resource_type: Literal["issue", "pull_request"]
+ actor_login: str
+ issue_id: UUID | None = None
+ fingerprint: str | None = field(default=None, repr=False)
+
+ def __post_init__(self) -> None:
+ if (self.issue_id is None) == (self.fingerprint is None):
+ raise ValueError("Provide exactly one PostHog issue identifier.")
+
+
@dataclass(frozen=True)
class ErrorTrackingFingerprint:
id: UUID
diff --git a/products/error_tracking/backend/facade/github.py b/products/error_tracking/backend/facade/github.py
new file mode 100644
index 000000000000..25173847acad
--- /dev/null
+++ b/products/error_tracking/backend/facade/github.py
@@ -0,0 +1,3 @@
+from products.error_tracking.backend.tasks.github import enqueue_github_external_references
+
+__all__ = ["enqueue_github_external_references"]
diff --git a/products/error_tracking/backend/logic/external_references.py b/products/error_tracking/backend/logic/external_references.py
index 48a639096294..391e691a229b 100644
--- a/products/error_tracking/backend/logic/external_references.py
+++ b/products/error_tracking/backend/logic/external_references.py
@@ -137,6 +137,15 @@ def _clean_existing_external_context(integration: Integration, external_context:
)
cleaned["title"] = title.strip()
+ if integration.kind == Integration.IntegrationKind.GITHUB:
+ resource_type = external_context.get("resource_type")
+ if resource_type is not None:
+ if resource_type not in {"issue", "pull_request"}:
+ raise ErrorTrackingExternalReferenceValidationError(
+ "GitHub references must identify either an issue or a pull request."
+ )
+ cleaned["resource_type"] = resource_type
+
return cleaned
@@ -198,9 +207,12 @@ def create_external_reference(
issue=issue, integration=integration, external_context__contains=identifier_context
).first()
if existing is not None:
- title = stored_context.get("title")
- if title and (existing.external_context or {}).get("title") != title:
- existing.external_context = {**(existing.external_context or {}), "title": title}
+ updated_context = {
+ **(existing.external_context or {}),
+ **{key: stored_context[key] for key in ("title", "resource_type") if key in stored_context},
+ }
+ if updated_context != existing.external_context:
+ existing.external_context = updated_context
existing.save(update_fields=["external_context"])
return existing, False
if integration.kind == Integration.IntegrationKind.LINEAR:
diff --git a/products/error_tracking/backend/logic/github_external_references.py b/products/error_tracking/backend/logic/github_external_references.py
new file mode 100644
index 000000000000..dbeb4a2f1fd4
--- /dev/null
+++ b/products/error_tracking/backend/logic/github_external_references.py
@@ -0,0 +1,220 @@
+import re
+from typing import Any, Literal
+from urllib.parse import unquote
+from uuid import UUID
+
+from django.conf import settings
+from django.core.cache import cache
+from django.db import transaction
+
+from posthog.dataclasses import frozen
+from posthog.models.integration import GitHubIntegration, Integration
+
+from products.error_tracking.backend.facade import contracts
+from products.error_tracking.backend.logic import external_references
+from products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingIssueFingerprintV2
+
+# A cheap shed before we spend a Celery task and a GitHub API call, not a trust gate: OWNER and
+# MEMBER say nothing about access to this repo, and COLLABORATOR covers read/triage-only invites.
+# CONTRIBUTOR is admitted because the field is unreliable in App-delivered payloads: GitHub
+# computes it with less context than a user-token call, so org members on private repos arrive
+# downgraded. link_reference holds the authoritative gate (see _WRITE_PERMISSIONS).
+_PAYLOAD_GATE_ASSOCIATIONS = frozenset({"OWNER", "MEMBER", "COLLABORATOR", "CONTRIBUTOR"})
+_SUPPORTED_ACTIONS = frozenset({"opened", "edited"})
+_MAX_REFERENCES_PER_WEBHOOK = 20
+
+# The reference is permanent (references cannot be deleted), so linking must require someone who
+# could change the repo anyway. GitHub's legacy permission field folds maintain into write and
+# triage into read.
+#
+# Asymmetric cache TTLs: a cached ALLOW is a revocation window, so it stays short. A cached DENY
+# only delays a just-promoted collaborator's first link, which is harmless.
+_WRITE_PERMISSIONS = frozenset({"admin", "write"})
+_ACTOR_PERMISSION_ALLOW_CACHE_SECONDS = 60
+_ACTOR_PERMISSION_DENY_CACHE_SECONDS = 10 * 60
+
+
+@frozen
+class _PostHogIssueReference:
+ team_id: int
+ issue_id: UUID | None = None
+ fingerprint: str | None = None
+
+
+def prepare_jobs(event_type: str, payload: dict[str, Any]) -> list[contracts.GitHubExternalReferenceJob]:
+ resource_type: Literal["issue", "pull_request"]
+ resource: Any
+ if event_type == "issues":
+ resource_type = "issue"
+ resource = payload.get("issue")
+ elif event_type == "pull_request":
+ resource_type = "pull_request"
+ resource = payload.get("pull_request")
+ else:
+ return []
+
+ if payload.get("action") not in _SUPPORTED_ACTIONS or not isinstance(resource, dict):
+ return []
+
+ sender = payload.get("sender") or {}
+ # A bot (dependabot, renovate) cannot be a repo collaborator, so the permission lookup would
+ # only ever deny it. Drop it here rather than pay a task and an API call to reach that answer.
+ if sender.get("type") == "Bot":
+ return []
+
+ # The actor is the sender, not the resource author: on an edit they are different people, and
+ # only the sender chose to add the link. author_association describes the author, so it says
+ # something about the actor only when the two are the same person.
+ actor_login = sender.get("login")
+ author_login = (resource.get("user") or {}).get("login")
+ if (
+ actor_login == author_login
+ and str(resource.get("author_association") or "").upper() not in _PAYLOAD_GATE_ASSOCIATIONS
+ ):
+ return []
+
+ installation_id = (payload.get("installation") or {}).get("id")
+ repository_full_name = (payload.get("repository") or {}).get("full_name")
+ number = resource.get("number")
+ title = resource.get("title")
+ body = resource.get("body")
+ if (
+ not isinstance(actor_login, str)
+ or not actor_login
+ or isinstance(installation_id, bool)
+ or not isinstance(installation_id, int)
+ or installation_id <= 0
+ or not isinstance(repository_full_name, str)
+ or repository_full_name.count("/") != 1
+ or isinstance(number, bool)
+ or not isinstance(number, int)
+ or number <= 0
+ or not isinstance(title, str)
+ or not isinstance(body, str)
+ ):
+ return []
+
+ return [
+ contracts.GitHubExternalReferenceJob(
+ team_id=reference.team_id,
+ installation_id=str(installation_id),
+ repository_full_name=repository_full_name,
+ number=number,
+ title=title,
+ resource_type=resource_type,
+ actor_login=actor_login,
+ issue_id=reference.issue_id,
+ fingerprint=reference.fingerprint,
+ )
+ for reference in _extract_posthog_issue_references(body)
+ ]
+
+
+def _extract_posthog_issue_references(body: str) -> list[_PostHogIssueReference]:
+ site_url = re.escape(settings.SITE_URL.rstrip("/"))
+ pattern = re.compile(
+ rf"{site_url}/project/(?P<team_id>[1-9][0-9]*)/error_tracking/"
+ rf"(?:fingerprint/(?P<fingerprint>[^/?#\s<>\]\)]+)|"
+ rf"(?P<issue_id>[0-9a-fA-F]{{8}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{4}}-"
+ rf"[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{12}}))"
+ )
+
+ references: list[_PostHogIssueReference] = []
+ seen: set[_PostHogIssueReference] = set()
+ for match in pattern.finditer(body):
+ issue_id = match.group("issue_id")
+ reference = _PostHogIssueReference(
+ team_id=int(match.group("team_id")),
+ issue_id=UUID(issue_id) if issue_id else None,
+ fingerprint=unquote(match.group("fingerprint")) if match.group("fingerprint") else None,
+ )
+ if reference in seen:
+ continue
+ seen.add(reference)
+ references.append(reference)
+ if len(references) == _MAX_REFERENCES_PER_WEBHOOK:
+ break
+ return references
+
+
+def _resolve_issue(job: contracts.GitHubExternalReferenceJob) -> ErrorTrackingIssue | None:
+ if job.issue_id is not None:
+ return ErrorTrackingIssue.objects.filter(team_id=job.team_id, id=job.issue_id).first()
+ if job.fingerprint is None:
+ return None
+ fingerprint = ErrorTrackingIssueFingerprintV2.objects.filter(
+ team_id=job.team_id, fingerprint=job.fingerprint
+ ).first()
+ return fingerprint.issue if fingerprint is not None else None
+
+
+def _actor_lacks_write_permission(integration: Integration, job: contracts.GitHubExternalReferenceJob) -> bool:
+ """Whether the actor's effective permission on the repo is below write.
+
+ This is the only gate that proves repo access, because the webhook's author_association
+ does not.
+ Costs a GitHub API call, so it runs after the cheaper checks and the result is cached briefly
+ per (integration, repo, login). Lookup errors propagate: the caller retries the delivery rather
+ than failing open.
+ """
+ cache_key = (
+ f"error_tracking:github_actor_permission:{integration.id}:"
+ f"{job.repository_full_name.casefold()}:{job.actor_login.casefold()}"
+ )
+ permission = cache.get(cache_key)
+ if permission is None:
+ permission = GitHubIntegration(integration).get_collaborator_permission(
+ job.repository_full_name, job.actor_login
+ )
+ ttl = (
+ _ACTOR_PERMISSION_ALLOW_CACHE_SECONDS
+ if permission in _WRITE_PERMISSIONS
+ else _ACTOR_PERMISSION_DENY_CACHE_SECONDS
+ )
+ cache.set(cache_key, permission, ttl)
+ return permission not in _WRITE_PERMISSIONS
+
+
+def link_reference(job: contracts.GitHubExternalReferenceJob) -> bool:
+ owner, repository = job.repository_full_name.split("/", 1)
+ integration = (
+ Integration.objects.filter(
+ team_id=job.team_id,
+ kind=Integration.IntegrationKind.GITHUB.value,
+ integration_id=job.installation_id,
+ )
+ .order_by("id")
+ .first()
+ )
+ if integration is None:
+ return False
+ try:
+ integration_owner = GitHubIntegration(integration).organization()
+ except ValueError:
+ return False
+ if integration_owner.casefold() != owner.casefold():
+ return False
+
+ if _actor_lacks_write_permission(integration, job):
+ return False
+
+ issue = _resolve_issue(job)
+ if issue is None:
+ return False
+
+ with transaction.atomic():
+ locked_issue = ErrorTrackingIssue.objects.select_for_update().filter(team_id=job.team_id, id=issue.id).first()
+ if locked_issue is None:
+ return False
+ _, created = external_references.create_external_reference(
+ team_id=job.team_id,
+ issue_id=locked_issue.id,
+ integration_id=integration.id,
+ external_context={
+ "repository": repository,
+ "number": job.number,
+ "title": job.title,
+ "resource_type": job.resource_type,
+ },
+ )
+ return created
diff --git a/products/error_tracking/backend/tasks/__init__.py b/products/error_tracking/backend/tasks/__init__.py
index fc1db816e180..984d9890953d 100644
--- a/products/error_tracking/backend/tasks/__init__.py
+++ b/products/error_tracking/backend/tasks/__init__.py
@@ -1,3 +1,4 @@
+from products.error_tracking.backend.tasks.github import process_github_external_reference # noqa: F401
from products.error_tracking.backend.tasks.tasks import ( # noqa: F401
compute_error_tracking_recommendation,
dispatch_error_tracking_alert_deliveries,
diff --git a/products/error_tracking/backend/tasks/github.py b/products/error_tracking/backend/tasks/github.py
new file mode 100644
index 000000000000..d1e5cfd160b1
--- /dev/null
+++ b/products/error_tracking/backend/tasks/github.py
@@ -0,0 +1,68 @@
+from typing import Any, Literal, cast
+from uuid import UUID
+
+from django.db import DatabaseError
+
+from celery import shared_task
+
+from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.models.integration import GitHubIntegrationError
+from posthog.models.scoping import with_team_scope
+
+from products.error_tracking.backend.facade import api, contracts
+
+
+def enqueue_github_external_references(event_type: str, payload: dict[str, Any]) -> None:
+ for job in api.prepare_github_external_reference_jobs(event_type, payload):
+ cast(Any, process_github_external_reference).delay(
+ team_id=job.team_id,
+ installation_id=job.installation_id,
+ repository_full_name=job.repository_full_name,
+ number=job.number,
+ title=job.title,
+ resource_type=job.resource_type,
+ actor_login=job.actor_login,
+ issue_id=str(job.issue_id) if job.issue_id is not None else None,
+ fingerprint=job.fingerprint,
+ )
+
+
+@shared_task(
+ name="products.error_tracking.backend.tasks.process_github_external_reference",
+ ignore_result=True,
+ acks_late=True,
+ reject_on_worker_lost=True,
+ # The repo-permission lookup fails closed, so a transient GitHub error must retry rather than
+ # drop the delivery, because a blip would otherwise lose a legitimate link for good.
+ autoretry_for=(DatabaseError, GitHubIntegrationError, GitHubRateLimitError),
+ max_retries=5,
+ retry_backoff=True,
+ retry_backoff_max=300,
+ retry_jitter=True,
+)
+@with_team_scope()
+def process_github_external_reference(
+ *,
+ team_id: int,
+ installation_id: str,
+ repository_full_name: str,
+ number: int,
+ title: str,
+ resource_type: Literal["issue", "pull_request"],
+ actor_login: str,
+ issue_id: str | None,
+ fingerprint: str | None,
+) -> None:
+ api.link_github_external_reference(
+ contracts.GitHubExternalReferenceJob(
+ team_id=team_id,
+ installation_id=installation_id,
+ repository_full_name=repository_full_name,
+ number=number,
+ title=title,
+ resource_type=resource_type,
+ actor_login=actor_login,
+ issue_id=UUID(issue_id) if issue_id is not None else None,
+ fingerprint=fingerprint,
+ )
+ )
diff --git a/products/error_tracking/backend/test/test_facade_api.py b/products/error_tracking/backend/test/test_facade_api.py
index 993fa07655cb..6bb21151e8fd 100644
--- a/products/error_tracking/backend/test/test_facade_api.py
+++ b/products/error_tracking/backend/test/test_facade_api.py
@@ -290,6 +290,10 @@ class TestErrorTrackingFacadeAPI(BaseTest):
("blank_repository", {"repository": " ", "number": 42}),
("path_traversal_repository", {"repository": "../../settings", "number": 42}),
("dot_segment_repository", {"repository": "..", "number": 42}),
+ (
+ "invalid_github_resource_type",
+ {"repository": "posthog", "number": 42, "resource_type": "discussion"},
+ ),
]
)
def test_link_existing_issue_rejects_invalid_external_context(self, _name, external_context):
diff --git a/products/error_tracking/backend/test/test_github_external_references.py b/products/error_tracking/backend/test/test_github_external_references.py
new file mode 100644
index 000000000000..42e5df9a7426
--- /dev/null
+++ b/products/error_tracking/backend/test/test_github_external_references.py
@@ -0,0 +1,281 @@
+import hmac
+import json
+import hashlib
+from urllib.parse import quote
+
+from posthog.test.base import BaseTest
+from unittest.mock import Mock, patch
+
+from django.core.cache import cache
+from django.db import DatabaseError
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.ingress.dispatch.loading import reset_consumer_registry
+from posthog.models import Team
+from posthog.models.integration import GitHubIntegration, GitHubIntegrationError, Integration
+
+from products.error_tracking.backend.facade import api
+from products.error_tracking.backend.models import (
+ ErrorTrackingExternalReference,
+ ErrorTrackingIssue,
+ ErrorTrackingIssueFingerprintV2,
+)
+from products.error_tracking.backend.tasks.github import process_github_external_reference
+
+LINKED_BODY = "https://app.example.com/project/12/error_tracking/00000000-0000-0000-0000-000000000001"
+
+
+@override_settings(SITE_URL="https://app.example.com")
+class TestPrepareGitHubExternalReferenceJob(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("unsupported_action", "closed", "MEMBER", "octocat", "User", LINKED_BODY),
+ ("unrelated_author", "opened", "NONE", "octocat", "User", LINKED_BODY),
+ ("missing_sender", "opened", "MEMBER", None, "User", LINKED_BODY),
+ ("bot_sender", "opened", "MEMBER", "dependabot[bot]", "Bot", LINKED_BODY),
+ ("missing_body", "opened", "MEMBER", "octocat", "User", None),
+ ]
+ )
+ def test_rejects_ineligible_events(
+ self,
+ _name: str,
+ action: str,
+ author_association: str,
+ sender_login: str | None,
+ sender_type: str,
+ body: str | None,
+ ) -> None:
+ payload = {
+ "action": action,
+ "installation": {"id": 123},
+ "repository": {"full_name": "acme/widgets"},
+ "sender": {"login": sender_login, "type": sender_type},
+ "issue": {
+ "number": 17,
+ "title": "Checkout failed",
+ "body": body,
+ "user": {"login": "octocat"},
+ "author_association": author_association,
+ },
+ }
+
+ assert api.prepare_github_external_reference_jobs("issues", payload) == []
+
+ def test_carries_the_editor_rather_than_the_author_as_the_actor(self) -> None:
+ payload = {
+ "action": "edited",
+ "installation": {"id": 123},
+ "repository": {"full_name": "acme/widgets"},
+ "sender": {"login": "editor", "type": "User"},
+ "issue": {
+ "number": 17,
+ "title": "Checkout failed",
+ "body": LINKED_BODY,
+ "user": {"login": "drive-by"},
+ "author_association": "NONE",
+ },
+ }
+
+ jobs = api.prepare_github_external_reference_jobs("issues", payload)
+
+ assert [job.actor_login for job in jobs] == ["editor"]
+
+
+class TestGitHubExternalReferenceTask(SimpleTestCase):
+ def test_retries_transient_database_failures_without_losing_worker_crashes(self) -> None:
+ assert process_github_external_reference.acks_late is True
+ assert process_github_external_reference.reject_on_worker_lost is True
+ assert process_github_external_reference.autoretry_for == (
+ DatabaseError,
+ GitHubIntegrationError,
+ GitHubRateLimitError,
+ )
+ assert process_github_external_reference.max_retries == 5
+ assert process_github_external_reference.retry_backoff is True
+ assert process_github_external_reference.retry_backoff_max == 300
+ assert process_github_external_reference.retry_jitter is True
+
+
+@override_settings(SITE_URL="https://app.example.com")
+class TestErrorTrackingGitHubWebhook(SimpleTestCase):
+ def setUp(self) -> None:
+ reset_consumer_registry()
+ cache.clear()
+ self.addCleanup(reset_consumer_registry)
+ self.addCleanup(cache.clear)
+
+ @parameterized.expand(
+ [
+ ("issue", "issues", "issue", "issue"),
+ ("pull_request", "pull_request", "pull_request", "pull_request"),
+ ]
+ )
+ @patch("products.error_tracking.backend.tasks.github.process_github_external_reference.delay")
+ @patch("posthog.ingress.github.provider.get_instance_setting", return_value="webhook-secret")
+ def test_verified_delivery_enqueues_supported_events(
+ self,
+ _name: str,
+ event_type: str,
+ resource_key: str,
+ expected_resource_type: str,
+ _get_instance_setting: Mock,
+ delay: Mock,
+ ) -> None:
+ payload = {
+ "action": "opened",
+ "installation": {"id": 42},
+ "repository": {"full_name": "example/app"},
+ "sender": {"login": "octocat"},
+ resource_key: {
+ "number": 7,
+ "title": "Fix checkout",
+ "body": "https://app.example.com/project/12/error_tracking/00000000-0000-0000-0000-000000000001",
+ "user": {"login": "octocat"},
+ "author_association": "MEMBER",
+ },
+ }
+ body = json.dumps(payload).encode()
+ signature = "sha256=" + hmac.new(b"webhook-secret", body, hashlib.sha256).hexdigest()
+
+ with (
+ patch("products.conversations.backend.facade.api.accept_github_event"),
+ patch("products.tasks.backend.facade.api.accept_github_event_for_loops"),
+ patch("products.tasks.backend.facade.api.accept_github_pull_request"),
+ patch("products.workflows.backend.facade.api.accept_github_event"),
+ ):
+ response = self.client.post(
+ "/webhooks/github/",
+ data=body,
+ content_type="application/json",
+ headers={
+ "X-Hub-Signature-256": signature,
+ "X-GitHub-Delivery": f"delivery-{event_type}",
+ "X-GitHub-Event": event_type,
+ },
+ )
+
+ assert response.status_code == 202
+ delay.assert_called_once_with(
+ team_id=12,
+ installation_id="42",
+ repository_full_name="example/app",
+ number=7,
+ title="Fix checkout",
+ resource_type=expected_resource_type,
+ actor_login="octocat",
+ issue_id="00000000-0000-0000-0000-000000000001",
+ fingerprint=None,
+ )
+
+
+@override_settings(SITE_URL="https://app.example.com")
+class TestGitHubExternalReferences(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # The repo-permission result is cached per actor, and the cache outlives a rolled-back test.
+ cache.clear()
+ self.addCleanup(cache.clear)
+
+ @parameterized.expand(
+ [
+ ("issue", "issues", "issue", "issues"),
+ ("pull_request", "pull_request", "pull_request", "pull"),
+ ]
+ )
+ def test_links_referenced_issues_with_team_and_installation_scope(
+ self, _name: str, event_type: str, resource_key: str, expected_github_path: str
+ ) -> None:
+ integration = Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.GITHUB.value,
+ integration_id="123",
+ config={"account": {"name": "acme"}},
+ sensitive_config={"access_token": "access-token"},
+ )
+ direct_issue = ErrorTrackingIssue.objects.create(team=self.team, name="Direct issue")
+ fingerprint_issue = ErrorTrackingIssue.objects.create(team=self.team, name="Fingerprint issue")
+ foreign_host_issue = ErrorTrackingIssue.objects.create(team=self.team, name="Foreign host issue")
+ fingerprint = "checkout/failure#group"
+ ErrorTrackingIssueFingerprintV2.objects.create(team=self.team, issue=fingerprint_issue, fingerprint=fingerprint)
+
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+ other_issue = ErrorTrackingIssue.objects.create(team=other_team, name="Other issue")
+
+ if event_type == "pull_request":
+ ErrorTrackingExternalReference.objects.create(
+ issue=direct_issue,
+ integration=integration,
+ external_context={"repository": "widgets", "number": 17, "title": "Old title"},
+ )
+
+ body = "\n".join(
+ [
+ f"https://app.example.com/project/{self.team.id}/error_tracking/{direct_issue.id}",
+ (
+ f"https://app.example.com/project/{self.team.id}/error_tracking/fingerprint/"
+ f"{quote(fingerprint, safe='')}"
+ ),
+ f"https://app.example.com/project/{other_team.id}/error_tracking/{other_issue.id}",
+ f"https://other.example.com/project/{self.team.id}/error_tracking/{foreign_host_issue.id}",
+ ]
+ )
+ payload = {
+ "action": "opened",
+ "installation": {"id": 123},
+ "repository": {"full_name": "acme/widgets"},
+ "sender": {"login": "maintainer"},
+ resource_key: {
+ "number": 17,
+ "title": "Fix checkout failures",
+ "body": body,
+ "user": {"login": "maintainer"},
+ "author_association": "MEMBER",
+ },
+ }
+
+ mismatched_owner_payload = {**payload, "repository": {"full_name": "other/widgets"}}
+ assert not any(
+ api.link_github_external_reference(job)
+ for job in api.prepare_github_external_reference_jobs(event_type, mismatched_owner_payload)
+ )
+
+ # An org member with read-only access to the repo passes the payload gate, so the repo
+ # permission is the only thing standing between them and a permanent reference.
+ read_only_payload = {**payload, "sender": {"login": "onlooker"}}
+ with patch.object(GitHubIntegration, "get_collaborator_permission", return_value="read") as read_permission:
+ assert not any(
+ api.link_github_external_reference(job)
+ for job in api.prepare_github_external_reference_jobs(event_type, read_only_payload)
+ )
+ read_permission.assert_called_with("acme/widgets", "onlooker")
+ assert not ErrorTrackingExternalReference.objects.filter(issue=fingerprint_issue).exists()
+
+ jobs = api.prepare_github_external_reference_jobs(event_type, payload)
+ with (
+ patch.object(GitHubIntegration, "get_collaborator_permission", return_value="write"),
+ patch.object(
+ ErrorTrackingIssue.objects,
+ "select_for_update",
+ wraps=ErrorTrackingIssue.objects.select_for_update,
+ ) as select_for_update,
+ ):
+ created_count = sum(api.link_github_external_reference(job) for job in jobs)
+
+ assert select_for_update.call_count == 2
+ references = {
+ reference.issue_id: reference
+ for reference in ErrorTrackingExternalReference.objects.select_related("integration").all()
+ }
+ assert created_count == (1 if event_type == "pull_request" else 2)
+ assert len(jobs) == 3
+ assert set(references) == {direct_issue.id, fingerprint_issue.id}
+ direct_context = references[direct_issue.id].external_context
+ assert direct_context is not None
+ assert direct_context["title"] == "Fix checkout failures"
+ for reference in references.values():
+ resolved_reference = api.get_external_reference(reference.id, self.team.id)
+ assert resolved_reference is not None
+ assert resolved_reference.external_url == f"https://github.com/acme/widgets/{expected_github_path}/17"
diff --git a/products/error_tracking/backend/webhook_consumers.py b/products/error_tracking/backend/webhook_consumers.py
new file mode 100644
index 000000000000..88e45cc7a549
--- /dev/null
+++ b/products/error_tracking/backend/webhook_consumers.py
@@ -0,0 +1,20 @@
+from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery
+
+
+def _enqueue_external_references(delivery: WebhookDelivery) -> None:
+ from products.error_tracking.backend.facade.github import ( # noqa: PLC0415 - keeps Celery and product logic off the registry import path
+ enqueue_github_external_references,
+ )
+
+ enqueue_github_external_references(delivery.event_type, dict(delivery.payload))
+
+
+WEBHOOK_CONSUMERS = (
+ WebhookConsumer(
+ name="error_tracking_external_references",
+ provider="github",
+ app="posthog",
+ event_types=frozenset({"issues", "pull_request"}),
+ handler=_enqueue_external_references,
+ ),
+)
diff --git a/products/error_tracking/turbo.json b/products/error_tracking/turbo.json
index 81d8b2d4fd6b..8bb3273e238f 100644
--- a/products/error_tracking/turbo.json
+++ b/products/error_tracking/turbo.json
@@ -13,6 +13,7 @@
"backend/max_tools.py",
"backend/temporal/**",
"backend/tasks/**",
+ "backend/webhook_consumers.py",
"backend/models.py",
"backend/migrations/**"
],