: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(tasks): instrument org vs personal account on github pr webhooks (#71959)
Rafael Audibert2111e1fce92c
diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex f5ace2d8d0b0..00013b782ec6 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -103,6 +103,15 @@ logger = structlog.get_logger(__name__)GITHUB_REPOSITORY_NAME_RE = re.compile(r"[A-Za-z0-9_.\-]+")+def _github_account_type(owner_type: str | None) -> str | None:+ """Normalize GitHub's account ``type`` ("Organization" / "User") to org vs personal."""+ if owner_type == "Organization":+ return "organization"+ if owner_type == "User":+ return "personal"+ return None++def validate_github_repository_name(repo: str) -> str:"""Validate repository paths accepted by GitHub integration endpoints."""parts = repo.split("/")@@ -410,10 +419,17 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerialself.context["request"].user, self.context["get_team"]()):raise PermissionDenied("Editing an existing integration requires project admin access.")+ report_properties: dict[str, Any] = {"integration_kind": kind, "is_overwrite": is_overwrite}+ if kind == "github":+ # Surface whether the connected GitHub account is an org or a personal one, mirroring the+ # account_type we attach to PR webhook events. GitHub reports "Organization" / "User".+ owner_type = ((instance.config or {}).get("account") or {}).get("type")+ report_properties["repo_owner_type"] = owner_type+ report_properties["account_type"] = _github_account_type(owner_type)report_user_action(self.context["request"].user,"integration created",- {"integration_kind": kind, "is_overwrite": is_overwrite},+ report_properties,team=self.context["get_team"](),)return instancediff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex c2c23a7faffa..f28dc06d79d4 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -1996,6 +1996,21 @@ class TestIntegrationAPIKeyAccess:assert results[0]["kind"] == "twilio"+class TestGithubAccountTypeHelper:+ @parameterized.expand(+ [+ ("organization", "Organization", "organization"),+ ("user", "User", "personal"),+ ("missing", None, None),+ ("unknown", "Bot", None),+ ]+ )+ def test_github_account_type(self, _name, owner_type, expected):+ from posthog.api.integration import _github_account_type++ assert _github_account_type(owner_type) == expected++class TestGitHubIntegrationStateValidation:@pytest.fixture(autouse=True)def setup_environment(self, db):@@ -2161,6 +2176,63 @@ class TestGitHubIntegrationStateValidation:assert cache.get(f"github_authorize:{state_token}") is Noneassert cache.get(f"github_authorize_pending:{self.user.id}") is None+ @patch("posthog.api.integration.report_user_action")+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")+ @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.user_integration.user_github_integration_from_installation")+ def test_create_github_integration_reports_account_type(+ self,+ mock_user_integration,+ mock_from_install,+ mock_from_code,+ mock_verify,+ mock_report,+ client: HttpClient,+ ):+ from posthog.models.integration import GitHubUserAuthorization++ client.force_login(self.user)+ state_token = "account-type-token"+ store_unified_authorize_state(+ GitHubAuthorizeState(+ token=state_token,+ flow=FlowKind.TEAM_INSTALL,+ user_id=self.user.id,+ team_id=self.team.pk,+ next_url=None,+ ),+ )+ mock_from_code.return_value = GitHubUserAuthorization(+ gh_id=42,+ gh_login="testuser",+ access_token="ghu_test",+ refresh_token=None,+ access_token_expires_in=None,+ refresh_token_expires_in=None,+ )+ mock_verify.return_value = True+ mock_from_install.return_value = Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id="12345",+ config={"installation_id": "12345", "account": {"type": "Organization", "name": "acme"}},+ sensitive_config={"access_token": "ghs_test"},+ )++ response = client.post(+ f"/api/environments/{self.team.pk}/integrations/",+ {"kind": "github", "config": self._github_config(state=state_token)},+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.content+ mock_report.assert_called_once()+ props = mock_report.call_args.args[2]+ assert props["integration_kind"] == "github"+ assert props["repo_owner_type"] == "Organization"+ assert props["account_type"] == "organization"+@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")@patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex ffe0d763b7d8..7185eca0240b 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -18,7 +18,22 @@ from posthog.models.user import Userfrom products.signals.backend.models import SignalReportfrom products.signals.backend.task_run_artefacts import append_task_run_artefactfrom products.tasks.backend.models import Task, TaskRun-from products.tasks.backend.webhooks import find_task_run+from products.tasks.backend.webhooks import _account_type, find_task_run+++class TestAccountType(TestCase):+ @parameterized.expand(+ [+ ("org_owner", {"repository": {"owner": {"type": "Organization"}}}, "organization"),+ ("user_owner", {"repository": {"owner": {"type": "User"}}}, "personal"),+ ("org_fallback_no_owner", {"organization": {"login": "acme"}}, "organization"),+ ("org_owner_beats_missing_org", {"repository": {"owner": {"type": "Organization"}}}, "organization"),+ ("unknown", {"repository": {"full_name": "acme/widgets"}}, None),+ ("empty", {}, None),+ ]+ )+ def test_account_type(self, _name, payload, expected):+ self.assertEqual(_account_type(payload), expected)def generate_github_signature(payload: bytes, secret: str) -> str:@@ -726,7 +741,8 @@ class TestExternalPRWebhook(TestCase):return {"action": action,"installation": {"id": 555000},- "repository": {"full_name": "acme/widgets"},+ "repository": {"full_name": "acme/widgets", "owner": {"login": "acme", "type": "Organization"}},+ "organization": {"login": "acme"},"pull_request": {"html_url": "https://github.com/acme/widgets/pull/7","number": 7,@@ -775,6 +791,8 @@ class TestExternalPRWebhook(TestCase):self.assertEqual(props["pr_deletions"], 30)self.assertEqual(props["pr_changed_files"], 5)self.assertEqual(props["pr_commits"], 3)+ self.assertEqual(props["account_type"], "organization")+ self.assertEqual(props["repo_owner_type"], "Organization")self.assertIsNone(props["task_id"])self.assertIsNone(props["origin_product"])self.assertIsNone(props["title"])diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex 7ada9ba0e410..e65c7edc3a23 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -302,6 +302,23 @@ def _record_run_output_field(task_run: TaskRun, key: str, value: str | bool, fai_TASK_ATTRIBUTION_KEYS = ("task_id", "run_id", "origin_product", "signal_report_id", "environment", "mode", "title")+def _account_type(payload: dict) -> str | None:+ """Whether the webhook's repo is owned by a GitHub org or a personal account.++ ``repository.owner.type`` is "Organization" or "User"; the top-level+ ``organization`` object is present only for org-owned repos and backs it up+ when the owner block is missing. Returns None when neither signal is present.+ """+ owner_type = ((payload.get("repository") or {}).get("owner") or {}).get("type")+ if owner_type == "Organization":+ return "organization"+ if owner_type == "User":+ return "personal"+ if payload.get("organization"):+ return "organization"+ return None++def _pr_payload_properties(payload: dict) -> dict:pull_request = payload.get("pull_request") or {}return {@@ -314,6 +331,8 @@ def _pr_payload_properties(payload: dict) -> dict:"pr_deletions": pull_request.get("deletions"),"pr_changed_files": pull_request.get("changed_files"),"pr_commits": pull_request.get("commits"),+ "account_type": _account_type(payload),+ "repo_owner_type": ((payload.get("repository") or {}).get("owner") or {}).get("type"),}