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(signals): scope repo-selection GitHub fallback to org owners (#66717)

Andrew Maguire14c349ac8844
diff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.py
index fffc6d88457f..957bbdb3d5bc 100644
--- a/products/signals/backend/test/test_agentic_report_activity.py
+++ b/products/signals/backend/test/test_agentic_report_activity.py
@@ -216,7 +216,9 @@ async def test_select_repository_activity_does_not_raise_with_only_user_integrat
# was wired up, this combination raised `RuntimeError("No GitHub integration found ...")` and
# killed the activity. Now it must resolve a user_id and reach `select_repository_for_report`.
user = await sync_to_async(User.objects.create)(email=f"posthog-code-{random.randint(1, 99999)}@example.com")
- await sync_to_async(OrganizationMembership.objects.create)(user=user, organization_id=ateam.organization_id)
+ await sync_to_async(OrganizationMembership.objects.create)(
+ user=user, organization_id=ateam.organization_id, level=OrganizationMembership.Level.OWNER
+ )
await sync_to_async(UserIntegration.objects.create)(
user=user,
kind=UserIntegration.IntegrationKind.GITHUB,
diff --git a/products/signals/backend/test/test_resolve_team_github_integration.py b/products/signals/backend/test/test_resolve_team_github_integration.py
index 0cb699148b1b..c172b2816518 100644
--- a/products/signals/backend/test/test_resolve_team_github_integration.py
+++ b/products/signals/backend/test/test_resolve_team_github_integration.py
@@ -24,9 +24,15 @@ def team(organization):
return Team.objects.create(organization=organization, name="test-cascade-team")
-def _create_user(email: str, organization: Organization, *, is_active: bool = True) -> User:
+def _create_user(
+ email: str,
+ organization: Organization,
+ *,
+ is_active: bool = True,
+ level: OrganizationMembership.Level = OrganizationMembership.Level.OWNER,
+) -> User:
user = User.objects.create(email=email, is_active=is_active)
- OrganizationMembership.objects.create(user=user, organization=organization)
+ OrganizationMembership.objects.create(user=user, organization=organization, level=level)
return user
@@ -112,26 +118,137 @@ def test_falls_back_to_user_integration_when_no_team_integration(organization, t
@pytest.mark.django_db
-def test_picks_oldest_user_integration_among_org_members(organization, team):
- first_user = _create_user("[email protected]", organization)
- second_user = _create_user("[email protected]", organization)
- first_user_int = _create_user_integration(first_user, integration_id="first")
- # Backdate `first_user_int` so it sorts first by `created_at` regardless of
+def test_picks_newest_user_integration_among_owners(organization, team):
+ first_owner = _create_user("[email protected]", organization)
+ second_owner = _create_user("[email protected]", organization)
+ older_int = _create_user_integration(first_owner, integration_id="older")
+ # Backdate `older_int` so the other one is unambiguously newer regardless of
# auto_now_add resolution between the two creates.
- UserIntegration.objects.filter(pk=first_user_int.pk).update(
- created_at=first_user_int.created_at - datetime.timedelta(hours=1)
+ UserIntegration.objects.filter(pk=older_int.pk).update(
+ created_at=older_int.created_at - datetime.timedelta(hours=1)
+ )
+ newer_int = _create_user_integration(second_owner, integration_id="newer")
+
+ resolved = resolve_team_github_integration(team.id)
+
+ assert isinstance(resolved, UserGitHubIntegration)
+ assert resolved.integration.id == newer_int.id
+
+
+def test_ignores_non_owner_member_personal_github(organization, team):
+ # The bug: an org member's personal GitHub leaked into another team's report. A plain
+ # member (not an owner) must never have their personal repos borrowed for the team.
+ member = _create_user("[email protected]", organization, level=OrganizationMembership.Level.MEMBER)
+ _create_user_integration(member, integration_id="member-int")
+
+ assert resolve_team_github_integration(team.id) is None
+
+
+def test_prefers_owner_integration_over_member_integration(organization, team):
+ owner = _create_user("[email protected]", organization)
+ member = _create_user("[email protected]", organization, level=OrganizationMembership.Level.MEMBER)
+ # Member connected first; pre-fix this would have won by `created_at`.
+ member_int = _create_user_integration(member, integration_id="member-int")
+ UserIntegration.objects.filter(pk=member_int.pk).update(
+ created_at=member_int.created_at - datetime.timedelta(hours=1)
)
- _create_user_integration(second_user, integration_id="second")
+ owner_int = _create_user_integration(owner, integration_id="owner-int")
resolved = resolve_team_github_integration(team.id)
assert isinstance(resolved, UserGitHubIntegration)
- assert resolved.integration.id == first_user_int.id
+ assert resolved.integration.id == owner_int.id
+
+
+def test_prefers_owner_personal_account_over_org_account(organization, team):
+ # An owner who belongs to a big GitHub org (e.g. `posthog`) must not have that org's repos
+ # outrank their own personal account where the team's project actually lives.
+ owner = _create_user("[email protected]", organization)
+ org_int = _create_user_integration(owner, integration_id="owner-org", account_type="Organization")
+ # Backdate the personal one so the win is from the account-type preference, not recency.
+ personal_int = _create_user_integration(owner, integration_id="owner-personal", account_type="User")
+ UserIntegration.objects.filter(pk=personal_int.pk).update(
+ created_at=org_int.created_at - datetime.timedelta(hours=1)
+ )
+
+ resolved = resolve_team_github_integration(team.id)
+
+ assert isinstance(resolved, UserGitHubIntegration)
+ assert resolved.integration.id == personal_int.id
+
+
+def test_requester_own_integration_used_when_not_an_owner(organization, team):
+ # User-initiated path: a non-owner requester referencing their own connected repo must still
+ # resolve their own integration (their own credentials — not the cross-account leak the
+ # owner-only fallback guards against). Without `requester_user_id` this returns None.
+ member = _create_user("[email protected]", organization, level=OrganizationMembership.Level.MEMBER)
+ member_int = _create_user_integration(member, integration_id="member-int")
+
+ assert resolve_team_github_integration(team.id) is None
+
+ resolved = resolve_team_github_integration(team.id, requester_user_id=member.id)
+ assert isinstance(resolved, UserGitHubIntegration)
+ assert resolved.integration.id == member_int.id
+
+
+def test_requester_integration_preferred_over_owner_fallback(organization, team):
+ # The requester explicitly named a repo only they have connected, so their own integration
+ # must outrank an owner's fallback (which lists different repos).
+ owner = _create_user("[email protected]", organization)
+ member = _create_user("[email protected]", organization, level=OrganizationMembership.Level.MEMBER)
+ _create_user_integration(owner, integration_id="owner-int")
+ member_int = _create_user_integration(member, integration_id="member-int")
+
+ resolved = resolve_team_github_integration(team.id, requester_user_id=member.id)
+
+ assert isinstance(resolved, UserGitHubIntegration)
+ assert resolved.integration.id == member_int.id
+
+
+def test_requester_path_does_not_borrow_other_members_integration(organization, team):
+ # Passing a requester must only surface that requester's own integration — never another
+ # member's. A requester with no GitHub falls through to the owner-only fallback.
+ requester = _create_user("[email protected]", organization, level=OrganizationMembership.Level.MEMBER)
+ other_member = _create_user("[email protected]", organization, level=OrganizationMembership.Level.MEMBER)
+ _create_user_integration(other_member, integration_id="other-int")
+
+ assert resolve_team_github_integration(team.id, requester_user_id=requester.id) is None
+
+
+def test_requester_falls_back_to_owner_when_requester_has_no_github(organization, team):
+ # A requester with no GitHub of their own still benefits from the owner fallback.
+ owner = _create_user("[email protected]", organization)
+ requester = _create_user("[email protected]", organization, level=OrganizationMembership.Level.MEMBER)
+ owner_int = _create_user_integration(owner, integration_id="owner-int")
+
+ resolved = resolve_team_github_integration(team.id, requester_user_id=requester.id)
+
+ assert isinstance(resolved, UserGitHubIntegration)
+ assert resolved.integration.id == owner_int.id
+
+
+def test_team_integration_still_wins_over_requester(organization, team):
+ member = _create_user("[email protected]", organization, level=OrganizationMembership.Level.MEMBER)
+ _create_user_integration(member, integration_id="member-int")
+ team_int = _create_team_integration(team, integration_id="team-1")
+
+ resolved = resolve_team_github_integration(team.id, requester_user_id=member.id)
+
+ assert isinstance(resolved, GitHubIntegration)
+ assert resolved.integration.id == team_int.id
@pytest.mark.django_db
-def test_skips_user_integration_when_owner_has_no_team_access(organization, team):
- # Owner with no organization membership = no team access via `team.all_users_with_access()`.
+def test_skips_user_integration_when_owner_has_no_org_membership(team):
+ # A user with a GitHub integration but no membership in the team's org is not an owner.
outsider = User.objects.create(email="[email protected]")
_create_user_integration(outsider, integration_id="outsider-int")
diff --git a/products/signals/backend/test/test_resolve_user_id.py b/products/signals/backend/test/test_resolve_user_id.py
index 9f93543ca76b..eb662b03f616 100644
--- a/products/signals/backend/test/test_resolve_user_id.py
+++ b/products/signals/backend/test/test_resolve_user_id.py
@@ -20,9 +20,15 @@ def team(organization):
return Team.objects.create(organization=organization, name="test-resolve-user-team")
-def _create_user(email: str, organization: Organization, *, is_active: bool = True) -> User:
+def _create_user(
+ email: str,
+ organization: Organization,
+ *,
+ is_active: bool = True,
+ level: OrganizationMembership.Level = OrganizationMembership.Level.OWNER,
+) -> User:
user = User.objects.create(email=email, is_active=is_active)
- OrganizationMembership.objects.create(user=user, organization=organization)
+ OrganizationMembership.objects.create(user=user, organization=organization, level=level)
return user
diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.py
index 3055e821fa7a..c0f4bc2da0cf 100644
--- a/products/tasks/backend/logic/repo_selection/agent.py
+++ b/products/tasks/backend/logic/repo_selection/agent.py
@@ -2,12 +2,15 @@ from __future__ import annotations
import json
import logging
-from collections.abc import Callable
+from collections.abc import Callable, Iterable
from typing import TYPE_CHECKING
+from django.db.models import Case, IntegerField, Value, When
+
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.integration_repository_cache import GitHubRepositoryFullCache
+from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
from posthog.sync import database_sync_to_async
@@ -60,8 +63,51 @@ class RepoSelectionUnavailableError(Exception):
super().__init__(reason)
-def resolve_team_github_integration(team_id: int, team: Team | None = None) -> GitHubIntegrationBase | None:
- """Resolve the GitHub source the agent should use for this team."""
+def _first_user_github_integration(user_ids: Iterable[int]) -> UserIntegration | None:
+ """Pick one GitHub ``UserIntegration`` among ``user_ids`` to act as a fallback source.
+
+ Among the candidates we prefer a personal (``User``) account over an organization the user
+ merely belongs to (a ``posthog/*`` org the user happens to work in must not outrank their own
+ repos), then the most recently connected one. Integrations whose installation has been synced
+ and confirmed empty (0 repos) are skipped.
+ """
+ return (
+ UserIntegration.objects.filter(
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ user_id__in=user_ids,
+ )
+ .exclude(repository_cache=[], repository_cache_updated_at__isnull=False)
+ .annotate(
+ _is_org_account=Case(
+ When(config__account__type="User", then=Value(0)),
+ default=Value(1),
+ output_field=IntegerField(),
+ )
+ )
+ .order_by("_is_org_account", "-created_at", "-id")
+ .first()
+ )
+
+
+def resolve_team_github_integration(
+ team_id: int, team: Team | None = None, requester_user_id: int | None = None
+) -> GitHubIntegrationBase | None:
+ """Resolve the GitHub source the agent should use for this team.
+
+ A team-level integration always wins. When the team has none, the fallback depends on context:
+
+ - ``requester_user_id`` set (user-initiated path, e.g. a sandbox chat message): the requester
+ acts on their own behalf, so their own connected GitHub stands in next — using their own
+ credentials is never a cross-account leak, and it lets them reference repos that only they
+ have connected.
+ - Otherwise (scheduled/team contexts with no requester): fall back to a GitHub integration
+ connected by an *organization owner* — never an arbitrary member. This fallback used to span
+ ``team.all_users_with_access()`` (org-wide), which let one member's personal GitHub repos
+ surface as the candidate list for another member's report — a wrong-repo / cross-account leak.
+
+ The owner fallback still applies after the requester check, so an owner-connected source backs
+ a requester who has none of their own.
+ """
integration = (
Integration.objects.filter(team_id=team_id, kind="github")
# Skip integrations whose installation has been synced and confirmed empty (0 repos)
@@ -73,20 +119,24 @@ def resolve_team_github_integration(team_id: int, team: Team | None = None) -> G
# Prefer the first GitHub integration from the team
if integration is not None:
return GitHubIntegration(integration)
- if team is None:
- team = Team.objects.get(id=team_id)
- user_integration = (
- UserIntegration.objects.filter(
- kind=UserIntegration.IntegrationKind.GITHUB,
- user__in=team.all_users_with_access(),
- )
- .exclude(repository_cache=[], repository_cache_updated_at__isnull=False)
- .order_by("config__account__type", "created_at", "id")
- .first()
- )
- # If no team integration - pick the integration of the first user
- if user_integration is not None:
- return UserGitHubIntegration(user_integration)
+
+ # User-initiated path: the requester's own connected GitHub (their own credentials, not a leak)
+ # takes precedence over the owner fallback so they can reference repos only they have connected.
+ if requester_user_id is not None:
+ requester_integration = _first_user_github_integration([requester_user_id])
+ if requester_integration is not None:
+ return UserGitHubIntegration(requester_integration)
+
+ organization = (team if team is not None else Team.objects.get(id=team_id)).organization
+ owner_user_ids = OrganizationMembership.objects.filter(
+ organization=organization,
+ level=OrganizationMembership.Level.OWNER,
+ user__is_active=True,
+ ).values_list("user_id", flat=True)
+ # If no team integration - pick an org owner's integration (personal account preferred)
+ owner_integration = _first_user_github_integration(owner_user_ids)
+ if owner_integration is not None:
+ return UserGitHubIntegration(owner_integration)
return None
diff --git a/products/tasks/backend/logic/repo_selection/cascade.py b/products/tasks/backend/logic/repo_selection/cascade.py
index b9cc66ddf270..2cafea7a75c2 100644
--- a/products/tasks/backend/logic/repo_selection/cascade.py
+++ b/products/tasks/backend/logic/repo_selection/cascade.py
@@ -22,9 +22,15 @@ async def select_repository_for_message(
avoid the repo-selection LLM agent here. Messages without an explicit connected `owner/repo`
mention return `None`, which starts a repo-less sandbox. Selection must never block the
conversation from starting, so this never raises — every failure degrades to "no repo".
+
+ This is the user-initiated path, so we pass `user_id` as the requester: their own connected
+ GitHub is a valid source even if they aren't an org owner (it's their own credentials, not a
+ cross-account leak), letting them reference repos only they have connected.
"""
try:
- github = await database_sync_to_async(resolve_team_github_integration, thread_sensitive=False)(team_id)
+ github = await database_sync_to_async(resolve_team_github_integration, thread_sensitive=False)(
+ team_id, requester_user_id=user_id
+ )
if github is None:
return None
candidates = await database_sync_to_async(_list_candidate_repos, thread_sensitive=False)(github, team_id)