: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
fix(tasks): scope sandbox github tokens to the run's repos (#114896)
Charles Vien31110b11f783
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex e0dc95bde431..d29caf833a97 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -579,12 +579,13 @@ class GitHubIntegrationBase:def mint_scoped_installation_token(self,- permissions: Mapping[str, str],+ permissions: Mapping[str, str] | None,repositories: list[str] | None = None,) -> str:"""Mint an ephemeral installation token downscoped to ``permissions`` (e.g.``{"contents": "read", "metadata": "read"}``) and optionally to ``repositories``- (bare repo names, no owner prefix).+ (bare repo names, no owner prefix). ``None`` permissions keep every permission the+ installation holds.The token is returned to the caller and deliberately NOT persisted: the cached``sensitive_config`` token is the shared full-permission credential every other@@ -597,11 +598,14 @@ class GitHubIntegrationBase:if not installation_id:raise GitHubIntegrationError("No GitHub App installation id on this integration")- body: dict[str, Any] = {"permissions": dict(permissions)}+ body: dict[str, Any] = {}+ if permissions is not None:+ body["permissions"] = dict(permissions)if repositories:body["repositories"] = repositoriesresponse = self.client_request(f"installations/{installation_id}/access_tokens", method="POST", json_body=body)+ raise_if_github_rate_limited(response)try:data = response.json()except ValueError:@@ -692,15 +696,17 @@ class GitHubIntegrationBase:name = account.get("name") if isinstance(account, dict) else Nonereturn not name or str(name) == str(installation_id)- def ensure_account_name(self) -> bool:- """Replace a placeholder account name with the real GitHub login, at most once per cooldown.+ def ensure_account_name(self, *, force_refresh: bool = False) -> bool:+ """Refresh a placeholder (or suspected stale) login, at most once per cooldown.Skips installations already marked unavailable, since the lookup would fail the same way.Returns True when the name was healed. Persists the attempt timestamp either way so a brokeninstallation costs one GitHub call per cooldown window, not one per list request."""installation_id = self.github_installation_id- if not installation_id or self.installation_unavailable() or not self.account_name_needs_heal():+ if not installation_id or self.installation_unavailable():+ return False+ if not force_refresh and not self.account_name_needs_heal():return Falsenow = int(time.time())last_attempt = self.integration.config.get(ACCOUNT_NAME_HEAL_ATTEMPTED_AT_CONFIG_KEY)diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pyindex ba84879b108d..d6f6ff40073e 100644--- a/posthog/models/test/integration/test_github.py+++ b/posthog/models/test/integration/test_github.py@@ -289,30 +289,47 @@ class TestGitHubIntegrationModel(BaseTest):return _client_request+ @parameterized.expand(+ [+ ("uninstalled", 404, {}, GitHubIntegrationError, True),+ ("rate_limited", 429, {"retry-after": "30"}, GitHubRateLimitError, False),+ ]+ )@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- def test_mint_scoped_installation_token_marks_uninstalled_installation(self, mock_client_request):+ def test_mint_scoped_installation_token_failure(+ self, _name, status_code, headers, expected_error, marked_unavailable, mock_client_request+ ):integration = self.create_integration({"installation_id": "INSTALL", "expires_in": 3600, "refreshed_at": 1704110400},{"access_token": "FULL_TOKEN"},)- mock_response = MagicMock(status_code=404, text="Not Found")+ mock_response = MagicMock(status_code=status_code, headers=headers, text="Not Found")mock_response.json.return_value = {"message": "Not Found"}mock_client_request.return_value = mock_responsegithub = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)- with pytest.raises(GitHubIntegrationError):+ with pytest.raises(expected_error):github.mint_scoped_installation_token({"contents": "read"})# Without the permanently-gone marker, every scheduled run re-mints a dead installation# forever — the marker is what lets callers skip it until the customer reconnects.integration.refresh_from_db()assert (- GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).installation_unavailable() is True+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).installation_unavailable()+ is marked_unavailable)- assert "expires_in" not in integration.config+ assert ("expires_in" not in integration.config) is marked_unavailable+ @parameterized.expand(+ [+ ("permissions", {"contents": "read"}, None, {"permissions": {"contents": "read"}}),+ ("repositories", None, ["api"], {"repositories": ["api"]}),+ ]+ )@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- def test_mint_scoped_installation_token_downscopes_without_persisting(self, mock_client_request):+ def test_mint_scoped_installation_token_downscopes_without_persisting(+ self, _name, permissions, repositories, expected_body, mock_client_request+ ):integration = self.create_integration({"installation_id": "INSTALL"}, {"access_token": "FULL_TOKEN"})mock_response = MagicMock(status_code=201)mock_response.json.return_value = {"token": "SCOPED_TOKEN", "expires_at": "2024-01-01T13:00:00Z"}@@ -320,12 +337,12 @@ class TestGitHubIntegrationModel(BaseTest):token = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL- ).mint_scoped_installation_token({"contents": "read"})+ ).mint_scoped_installation_token(permissions, repositories=repositories)assert token == "SCOPED_TOKEN"# Without the permissions body the mint returns a FULL-permission token — a silent# privilege escalation for every read-only sandbox.- assert mock_client_request.call_args.kwargs["json_body"] == {"permissions": {"contents": "read"}}+ assert mock_client_request.call_args.kwargs["json_body"] == expected_body# The scoped token must never clobber the shared full-permission credential other flows read.integration.refresh_from_db()assert integration.sensitive_config == {"token": "REFRESH", "access_token": "FULL_TOKEN"}diff --git a/products/tasks/backend/temporal/conftest.py b/products/tasks/backend/temporal/conftest.pyindex 945e3ffb4741..9850c2ddefca 100644--- a/products/tasks/backend/temporal/conftest.py+++ b/products/tasks/backend/temporal/conftest.py@@ -4,6 +4,7 @@ import randomfrom collections.abc import Iteratorimport pytest+from unittest.mock import patchfrom temporalio.testing import ActivityEnvironment@@ -132,7 +133,11 @@ def github_integration(team):sensitive_config={"access_token": "fake_token"},)- yield integration+ # The fake installation must not call GitHub when minting scoped tokens either.+ with patch(+ "posthog.models.integration.GitHubIntegration.mint_scoped_installation_token", return_value="fake_token"+ ):+ yield integrationintegration.delete()diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 4487834ac6f9..da592d0c8e48 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -10,10 +10,13 @@ from typing import Anyfrom django.conf import settingsfrom django.utils import timezone+import requestsimport posthoganalyticsfrom temporalio import activityfrom posthog.dataclasses import frozen+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from posthog.models.github_integration_base import GitHubIntegrationErrorfrom posthog.models.user_integration import ReauthorizationRequiredfrom posthog.temporal.common.utils import asyncify@@ -29,7 +32,10 @@ from products.tasks.backend.exceptions import (ComputeBillingLimitError,CredentialUnavailableError,GitHubAuthenticationError,+ GitHubRateLimitedError,OAuthTokenError,+ ProcessTaskError,+ ProcessTaskTransientError,RepositoryCloneError,SandboxNetworkPolicyError,TaskInvalidStateError,@@ -78,6 +84,9 @@ from products.tasks.backend.temporal.observability import (log_activity_execution,log_with_activity_context,)+from products.tasks.backend.temporal.process_task.activities.get_pr_context import (+ DEFAULT_GITHUB_RATE_LIMIT_BACKOFF_SECONDS,+)from products.tasks.backend.temporal.process_task.organization import check_organization_executionfrom products.tasks.backend.temporal.process_task.sandbox_connection import persist_sandbox_connectionfrom products.tasks.backend.temporal.process_task.sandbox_credentials import (@@ -396,6 +405,17 @@ def _repository_snapshot_integration_id(ctx: TaskProcessingContext, *, has_repo:return ctx.github_integration_id+def _github_token_error(error: Exception, message: str, context: dict[str, Any]) -> ProcessTaskError:+ if isinstance(error, GitHubRateLimitError | GitHubEgressBudgetExhausted):+ retry_after = getattr(error, "retry_after", None) or DEFAULT_GITHUB_RATE_LIMIT_BACKOFF_SECONDS+ return GitHubRateLimitedError(f"{message}; retrying in {retry_after}s", context, retry_after=retry_after)+ if isinstance(error, requests.ConnectionError | requests.Timeout) or (+ isinstance(error, GitHubIntegrationError) and error.status_code is not None and error.status_code >= 500+ ):+ return ProcessTaskTransientError(message, context, cause=error)+ return GitHubAuthenticationError(message, context, cause=error)++def _resolve_sandbox_github_token(ctx: TaskProcessingContext,*,@@ -420,7 +440,7 @@ def _resolve_sandbox_github_token(stays credential-less, and an entitled discussion can clone a private repository and push."""if ctx.github_read_access:- github_token = get_readonly_github_token(ctx.team_id) or ""+ github_token = get_readonly_github_token(ctx.team_id, repositories=ctx.repositories) or ""emit_agent_log(ctx.run_id,"debug",@@ -458,10 +478,10 @@ def _resolve_sandbox_github_token(cause=e,)except Exception as e:- raise GitHubAuthenticationError(+ raise _github_token_error(+ e,f"Failed to get GitHub token for integration {ctx.github_integration_id}",{"github_integration_id": ctx.github_integration_id, "task_id": ctx.task_id, "error": str(e)},- cause=e,)@@ -1355,7 +1375,7 @@ def inject_fresh_tokens_on_resume(input: InjectFreshTokensOnResumeInput) -> None# Same priority rule as fresh provisioning (_resolve_sandbox_github_token): a# read-only run must never regain the write-capable token on resume, cloned repos or# not. Best-effort, since an empty token just leaves the sandbox without GitHub access.- github_token = get_readonly_github_token(ctx.team_id) or ""+ github_token = get_readonly_github_token(ctx.team_id, repositories=ctx.repositories) or ""elif ctx.has_github_credentials:try:github_token = (@@ -1377,14 +1397,14 @@ def inject_fresh_tokens_on_resume(input: InjectFreshTokensOnResumeInput) -> Nonecause=e,)except Exception as e:- raise GitHubAuthenticationError(+ raise _github_token_error(+ e,f"Failed to refresh GitHub token for integration {ctx.github_integration_id}",{"github_integration_id": ctx.github_integration_id,"task_id": ctx.task_id,"error": str(e),},- cause=e,)try:diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py b/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.pyindex 10f588c8a720..0d41faffaeaa 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py@@ -92,7 +92,7 @@ class TestInjectFreshTokensOnResumeActivity:patch("products.tasks.backend.temporal.process_task.activities.provision_sandbox.get_readonly_github_token",return_value="ghs_readonly",- ),+ ) as resolve_readonly,patch("products.tasks.backend.temporal.process_task.activities.provision_sandbox.get_sandbox_github_token") as resolve_full,@@ -110,6 +110,7 @@ class TestInjectFreshTokensOnResumeActivity:),)+ resolve_readonly.assert_called_once_with(context.team_id, repositories=context.repositories)resolve_full.assert_not_called()# Both clones carry the token in their own `origin`, so both remotes are rewritten.rewritten = [c.args[0] for c in sandbox.execute.call_args_list if "x-access-token:ghs_readonly" in c.args[0]]diff --git a/products/tasks/backend/temporal/process_task/sandbox_credentials.py b/products/tasks/backend/temporal/process_task/sandbox_credentials.pyindex 9f59cf45e1fc..79929566c1e0 100644--- a/products/tasks/backend/temporal/process_task/sandbox_credentials.py+++ b/products/tasks/backend/temporal/process_task/sandbox_credentials.py@@ -397,7 +397,7 @@ class GitHubSandboxCredential:# repositories decide what the sandbox can read, never what it can write. Re-mint the same# read-only grant instead; best-effort like the original.if ctx.github_read_access:- token = get_readonly_github_token(ctx.team_id)+ token = get_readonly_github_token(ctx.team_id, repositories=ctx.repositories)if token and _loop_owner_credentials_revoked(task, ctx.state):token = Noneif token:@@ -533,7 +533,7 @@ class GitHubSandboxCredential:cause=cause,)try:- return get_github_token(task.github_integration_id)+ return get_github_token(task.github_integration_id, repositories=ctx.repositories)except Integration.DoesNotExist as e:raise CredentialUnavailableError("GitHub integration for this run no longer exists",diff --git a/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.pyindex f7e6f1a7c8e8..245482467ed0 100644--- a/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py+++ b/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py@@ -160,13 +160,14 @@ class TestGitHubSandboxCredential:patch("products.tasks.backend.temporal.process_task.sandbox_credentials.get_readonly_github_token",return_value="ghs_readonly",- ),+ ) as resolve_readonly,patch("products.tasks.backend.temporal.process_task.sandbox_credentials.get_sandbox_github_token") as resolve_full,):outcome = GitHubSandboxCredential().refresh(sandbox, ctx, MagicMock())+ resolve_readonly.assert_called_once_with(ctx.team_id, repositories=ctx.repositories)resolve_full.assert_not_called()assert outcome.refreshed is Trueassert b"ghs_readonly" in sandbox.write_file.call_args.args[1]@@ -334,7 +335,7 @@ class TestSharedUserIntegrationRefresh:assert outcome.refreshed is Trueassert outcome.next_refresh_seconds == 20 * 60- installation_token.assert_called_once_with(456)+ installation_token.assert_called_once_with(456, repositories=["explore-science/paper-wizard-frontend"])apply.assert_called_once_with(sandbox, ["explore-science/paper-wizard-frontend"], "ghs_team")def test_reauthorization_without_team_integration_raises_credential_unavailable(self):diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex ea7aa244eea2..a2df0b3f9c6b 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -834,6 +834,65 @@ class TestGetGithubToken(TestCase):with self.assertRaises(CredentialUnavailableError):get_github_token(integration.id)+ @parameterized.expand(+ [+ ("renamed_account", "OldAcme", ["acme/api"], ["api"], "ghs_scoped"),+ ("dedupes_owner_and_case", "Acme", ["Acme/API", "acme/api", "acme/web"], ["api", "web"], "ghs_scoped"),+ ("drops_public_bootstrap_repo", "Acme", ["acme/web", "PostHog/.github"], ["web"], "ghs_scoped"),+ ("public_bootstrap_only_keeps_shared_token", "Acme", ["PostHog/.github"], None, "ghs_shared"),+ ("drops_repo_another_account_owns", "Acme", ["acme/web", "evilorg/api"], ["web"], "ghs_scoped"),+ ("another_account_only_gets_no_token", "Acme", ["evilorg/api"], None, None),+ ("placeholder_account_rejects_other_owner", "INSTALL", ["evilorg/api"], None, None),+ ("placeholder_account_heals", "INSTALL", ["acme/api"], ["api"], "ghs_scoped"),+ ("missing_account_heals", None, ["acme/api"], ["api"], "ghs_scoped"),+ ("placeholder_heal_fails", "INSTALL", ["evilorg/api"], None, None, 500),+ ("missing_heal_fails", None, ["acme/api"], None, None, 500),+ ]+ )+ def test_repositories_get_a_cached_scoped_token_instead_of_the_shared_one(+ self, _name, account_name, repositories, expected_mint_repositories, expected_token, lookup_status=200+ ):+ from posthog.models import Integration, Organization, Team+ from posthog.models.integration import GitHubIntegration++ from products.tasks.backend.redis import get_tasks_cache+ from products.tasks.backend.temporal.process_task.utils import get_github_token++ get_tasks_cache().clear()+ org = Organization.objects.create(name="o")+ team = Team.objects.create(organization=org, name="t")+ integration = Integration.objects.create(+ team=team,+ kind="github",+ integration_id="INSTALL",+ config={"installation_id": "INSTALL", "account": {"type": "Organization", "name": account_name}},+ sensitive_config={"access_token": "ghs_shared"},+ )++ with (+ patch.object(GitHubIntegration, "mint_scoped_installation_token", return_value="ghs_scoped") as mint,+ patch.object(+ GitHubIntegration,+ "client_request",+ return_value=MagicMock(+ status_code=lookup_status, json=lambda: {"account": {"login": "Acme", "type": "Organization"}}+ ),+ ) as lookup,+ ):+ tokens = [get_github_token(integration.id, repositories=repositories) for _ in range(2)]++ if account_name in ("OldAcme", "INSTALL", None) or (+ account_name == "Acme" and any(r.startswith("evilorg/") for r in repositories)+ ):+ lookup.assert_called_once_with("installations/INSTALL")+ else:+ lookup.assert_not_called()+ assert tokens == [expected_token, expected_token]+ if expected_mint_repositories is None:+ mint.assert_not_called()+ else:+ mint.assert_called_once_with(None, repositories=expected_mint_repositories)+class TestSlackTaskRunActorUser(TestCase):def test_credential_user_grandfathers_legacy_runs_without_actor_state(self) -> None:@@ -952,7 +1011,7 @@ class TestGetSandboxGitHubToken(SimpleTestCase):if has_identity:mock_resolve.assert_called_once_with(identity)if error_case in ("missing", "reauthorization", "empty_token"):- mock_get_github_token.assert_called_once_with(123)+ mock_get_github_token.assert_called_once_with(123, repositories=[])else:mock_get_github_token.assert_not_called()@@ -989,14 +1048,26 @@ class TestGetSandboxGitHubToken(SimpleTestCase):created_by=MagicMock(name="creator"),)+ @parameterized.expand(+ [+ ("repo_less", {}, None, []),+ ("task_repository", {}, "acme/api", ["acme/api"]),+ ("pinned_list_ignores_changed_task_repository", {"repositories": ["acme/api"]}, "acme/new", ["acme/api"]),+ ("empty_pinned_list_ignores_task_repository", {"repositories": []}, "acme/api", []),+ ]+ )@patch("products.tasks.backend.temporal.process_task.utils.get_github_token")- def test_bot_authorship_uses_installation_token(self, mock_get_github_token) -> None:+ def test_bot_authorship_scopes_installation_token_to_run_repositories(+ self, _name, extra_state, repository, expected_repositories, mock_get_github_token+ ) -> None:mock_get_github_token.return_value = "ghs_bot"- result = get_sandbox_github_token(123, run_id="run-1", state={"pr_authorship_mode": "bot"})+ result = get_sandbox_github_token(+ 123, run_id="run-1", state={"pr_authorship_mode": "bot", **extra_state}, repository=repository+ )assert result == "ghs_bot"- mock_get_github_token.assert_called_once_with(123)+ mock_get_github_token.assert_called_once_with(123, repositories=expected_repositories)@patch("products.tasks.backend.temporal.process_task.utils.get_github_token")def test_no_state_falls_through_to_installation_token(self, mock_get_github_token) -> None:@@ -1005,7 +1076,7 @@ class TestGetSandboxGitHubToken(SimpleTestCase):result = get_sandbox_github_token(123, run_id="run-1", state=None)assert result == "ghs_default"- mock_get_github_token.assert_called_once_with(123)+ mock_get_github_token.assert_called_once_with(123, repositories=[])@patch("products.tasks.backend.temporal.process_task.utils.get_github_token")def test_empty_state_falls_through_to_installation_token(self, mock_get_github_token) -> None:@@ -1014,7 +1085,7 @@ class TestGetSandboxGitHubToken(SimpleTestCase):result = get_sandbox_github_token(123, run_id="run-1", state={})assert result == "ghs_default"- mock_get_github_token.assert_called_once_with(123)+ mock_get_github_token.assert_called_once_with(123, repositories=[])def test_no_integration_id_returns_none(self) -> None:result = get_sandbox_github_token(None, run_id="run-1", state={"pr_authorship_mode": "bot"})diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex fcc78a5318ad..63cd91e55efd 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -16,6 +16,7 @@ from pydantic import BaseModelfrom posthog.egress.limiter.policies import Priorityfrom posthog.enums import LabeledStrEnumfrom posthog.llm.gateway_client import GatewayNotConfiguredError, ensure_scout_trial_capture_ready+from posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import GitHubIntegration, Integrationfrom posthog.models.user import Userfrom posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegration@@ -59,6 +60,7 @@ from products.tasks.backend.logic.services.run_actor import (is_slack_interaction_state as is_slack_interaction_state,loop_owner_eligible_for_credentials,)+from products.tasks.backend.logic.services.sandbox import is_public_sandbox_repofrom products.tasks.backend.redis import get_tasks_cachefrom products.tasks.backend.temporal.process_task.ai_gateway_token import (AI_GATEWAY_TOKEN_MINTS,@@ -878,7 +880,57 @@ def get_sandbox_ph_mcp_configs(]-def get_github_token(github_integration_id: int) -> Optional[str]:+# GitHub installation tokens expire after 1 hour and sandboxes refresh theirs every 20 minutes, so a+# token cached for 30 minutes still outlives the next refresh.+SCOPED_GITHUB_TOKEN_CACHE_TTL_SECONDS = 30 * 60+++def _private_repositories(repositories: Sequence[str]) -> list[str]:+ # Public sandbox repos clone without credentials and usually sit outside the installation,+ # where GitHub rejects a scoped mint that names them.+ return [repository for repository in repositories if not is_public_sandbox_repo(repository)]+++def _installation_repository_names(github_integration: GitHubIntegrationBase, repositories: Sequence[str]) -> list[str]:+ # GitHub scopes a mint by bare repo name, so a repo another account owns would get the installation's+ # repo of the same name. Do not mint until the installation owner is known.+ owner = None if github_integration.account_name_needs_heal() else github_integration.organization().lower()+ if owner is None or any(repository.lower().rpartition("/")[0] != owner for repository in repositories):+ github_integration.ensure_account_name(force_refresh=True)+ if github_integration.account_name_needs_heal():+ return []+ owner = github_integration.organization().lower()+ names: set[str] = set()+ for repository in repositories:+ repository_owner, _, name = repository.lower().rpartition("/")+ if repository_owner == owner:+ names.add(name)+ return sorted(names)+++def _sandbox_repositories(state: dict[str, Any] | None, repository: str | None) -> list[str]:+ # Same rule as TaskProcessingContext.repositories, so the token covers exactly what the run clones.+ pinned = (state or {}).get("repositories")+ if isinstance(pinned, list) and all(isinstance(r, str) for r in pinned):+ return pinned+ return [repository] if repository else []+++def _mint_repository_scoped_token(github_integration: GitHubIntegrationBase, repositories: Sequence[str]) -> str | None:+ names = _installation_repository_names(github_integration, repositories)+ if not names:+ return None+ cache_key = f"task-sandbox-github-token:{github_integration.github_installation_id}:{','.join(names)}"+ cache = get_tasks_cache()+ cached = cache.get(cache_key)+ if isinstance(cached, str) and cached:+ return cached+ token = github_integration.mint_scoped_installation_token(None, repositories=names)+ cache.set(cache_key, token, timeout=SCOPED_GITHUB_TOKEN_CACHE_TTL_SECONDS)+ return token+++def get_github_token(github_integration_id: int, repositories: Sequence[str] = ()) -> Optional[str]:integration = Integration.objects.get(id=github_integration_id)github_integration = GitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)@@ -887,6 +939,9 @@ def get_github_token(github_integration_id: int) -> Optional[str]:"GitHub App installation for this integration is uninstalled or suspended",{"github_integration_id": github_integration_id},)+ private_repositories = _private_repositories(repositories)+ if private_repositories:+ return _mint_repository_scoped_token(github_integration, private_repositories)if github_integration.access_token_expired():github_integration.refresh_access_token()@@ -935,8 +990,8 @@ def resolve_readonly_github_integration(team_id: int) -> GitHubIntegration | Nonreturn integration-def get_readonly_github_token(team_id: int) -> Optional[str]:- """Mint an ephemeral read-only GitHub token for a repo-less sandbox, or None.+def get_readonly_github_token(team_id: int, repositories: Sequence[str] = ()) -> Optional[str]:+ """Mint an ephemeral read-only GitHub token scoped to the sandbox repositories, or None.Resolves the same integration the repo-selection agent would use for this team, then mints aninstallation token downscoped to read-only permissions. Team-level installations only: the@@ -953,16 +1008,25 @@ def get_readonly_github_token(team_id: int) -> Optional[str]:if integration is None:logger.info("No mintable team-level GitHub integration for team %d, skipping read-only token", team_id)return None- return integration.mint_scoped_installation_token(READONLY_SANDBOX_GITHUB_PERMISSIONS)+ private_repositories = _private_repositories(repositories)+ names = _installation_repository_names(integration, private_repositories)+ if private_repositories and not names:+ return None+ return integration.mint_scoped_installation_token(+ READONLY_SANDBOX_GITHUB_PERMISSIONS, repositories=names or None+ )except Exception:logger.warning("Failed to mint read-only GitHub token for team %d", team_id, exc_info=True)return None-def get_user_github_token(github_user_integration_id: str) -> Optional[str]:+def get_user_github_token(github_user_integration_id: str, repositories: Sequence[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, source="tasks_sandbox", priority=Priority.CRITICAL)+ private_repositories = _private_repositories(repositories)+ if private_repositories:+ return _mint_repository_scoped_token(github_integration, private_repositories)if github_integration.access_token_expired():github_integration.refresh_access_token()return github_integration.integration.sensitive_config.get("access_token") or None@@ -1199,6 +1263,7 @@ def _resolve_sandbox_github_token(else:run_state = parse_run_state(state)pr_authorship_mode = run_state.pr_authorship_mode+ repositories = _sandbox_repositories(state, repository)# Loop runs mint credentials as the owner, so gate every GitHub token resolution (initial# provisioning, snapshot resume, and refresh all reach here) on current owner eligibility. A@@ -1245,7 +1310,7 @@ def _resolve_sandbox_github_token(raise ReauthorizationRequired(f"User-authored run {run_id} requires a linked GitHub account with repo access.")- return get_github_token(github_integration_id)+ return get_github_token(github_integration_id, repositories=repositories)# Serialize the rotating mint per integration so concurrent runs (provisioning# clones and refresh loops) don't revoke each other's in-flight user token.from products.tasks.backend.temporal.process_task.sandbox_credentials import ( # noqa: PLC0415@@ -1271,19 +1336,19 @@ def _resolve_sandbox_github_token(raise ReauthorizationRequired(f"User-authored run {run_id} requires a linked GitHub account with repo access.")- return get_github_token(github_integration_id)+ return get_github_token(github_integration_id, repositories=repositories)elif pr_authorship_mode == PrAuthorshipMode.BOT:if github_integration_id is not None:- return get_github_token(github_integration_id)+ return get_github_token(github_integration_id, repositories=repositories)# 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 get_user_github_token(github_user_integration_id, repositories=repositories)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)+ return get_github_token(github_integration_id, repositories=repositories)def format_allowed_domains_for_log(domains: list[str], limit: int = 5) -> str:diff --git a/products/tasks/backend/tests/test_sandbox_utils.py b/products/tasks/backend/tests/test_sandbox_utils.pyindex e88d5ebf7704..5f585cefc8a9 100644--- a/products/tasks/backend/tests/test_sandbox_utils.py+++ b/products/tasks/backend/tests/test_sandbox_utils.py@@ -3,15 +3,23 @@ from unittest.mock import MagicMock, patchfrom django.test import override_settings+import requestsfrom parameterized import parameterized+from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.github_integration_base import GitHubIntegrationErrorfrom posthog.models.integration import GitHubIntegrationfrom posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration-from products.tasks.backend.exceptions import CredentialUnavailableError+from products.tasks.backend.exceptions import (+ CredentialUnavailableError,+ GitHubAuthenticationError,+ GitHubRateLimitedError,+ ProcessTaskTransientError,+)from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContextfrom products.tasks.backend.temporal.process_task.utils import (+ READONLY_SANDBOX_GITHUB_PERMISSIONS,can_mint_readonly_github_token,get_readonly_github_token,get_sandbox_api_url,@@ -34,6 +42,8 @@ def test_get_sandbox_api_url(sandbox_api_url: str | None, expected: str) -> Nonedef _team_integration(*, unavailable: bool = False, mint_raises: bool = False) -> MagicMock:github = MagicMock(spec=GitHubIntegration)github.installation_unavailable.return_value = unavailable+ github.account_name_needs_heal.return_value = False+ github.organization.return_value = "Acme"if mint_raises:github.mint_scoped_installation_token.side_effect = GitHubIntegrationError("mint failed")return github@@ -168,6 +178,7 @@ def test_readonly_request_takes_priority_over_full_credential_path(ctx, task=MagicMock(), actor_user=None, repository=repository, has_repo=has_repo)+ mock_readonly.assert_called_once_with(ctx.team_id, repositories=ctx.repositories)assert token == "READONLY_TOKEN"mock_full.assert_not_called()@@ -210,10 +221,21 @@ def test_repo_less_report_run_follows_the_integration_the_create_path_attached(assert token == expected+ "error, expected_error",+ [+ (ReauthorizationRequired("relink GitHub"), CredentialUnavailableError),+ (GitHubRateLimitError("limited", retry_after=30), GitHubRateLimitedError),+ (requests.ConnectionError("reset"), ProcessTaskTransientError),+ (GitHubIntegrationError("bad gateway", status_code=502), ProcessTaskTransientError),+ (GitHubIntegrationError("not accessible", status_code=422), GitHubAuthenticationError),+ ],+ ids=["reauthorization", "rate_limited", "connection_error", "server_error", "rejected_mint"],+)@patch("products.tasks.backend.temporal.process_task.activities.provision_sandbox.emit_agent_log")@patch("products.tasks.backend.temporal.process_task.activities.provision_sandbox.get_sandbox_github_token")-def test_reauthorization_required_surfaces_as_credential_unavailable(- mock_full: MagicMock, _mock_log: MagicMock+def test_github_token_failure_maps_to_run_error(+ mock_full: MagicMock, _mock_log: MagicMock, error: Exception, expected_error: type[Exception]) -> None:# ReauthorizationRequired is a user-actionable "re-link your GitHub account" signal, not a# system fault. Provisioning must surface it as CredentialUnavailableError (fatal, non-retryable,@@ -223,7 +245,7 @@ def test_reauthorization_required_surfaces_as_credential_unavailable(_resolve_sandbox_github_token,)- mock_full.side_effect = ReauthorizationRequired("relink GitHub")+ mock_full.side_effect = errorctx = TaskProcessingContext(task_id="t",run_id="r",@@ -236,5 +258,33 @@ def test_reauthorization_required_surfaces_as_credential_unavailable(state={},)- with pytest.raises(CredentialUnavailableError):+ with pytest.raises(expected_error) as raised:_resolve_sandbox_github_token(ctx, task=MagicMock(), actor_user=None, repository="acme/repo", has_repo=True)+ assert type(raised.value) is expected_error+++ "repositories, mints, expected",+ [+ ([], True, None),+ (["Acme/API", "acme/api", "acme/web"], True, ["api", "web"]),+ (["PostHog/.github"], True, None),+ (["evilorg/api"], False, None),+ ],+ ids=["repo_less", "pinned_repositories", "public_bootstrap_only", "another_account_only"],+)+def test_readonly_token_scopes_repositories_without_widening_permissions(repositories, mints, expected):+ integration = _team_integration()+ with patch(+ "products.tasks.backend.temporal.process_task.utils.resolve_readonly_github_integration",+ return_value=integration,+ ):+ token = get_readonly_github_token(1, repositories=repositories)+ if mints:+ assert token == integration.mint_scoped_installation_token.return_value+ integration.mint_scoped_installation_token.assert_called_once_with(+ READONLY_SANDBOX_GITHUB_PERMISSIONS, repositories=expected+ )+ else:+ assert token is None+ integration.mint_scoped_installation_token.assert_not_called()