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): If BOT comes to Task with repo+user id, but no team GitHub integration - allow to user user's GitHub integration (#58042)

Alex Lebedev9d7cb255d903
diff --git a/products/signals/backend/report_generation/select_repo.py b/products/signals/backend/report_generation/select_repo.py
index 4608cb2f0a0f..de462f753d35 100644
--- a/products/signals/backend/report_generation/select_repo.py
+++ b/products/signals/backend/report_generation/select_repo.py
@@ -47,8 +47,10 @@ def resolve_team_github_integration(team_id: int, team: Team | None = None) -> G
"""Resolve the GitHub source the agent should use for this team."""
integration = (
Integration.objects.filter(team_id=team_id, kind="github")
- # Prioritize orgs vs users (alphabetically)
- .order_by("config__account__type", "id")
+ # Skip integrations whose installation has been synced and confirmed empty (0 repos)
+ .exclude(repository_cache=[], repository_cache_updated_at__isnull=False)
+ # Prioritize orgs vs users (alphabetically), then oldest first
+ .order_by("config__account__type", "created_at", "id")
.first()
)
# Prefer the first GitHub integration from the team
@@ -61,7 +63,8 @@ def resolve_team_github_integration(team_id: int, team: Team | None = None) -> G
kind=UserIntegration.IntegrationKind.GITHUB,
user__in=team.all_users_with_access(),
)
- .order_by("config__account__type", "id")
+ .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
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 708c515927ea..0cb699148b1b 100644
--- a/products/signals/backend/test/test_resolve_team_github_integration.py
+++ b/products/signals/backend/test/test_resolve_team_github_integration.py
@@ -1,5 +1,9 @@
+import datetime
+
import pytest
+from django.utils import timezone
+
from posthog.models import Organization, Team, User
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.organization import OrganizationMembership
@@ -26,24 +30,57 @@ def _create_user(email: str, organization: Organization, *, is_active: bool = Tr
return user
-def _create_team_integration(team: Team, *, integration_id: str = "team-1") -> Integration:
- return Integration.objects.create(
+_REPO_CACHE_ENTRY = {"full_name": "PostHog/posthog", "id": 1}
+
+
+def _create_team_integration(
+ team: Team,
+ *,
+ integration_id: str = "team-1",
+ account_type: str | None = None,
+ repository_cache: list[dict] | None = None,
+ cache_synced: bool = True,
+) -> Integration:
+ config: dict = {"installation_id": integration_id}
+ if account_type is not None:
+ config["account"] = {"type": account_type}
+ integration = Integration.objects.create(
team=team,
kind="github",
integration_id=integration_id,
- config={"installation_id": integration_id},
+ config=config,
sensitive_config={},
+ repository_cache=[_REPO_CACHE_ENTRY] if repository_cache is None else repository_cache,
)
-
-
-def _create_user_integration(user: User, *, integration_id: str = "user-1") -> UserIntegration:
- return UserIntegration.objects.create(
+ if cache_synced:
+ Integration.objects.filter(pk=integration.pk).update(repository_cache_updated_at=timezone.now())
+ integration.refresh_from_db()
+ return integration
+
+
+def _create_user_integration(
+ user: User,
+ *,
+ integration_id: str = "user-1",
+ account_type: str | None = None,
+ repository_cache: list[dict] | None = None,
+ cache_synced: bool = True,
+) -> UserIntegration:
+ config: dict = {"installation_id": integration_id}
+ if account_type is not None:
+ config["account"] = {"type": account_type}
+ integration = UserIntegration.objects.create(
user=user,
kind=UserIntegration.IntegrationKind.GITHUB,
integration_id=integration_id,
- config={"installation_id": integration_id},
+ config=config,
sensitive_config={},
+ repository_cache=[_REPO_CACHE_ENTRY] if repository_cache is None else repository_cache,
)
+ if cache_synced:
+ UserIntegration.objects.filter(pk=integration.pk).update(repository_cache_updated_at=timezone.now())
+ integration.refresh_from_db()
+ return integration
@pytest.mark.django_db
@@ -75,10 +112,15 @@ def test_falls_back_to_user_integration_when_no_team_integration(organization, t
@pytest.mark.django_db
-def test_picks_first_user_integration_by_id(organization, team):
+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
+ # 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)
+ )
_create_user_integration(second_user, integration_id="second")
resolved = resolve_team_github_integration(team.id)
@@ -94,3 +136,84 @@ def test_skips_user_integration_when_owner_has_no_team_access(organization, team
_create_user_integration(outsider, integration_id="outsider-int")
assert resolve_team_github_integration(team.id) is None
+
+
+def test_skips_team_integration_with_empty_repository_cache(organization, team):
+ user = _create_user("[email protected]", organization)
+ _create_team_integration(team, integration_id="team-empty", repository_cache=[])
+ user_int = _create_user_integration(user, integration_id="user-1")
+
+ resolved = resolve_team_github_integration(team.id)
+
+ assert isinstance(resolved, UserGitHubIntegration)
+ assert resolved.integration.id == user_int.id
+
+
+def test_skips_user_integration_with_empty_repository_cache(organization, team):
+ empty_user = _create_user("[email protected]", organization)
+ populated_user = _create_user("[email protected]", organization)
+ _create_user_integration(empty_user, integration_id="user-empty", repository_cache=[])
+ populated_int = _create_user_integration(populated_user, integration_id="user-populated")
+
+ resolved = resolve_team_github_integration(team.id)
+
+ assert isinstance(resolved, UserGitHubIntegration)
+ assert resolved.integration.id == populated_int.id
+
+
+def test_returns_none_when_all_integrations_have_empty_repository_cache(organization, team):
+ user = _create_user("[email protected]", organization)
+ _create_team_integration(team, integration_id="team-empty", repository_cache=[])
+ _create_user_integration(user, integration_id="user-empty", repository_cache=[])
+
+ assert resolve_team_github_integration(team.id) is None
+
+
+def test_keeps_team_integration_with_empty_unsynced_repository_cache(team):
+ # Freshly installed integration: cache is empty but never synced (updated_at is NULL).
+ # We can't yet conclude "0 repos" — keep it so select_repo can lazily sync.
+ integration = _create_team_integration(team, integration_id="team-fresh", repository_cache=[], cache_synced=False)
+
+ resolved = resolve_team_github_integration(team.id)
+
+ assert isinstance(resolved, GitHubIntegration)
+ assert resolved.integration.id == integration.id
+
+
+def test_keeps_user_integration_with_empty_unsynced_repository_cache(organization, team):
+ user = _create_user("[email protected]", organization)
+ integration = _create_user_integration(user, integration_id="user-fresh", repository_cache=[], cache_synced=False)
+
+ resolved = resolve_team_github_integration(team.id)
+
+ assert isinstance(resolved, UserGitHubIntegration)
+ assert resolved.integration.id == integration.id
+
+
+def test_prefers_org_account_over_user_account(organization, team):
+ # Org accounts sort before User accounts on `config__account__type` (alphabetical).
+ _create_team_integration(team, integration_id="user-acct", account_type="User")
+ org_int = _create_team_integration(team, integration_id="org-acct", account_type="Organization")
+
+ resolved = resolve_team_github_integration(team.id)
+
+ assert isinstance(resolved, GitHubIntegration)
+ assert resolved.integration.id == org_int.id
+
+
+def test_prefers_oldest_among_same_account_type(organization, team):
+ older = _create_team_integration(team, integration_id="org-old", account_type="Organization")
+ Integration.objects.filter(pk=older.pk).update(created_at=older.created_at - datetime.timedelta(hours=1))
+ _create_team_integration(team, integration_id="org-new", account_type="Organization")
+
+ resolved = resolve_team_github_integration(team.id)
+
+ assert isinstance(resolved, GitHubIntegration)
+ assert resolved.integration.id == older.id
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index fd4af4898603..9df5763fed16 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -321,6 +321,16 @@ class Task(DeletedMetaFields, models.Model):
)
if user_github_integration_is_usable(user_github_integration):
github_user_integration = user_github_integration.integration if user_github_integration else None
+ elif authorship_mode == PrAuthorshipMode.BOT and github_integration is None:
+ # If BOT starts a task, provides a repo, but there's no team GitHub Integration,
+ # then use the user_id BOT provided and get user's GitHub Integration instead
+ user_github_integration = resolve_user_github_integration_for_task(
+ task_stub,
+ repository=repository,
+ allow_refresh=True,
+ )
+ if user_github_integration is not None:
+ github_user_integration = user_github_integration.integration
if repository:
if not github_integration and github_user_integration is None and not is_public_sandbox_repo(repository):
diff --git a/products/tasks/backend/services/sandbox.py b/products/tasks/backend/services/sandbox.py
index e7f6a66a3fdb..eab9162eccbf 100644
--- a/products/tasks/backend/services/sandbox.py
+++ b/products/tasks/backend/services/sandbox.py
@@ -83,8 +83,9 @@ class SandboxConfig(BaseModel):
WORKING_DIR = "/tmp/workspace"
-PUBLIC_SANDBOX_REPOS: frozenset[str] = frozenset({"posthog/hedgebox"})
-"""Repos the sandbox is allowed to clone unauthenticated, even when the team has no GitHub integration."""
+PUBLIC_SANDBOX_REPOS: frozenset[str] = frozenset({"posthog/hedgebox", "posthog/.github"})
+"""Repos the sandbox is allowed to clone unauthenticated, even when the team has no GitHub integration"""
+# TODO: Remove `posthog/.github` when we switch repo discovery to repo-less agent (now it works as a lightweight dummy)
def is_public_sandbox_repo(repository: str | None) -> bool:
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index 9fbf6cfaef6c..a7d0580d3f23 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -466,3 +466,60 @@ class TestGetSandboxGitHubToken(TestCase):
result = get_sandbox_github_token(None, run_id="run-1", state={"pr_authorship_mode": "bot"})
assert result is None
+
+ def test_bot_authorship_falls_back_to_user_install_token_when_team_integration_missing(self) -> None:
+ from posthog.models import Organization, Team
+ from posthog.models.user import User
+ from posthog.models.user_integration import UserIntegration
+
+ organization = Organization.objects.create(name="bot-fallback-org")
+ Team.objects.create(organization=organization, name="bot-fallback-team")
+ user = User.objects.create(email="[email protected]")
+ user_integration = UserIntegration.objects.create(
+ user=user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id="install-1",
+ config={},
+ sensitive_config={"access_token": "ghs_user_install"},
+ )
+
+ result = get_sandbox_github_token(
+ None,
+ run_id="run-1",
+ state={"pr_authorship_mode": "bot"},
+ github_user_integration_id=str(user_integration.id),
+ )
+
+ assert result == "ghs_user_install"
+
+ def test_bot_authorship_prefers_team_integration_over_user_install_token(self) -> None:
+ from posthog.models import Integration, Organization, Team
+ from posthog.models.user import User
+ from posthog.models.user_integration import UserIntegration
+
+ organization = Organization.objects.create(name="bot-precedence-org")
+ team = Team.objects.create(organization=organization, name="bot-precedence-team")
+ team_integration = Integration.objects.create(
+ team=team,
+ kind="github",
+ integration_id="team-install",
+ config={},
+ sensitive_config={"access_token": "ghs_team"},
+ )
+ user = User.objects.create(email="[email protected]")
+ user_integration = UserIntegration.objects.create(
+ user=user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id="user-install",
+ config={},
+ sensitive_config={"access_token": "ghs_user_install"},
+ )
+
+ result = get_sandbox_github_token(
+ team_integration.id,
+ run_id="run-1",
+ state={"pr_authorship_mode": "bot"},
+ github_user_integration_id=str(user_integration.id),
+ )
+
+ assert result == "ghs_team"
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index f1b4422ebaf3..1ffe91a9dcdf 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -332,6 +332,15 @@ def get_github_token(github_integration_id: int) -> Optional[str]:
return github_integration.integration.access_token or None
+def get_user_github_token(github_user_integration_id: str) -> Optional[str]:
+ """Return the installation access token from a UserIntegration, refreshing if expired."""
+ integration = UserIntegration.objects.get(id=github_user_integration_id)
+ github_integration = UserGitHubIntegration(integration)
+ if github_integration.access_token_expired():
+ github_integration.refresh_access_token()
+ return github_integration.integration.sensitive_config.get("access_token") or None
+
+
def _normalize_repository(repository: str | None) -> str | None:
if not repository:
return None
@@ -527,24 +536,32 @@ def get_sandbox_github_token(
raise ReauthorizationRequired(
f"User-authored run {run_id} requires a linked GitHub account with repo access."
)
- elif github_integration_id is None:
- token = user_github_integration.get_usable_user_access_token()
- if token is None:
+ return get_github_token(github_integration_id)
+ if github_integration_id is None:
+ no_team_token: str | None = user_github_integration.get_usable_user_access_token()
+ if no_team_token is None:
raise ReauthorizationRequired(
f"User-authored run {run_id} requires a linked GitHub account with repo access."
)
+ return no_team_token
+ try:
+ token: str | None = user_github_integration.get_usable_user_access_token()
+ except ReauthorizationRequired:
+ token = None
+ if token is not None:
return token
- else:
- try:
- token = user_github_integration.get_usable_user_access_token()
- except ReauthorizationRequired:
- token = None
- if token is not None:
- return token
-
+ return get_github_token(github_integration_id)
+ elif pr_authorship_mode == PrAuthorshipMode.BOT:
+ if github_integration_id is not None:
+ return get_github_token(github_integration_id)
+ # BOT fallback for teams without an Integration row: borrow the
+ # installation access token from the UserIntegration the task was created with.
+ if github_user_integration_id:
+ return get_user_github_token(github_user_integration_id)
+ return None
+ # No authorship mode resolved (legacy callers without state and without a task).
if github_integration_id is None:
return None
-
return get_github_token(github_integration_id)
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index dd6a9f5dda2e..1768730f53e1 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -13,7 +13,9 @@ from django.test import TestCase
from parameterized import parameterized
from posthog.models import Integration, Organization, Team
+from posthog.models.organization import OrganizationMembership
from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration
from posthog.storage import object_storage
from products.tasks.backend.models import CodeInvite, SandboxEnvironment, SandboxSnapshot, Task, TaskRun
@@ -206,6 +208,53 @@ class TestTask(TestCase):
self.assertEqual(task.github_integration, integration)
mock_execute_workflow.assert_called_once()
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_create_and_run_signal_report_falls_back_to_user_integration(self, mock_execute_workflow):
+ # Signal reports are BOT-authored. When the team has no Integration row but the task
+ # creator has a UserIntegration that grants access to the repo, we should accept it
+ # instead of raising "Team does not have a GitHub integration".
+ user = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(user=user, organization=self.organization)
+ user_integration = UserIntegration.objects.create(
+ user=user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id="install-1",
+ config={"installation_id": "install-1"},
+ sensitive_config={"access_token": "ghs_user_install"},
+ repository_cache=[{"full_name": "posthog/posthog", "id": 1}],
+ )
+
+ task = Task.create_and_run(
+ team=self.team,
+ title="Signal Report",
+ description="Research",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ user_id=user.id,
+ repository="posthog/posthog",
+ )
+
+ self.assertIsNone(task.github_integration)
+ self.assertEqual(task.github_user_integration, user_integration)
+ mock_execute_workflow.assert_called_once()
+
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_create_and_run_signal_report_raises_when_no_integration_anywhere(self, mock_execute_workflow):
+ user = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(user=user, organization=self.organization)
+
+ with self.assertRaises(ValueError) as cm:
+ Task.create_and_run(
+ team=self.team,
+ title="Signal Report",
+ description="Research",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ user_id=user.id,
+ repository="posthog/posthog",
+ )
+
+ self.assertIn("does not have a GitHub integration", str(cm.exception))
+ mock_execute_workflow.assert_not_called()
+
@parameterized.expand(
[
("posthog-repo",),