: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(review-hog): scope github tokens to read or push per step (#130633)
Charles Vien99878c1a84b8
diff --git a/products/review_hog/backend/reviewer/sandbox/executor.py b/products/review_hog/backend/reviewer/sandbox/executor.pyindex 1ef59cd40ec1..d2b4c04b6982 100644--- a/products/review_hog/backend/reviewer/sandbox/executor.py+++ b/products/review_hog/backend/reviewer/sandbox/executor.py@@ -145,6 +145,7 @@ async def run_sandbox_review(initial_permission_mode=initial_permission_mode,# Unset means "full" — never hand that to a session fed untrusted PR-comment text.posthog_mcp_scopes=REVIEW_MCP_SCOPES,+ github_token_scope="read",)return await _run_prompt(full_prompt,@@ -172,6 +173,7 @@ async def start_sandbox_session(model: str | None = None,reasoning_effort: str | None = None,initial_permission_mode: str | None = None,+ can_push: bool = False,) -> tuple[MultiTurnSession, _ModelT]:"""Open a multi-turn sandbox session and return it with its first validated turn.@@ -195,6 +197,7 @@ async def start_sandbox_session(initial_permission_mode=initial_permission_mode,# Unset means "full" — never hand that to a session fed untrusted PR-comment text.posthog_mcp_scopes=REVIEW_MCP_SCOPES,+ github_token_scope="push" if can_push else "read",)try:return await MultiTurnSession.start(diff --git a/products/review_hog/backend/reviewer/tests/test_executor.py b/products/review_hog/backend/reviewer/tests/test_executor.pyindex 2454beed4bbc..323467876e8f 100644--- a/products/review_hog/backend/reviewer/tests/test_executor.py+++ b/products/review_hog/backend/reviewer/tests/test_executor.py@@ -149,6 +149,33 @@ class TestRunSandboxReview:# The session path builds its own context, so the least-privilege pin must hold here too.assert call_kwargs["context"].posthog_mcp_scopes == ["llm_skill:read", "user:read"]+ @parameterized.expand(+ [+ ("single_turn", run_sandbox_review, {}, "read"),+ ("warm_session", start_sandbox_session, {}, "read"),+ ("warm_session_that_pushes", start_sandbox_session, {"can_push": True}, "push"),+ ]+ )+ @pytest.mark.asyncio+ async def test_github_access_is_read_only_unless_the_session_pushes(+ self, _name, entrypoint, extra_kwargs, expected_scope+ ) -> None:+ mock_start = AsyncMock(return_value=(AsyncMock(), DummyModel(result="ok")))++ with patch(f"{_EXECUTOR_PREFIX}.MultiTurnSession.start", mock_start):+ await entrypoint(+ team_id=1,+ user_id=2,+ repository="o/r",+ branch="b",+ prompt="p",+ system_prompt="s",+ model_to_validate=DummyModel,+ **extra_kwargs,+ )++ assert mock_start.call_args.kwargs["context"].github_token_scope == expected_scope+@parameterized.expand([("single_turn_with_prefix", run_sandbox_review, "review-pr:1:o/r:7:chunking", True),diff --git a/products/review_hog/backend/temporal/resolution.py b/products/review_hog/backend/temporal/resolution.pyindex 513b4f9628b7..20d8a9801a32 100644--- a/products/review_hog/backend/temporal/resolution.py+++ b/products/review_hog/backend/temporal/resolution.py@@ -830,6 +830,7 @@ async def resolve_threads_activity(input: ResolveThreadsInput) -> ResolutionRunRmodel=RESOLUTION_MODEL,reasoning_effort=RESOLUTION_REASONING_EFFORT,initial_permission_mode=RESOLUTION_INITIAL_PERMISSION_MODE,+ can_push=True,)await database_sync_to_async(_append_task_run, thread_sensitive=False)(input, prepared.report_id, sessiondiff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 9542b384bcb5..4af2e4ebedfc 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -3207,6 +3207,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(# runner); a PATCHable key would let any task controller mint a GitHub token onto a# queued repo-less run."github_read_access",+ "github_token_scope",# Historical loop runs use this server stamp to keep owner credential revocation fail-closed."loop_id",# Stamped at creation by workflow tasks: a PATCHable value would widen the run's connector allowlist.@@ -9688,6 +9689,7 @@ def warm_task_resume_sandbox("self_driving_head_branch","stack_base_branch","github_read_access",+ "github_token_scope","github_access_repositories",):if protected_key in (previous_run.state or {}):@@ -10125,6 +10127,8 @@ def run_task(# so this server-side copy is the only way it reaches a successor run.)if (previous_run.state or {}).get("github_read_access") is True:extra_state["github_read_access"] = True+ if github_token_scope := (previous_run.state or {}).get("github_token_scope"):+ extra_state["github_token_scope"] = github_token_scope# A resumed child run stays a child, so its sandbox still cannot start more runs. The keys# are PATCH-protected, so this server-side copy is the only way they reach a successor run.diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.pyindex 4aba043bd4a8..6bf5f4bff8a1 100644--- a/products/tasks/backend/logic/services/custom_prompt_internals.py+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py@@ -7,7 +7,7 @@ import asyncioimport loggingfrom collections.abc import Callable, Collection, Sequencefrom dataclasses import dataclass-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Literalfrom uuid import UUID, uuid4from django.conf import settings@@ -171,6 +171,7 @@ class CustomPromptSandboxContext:``contents: read``, so a run that pins repositories still clones them and just cannot push.Best-effort: if no team GitHub integration exists or the mint fails, the sandbox startswithout a token."""+ github_token_scope: Literal["read", "push"] | None = Noneinteraction_origin: str | None = None"""Surface the run is answering on (e.g. ``"slack"``). The agent server branches its systemprompt on this, so evals that grade surface-specific behavior must set it to exercise the@@ -424,6 +425,7 @@ async def _create_task_and_trigger(sandbox_timeout_seconds=context.sandbox_timeout_seconds,workflow_id_prefix=workflow_id_prefix,github_read_access=context.github_read_access,+ github_token_scope=context.github_token_scope,mcp_credential_owner_id=mcp_credential_owner_id,mcp_gateway_server_ids=mcp_gateway_server_ids,mcp_tool_allowlist=mcp_tool_allowlist,diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 154e6e7bee8f..7509f020df3c 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -1861,6 +1861,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):custom_image_builder_id: str | None = None,custom_image_id: str | None = None,github_read_access: bool = False,+ github_token_scope: Literal["read", "push"] | None = None,mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,mcp_credential_owner_id: int | None = None,mcp_gateway_server_ids: list[str] | None = None,@@ -1995,6 +1996,8 @@ class Task(Taggable, DeletedMetaFields, models.Model):# whether or not the run clones, so a repo-pinned caller that asks for read access# gets a checkout it can read and never write capability it did not ask for.run_extra_state["github_read_access"] = True+ if github_token_scope is not None:+ run_extra_state["github_token_scope"] = github_token_scope# Persist everything the dispatch needs alongside the row, in the same INSERT, so a# reconciler can re-dispatch faithfully if the workflow start is ever lost.run_extra_state["pending_dispatch"] = {diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex 011f6ce1e5f2..29d8496b97ab 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -240,6 +240,11 @@ class TaskProcessingContext:"""return (self.state or {}).get("github_read_access") is True+ @property+ def github_token_scope(self) -> Literal["read", "push"] | None:+ scope = (self.state or {}).get("github_token_scope")+ return scope if scope in ("read", "push") else None+@propertydef sandbox_environment_id(self) -> str | None:return (self.state or {}).get("sandbox_environment_id")diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 7cd605b490f3..126963e2bfe3 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -403,7 +403,7 @@ def _repository_snapshot_integration_id(ctx: TaskProcessingContext, *, has_repo:from whenever the snapshot was taken. A fresh clone with the read-only mint is the only treethat holds both guarantees."""- if not has_repo or ctx.custom_image_name or ctx.github_read_access:+ if not has_repo or ctx.custom_image_name or ctx.github_read_access or ctx.github_token_scope is not None:return Nonereturn ctx.github_integration_iddiff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.pyindex 60c1bf732bbf..ef0c1b39257e 100644--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py@@ -797,7 +797,7 @@ def _refresh_sandbox_github(# Read-only runs use a team installation grant, not the message actor's identity.# The periodic credential refresh rotates that grant without widening its permissions.- if (state or {}).get("github_read_access") is True:+ if (state or {}).get("github_read_access") is True or (state or {}).get("github_token_scope"):return Nonerun_id = str(task_run.id)diff --git a/products/tasks/backend/temporal/process_task/sandbox_credentials.py b/products/tasks/backend/temporal/process_task/sandbox_credentials.pyindex fecf9ba8bedd..11498be96884 100644--- a/products/tasks/backend/temporal/process_task/sandbox_credentials.py+++ b/products/tasks/backend/temporal/process_task/sandbox_credentials.py@@ -294,6 +294,8 @@ def _live_sandboxes_for_user_integration(user_integration_id: int) -> list[LiveScontinueif is_caller_token_run(str(run.id), run.state):continue+ if (run.state or {}).get("github_token_scope"):+ continueif _loop_owner_credentials_revoked(run.task, run.state):continue# This loop carries the owner's token; skip a sandbox a per-message transition rebound to@@ -441,8 +443,10 @@ class GitHubSandboxCredential:raise ReauthorizationRequired("Slack run requires an acting user before refreshing GitHub credentials.")integration = None- if get_pr_authorship_mode(task, ctx.state) == PrAuthorshipMode.USER and not is_caller_token_run(- ctx.run_id, ctx.state+ if (+ ctx.github_token_scope is None+ and get_pr_authorship_mode(task, ctx.state) == PrAuthorshipMode.USER+ and not is_caller_token_run(ctx.run_id, ctx.state)):integration = resolve_user_github_integration_for_task(task,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 466027952894..cc36841d298c 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@@ -391,25 +391,33 @@ class TestSharedUserIntegrationRefresh:with pytest.raises(CredentialUnavailableError):GitHubSandboxCredential().refresh(MagicMock(), _context(), task)- def test_caller_token_run_skips_coordinated_path(self):+ @pytest.mark.parametrize(+ "caller_token,state,token",+ [+ (True, {}, "ghu_caller"),+ (False, {"github_token_scope": "push"}, "ghs_scoped_push"),+ (False, {"github_token_scope": "read"}, "ghs_scoped_read"),+ ],+ )+ def test_pinned_credential_run_skips_coordinated_path(self, caller_token, state, token):import contextlibfrom products.tasks.backend.temporal.process_task.utils import PrAuthorshipModewith contextlib.ExitStack() as stack:stack.enter_context(patch(f"{MODULE}.get_pr_authorship_mode", return_value=PrAuthorshipMode.USER))- stack.enter_context(patch(f"{MODULE}.is_caller_token_run", return_value=True))+ stack.enter_context(patch(f"{MODULE}.is_caller_token_run", return_value=caller_token))resolve = stack.enter_context(patch(f"{MODULE}.resolve_user_github_integration_for_task"))- stack.enter_context(patch(f"{MODULE}.get_sandbox_github_token", return_value="ghu_caller"))+ stack.enter_context(patch(f"{MODULE}.get_sandbox_github_token", return_value=token))apply = stack.enter_context(patch(f"{MODULE}.apply_github_credentials_to_sandbox", return_value=True))sandbox = MagicMock()sandbox.id = "sb-own"- outcome = GitHubSandboxCredential().refresh(sandbox, _context(), MagicMock())+ outcome = GitHubSandboxCredential().refresh(sandbox, _context(state=state), MagicMock())assert outcome.refreshed is Trueresolve.assert_not_called()- apply.assert_called_once_with(sandbox, ["explore-science/paper-wizard-frontend"], "ghu_caller")+ apply.assert_called_once_with(sandbox, ["explore-science/paper-wizard-frontend"], token)class TestApplyTokenLocked:@@ -642,6 +650,13 @@ class TestLiveSandboxRegistry:status=TaskRun.Status.IN_PROGRESS,state={"sandbox_id": "sb-caller", "pr_authorship_mode": "user", "github_credential_source": "caller_token"},)+ scoped = _task("org/scoped")+ TaskRun.objects.create(+ task=scoped,+ team=team,+ status=TaskRun.Status.IN_PROGRESS,+ state={"sandbox_id": "sb-scoped", "pr_authorship_mode": "user", "github_token_scope": "push"},+ )result = _live_sandboxes_for_user_integration(integration.id)diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.pyindex dbbb4d2ae14d..0f57cf975b7b 100644--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py@@ -545,6 +545,7 @@ class TestSandboxGithubIdentityGate:(PrAuthorshipMode.BOT, None),(PrAuthorshipMode.USER, {"github_read_access": True}),(PrAuthorshipMode.BOT, {"github_read_access": True}),+ (PrAuthorshipMode.USER, {"github_token_scope": "push"}),],)def test_shared_installation_credentials_skip_actor_rebinding(diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex 6fbc7067aca8..e5832d1de305 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -24,6 +24,8 @@ from products.tasks.backend.models import Taskfrom products.tasks.backend.redis import get_tasks_cachefrom products.tasks.backend.temporal.process_task.utils import (POSTHOG_MCP_DESCRIPTION,+ PUSH_SANDBOX_GITHUB_PERMISSIONS,+ READONLY_SANDBOX_GITHUB_PERMISSIONS,GitHubCredentialSource,McpServerConfig,PrAuthorshipMode,@@ -1403,6 +1405,38 @@ class TestGetSandboxGitHubToken(SimpleTestCase):assert result == "ghs_bot"mock_get_github_token.assert_called_once_with(123, repositories=expected_repositories)+ @parameterized.expand(+ [+ ("bot_authored_push", "bot", "push", PUSH_SANDBOX_GITHUB_PERMISSIONS, 123),+ ("user_authored_push", "user", "push", PUSH_SANDBOX_GITHUB_PERMISSIONS, 123),+ ("bot_authored_read", "bot", "read", READONLY_SANDBOX_GITHUB_PERMISSIONS, 123),+ ("no_attached_installation", "bot", "push", PUSH_SANDBOX_GITHUB_PERMISSIONS, None),+ ]+ )+ @patch("products.tasks.backend.temporal.process_task.utils.get_user_github_token")+ @patch("products.tasks.backend.temporal.process_task.utils.get_github_token")+ @patch("products.tasks.backend.temporal.process_task.utils.get_scoped_github_token")+ def test_scoped_run_mints_only_from_the_attached_installation(+ self, _name, authorship, scope, permissions, integration_id, mock_scoped, mock_full, mock_user_install+ ) -> None:+ mock_scoped.return_value = "ghs_scoped"++ result = get_sandbox_github_token(+ integration_id,+ run_id="run-1",+ state={"pr_authorship_mode": authorship, "github_token_scope": scope, "repositories": ["acme/api"]},+ github_user_integration_id="user-install",+ )++ if integration_id is None:+ assert result is None+ mock_scoped.assert_not_called()+ else:+ assert result == "ghs_scoped"+ mock_scoped.assert_called_once_with(integration_id, ["acme/api"], permissions)+ mock_full.assert_not_called()+ mock_user_install.assert_not_called()+@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:mock_get_github_token.return_value = "ghs_default"diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex 90d5c89f5498..522245edea3f 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -1049,8 +1049,13 @@ def _resolve_installation_repository_names(return sorted(resolved)-def _scoped_token_cache_key(github_integration: GitHubIntegrationBase, names: Sequence[str]) -> str:- return f"task-sandbox-github-token:{github_integration.github_installation_id}:{','.join(names)}"+def _scoped_token_cache_key(+ github_integration: GitHubIntegrationBase, names: Sequence[str], permissions: dict[str, str] | None = None+) -> str:+ key = f"task-sandbox-github-token:{github_integration.github_installation_id}:{','.join(names)}"+ if permissions:+ key += ":" + ",".join(f"{name}={level}" for name, level in sorted(permissions.items()))+ return keydef _readonly_token_cache_key(github_integration: GitHubIntegrationBase, names: Sequence[str]) -> str:@@ -1075,8 +1080,16 @@ def _store_github_token(cache_key: str, token: str) -> None:def forget_cached_github_tokens(github_integration: GitHubIntegrationBase, repositories: Sequence[str]) -> None:names = _installation_repository_names(github_integration, _private_repositories(repositories))+ scoped_names = _installation_repository_names(github_integration, repositories)get_tasks_cache().delete_many(- [_scoped_token_cache_key(github_integration, names), _readonly_token_cache_key(github_integration, names)]+ [+ _scoped_token_cache_key(github_integration, names),+ _readonly_token_cache_key(github_integration, names),+ *(+ _scoped_token_cache_key(github_integration, scoped_names, permissions)+ for permissions in SCOPED_SANDBOX_GITHUB_PERMISSIONS.values()+ ),+ ])@@ -1096,17 +1109,21 @@ def resolve_installation_github_integration(team_id: int, github_integration_id:return GitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)-def _mint_repository_scoped_token(github_integration: GitHubIntegrationBase, repositories: Sequence[str]) -> str | None:+def _mint_repository_scoped_token(+ github_integration: GitHubIntegrationBase,+ repositories: Sequence[str],+ permissions: dict[str, str] | None = None,+) -> str | None:names = _installation_repository_names(github_integration, repositories)if not names:return None- cache_key = _scoped_token_cache_key(github_integration, names)+ cache_key = _scoped_token_cache_key(github_integration, names, permissions)cache = get_tasks_cache()cached = cache.get(cache_key)if isinstance(cached, str):return cached or Nonetry:- token = github_integration.mint_scoped_installation_token(None, repositories=names)+ token = github_integration.mint_scoped_installation_token(permissions, repositories=names)except GitHubIntegrationError as error:if error.status_code != 422:raise@@ -1114,20 +1131,24 @@ def _mint_repository_scoped_token(github_integration: GitHubIntegrationBase, repif not resolved_names:cache.set(cache_key, "", timeout=PUBLIC_GITHUB_REPOSITORY_CACHE_TTL_SECONDS)return None- token = github_integration.mint_scoped_installation_token(None, repositories=resolved_names)+ token = github_integration.mint_scoped_installation_token(permissions, repositories=resolved_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]:+def _available_github_integration(github_integration_id: int) -> GitHubIntegration:integration = Integration.objects.get(id=github_integration_id)github_integration = GitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)-if github_integration.installation_unavailable():raise CredentialUnavailableError("GitHub App installation for this integration is uninstalled or suspended",{"github_integration_id": github_integration_id},)+ return github_integration+++def get_github_token(github_integration_id: int, repositories: Sequence[str] = ()) -> Optional[str]:+ github_integration = _available_github_integration(github_integration_id)private_repositories = _private_repositories(repositories)if private_repositories:return _mint_repository_scoped_token(github_integration, private_repositories)@@ -1215,6 +1236,27 @@ def get_readonly_github_token(team_id: int, repositories: Sequence[str] = ()) ->return None+PUSH_SANDBOX_GITHUB_PERMISSIONS: dict[str, str] = {+ "contents": "write",+ "metadata": "read",+ "pull_requests": "read",+}+++SCOPED_SANDBOX_GITHUB_PERMISSIONS: dict[str, dict[str, str]] = {+ "read": READONLY_SANDBOX_GITHUB_PERMISSIONS,+ "push": PUSH_SANDBOX_GITHUB_PERMISSIONS,+}+++def get_scoped_github_token(+ github_integration_id: int, repositories: Sequence[str], permissions: dict[str, str]+) -> Optional[str]:+ return _mint_repository_scoped_token(+ _available_github_integration(github_integration_id), repositories, permissions+ )++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)@@ -1479,6 +1521,12 @@ def _resolve_sandbox_github_token(logger.warning("loop_github_token_owner_ineligible", extra={"run_id": run_id, "task_id": str(task.id)})return None+ scoped_permissions = SCOPED_SANDBOX_GITHUB_PERMISSIONS.get((state or {}).get("github_token_scope", ""))+ if scoped_permissions is not None:+ if github_integration_id is None:+ return None+ return get_scoped_github_token(github_integration_id, repositories, scoped_permissions)+if pr_authorship_mode == PrAuthorshipMode.USER:if task is not None and slack_interaction and created_by is None:raise ReauthorizationRequired(f"Slack run {run_id} requires an acting user with GitHub repo access.")diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 54a583f4dadb..b6a5f2f4a724 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -1726,9 +1726,11 @@ class TestFacadeReadsAndMappers(TestCase):("self_driving_head_branch", "posthog-self-driving/fix-abc123"),("stack_base_branch", "posthog-self-driving/schema-abc123"),("github_access_repositories", ["acme/api", "acme/assets"]),+ ("github_read_access", True),+ ("github_token_scope", "push"),])- def test_run_task_resume_carries_self_driving_branch_stamp(self, state_key: str, branch: str | list[str]):+ def test_run_task_resume_carries_self_driving_branch_stamp(self, state_key: str, branch: str | list[str] | bool):# The signals review carve-out binds a PR to its run by matching the PR head ref against the# PATCH-protected state.self_driving_head_branch stamp. A resume mints a new run, so the# stamp must be copied forward or the carve-out stops matching the successor — the receiverdiff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex c9ead6d11be6..f7681740ca2b 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -667,8 +667,15 @@ class TestTask(TestCase):self.assertEqual(state["repositories"], ["posthog/posthog"])self.assertEqual(state.get("github_access_repositories"), expected_access)+ @parameterized.expand(+ [+ ("read_access", "github_read_access", True),+ ("read_scope", "github_token_scope", "read"),+ ("push_scope", "github_token_scope", "push"),+ ]+ )@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")- def test_create_and_run_threads_github_read_access_into_state(self, mock_execute_workflow):+ def test_create_and_run_threads_scoped_github_grant_into_state(self, _name, grant, value, mock_execute_workflow):from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import ( # noqa: PLC0415 — activities import the workflow stack; keep it off this module's import pathTaskProcessingContext,)@@ -682,7 +689,7 @@ class TestTask(TestCase):description="repo-less run wanting gh evidence access",origin_product=Task.OriginProduct.SIGNAL_REPORT,user_id=user.id,- github_read_access=True,+ **{grant: value},)state = TaskRun.objects.get(id=mock_execute_workflow.call_args.kwargs["run_id"]).state@@ -699,7 +706,7 @@ class TestTask(TestCase):distinct_id="d",state=state,)- self.assertTrue(ctx.github_read_access)+ self.assertEqual(getattr(ctx, grant), value)with self.captureOnCommitCallbacks(execute=True):Task.create_and_run(@@ -710,7 +717,7 @@ class TestTask(TestCase):user_id=user.id,)state = TaskRun.objects.get(id=mock_execute_workflow.call_args.kwargs["run_id"]).state- self.assertNotIn("github_read_access", state)+ self.assertNotIn(grant, state)@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_create_and_run_threads_initial_permission_mode_into_state(self, mock_execute_workflow):diff --git a/products/tasks/backend/tests/test_sandbox_utils.py b/products/tasks/backend/tests/test_sandbox_utils.pyindex 940966f49920..17ac91435979 100644--- a/products/tasks/backend/tests/test_sandbox_utils.py+++ b/products/tasks/backend/tests/test_sandbox_utils.py@@ -23,11 +23,13 @@ from products.tasks.backend.exceptions import (from products.tasks.backend.redis import get_tasks_cachefrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContextfrom products.tasks.backend.temporal.process_task.utils import (+ PUSH_SANDBOX_GITHUB_PERMISSIONS,READONLY_SANDBOX_GITHUB_PERMISSIONS,can_mint_readonly_github_token,forget_cached_github_tokens,get_readonly_github_token,get_sandbox_api_url,+ get_scoped_github_token,)@@ -117,12 +119,13 @@ def test_can_mint_readonly_github_token_matches_mint_eligibility(resolved, expec@parameterized.expand([- ("full_credential_run_reuses", False, 5),- ("read_only_run_clones_fresh", True, None),+ ("full_credential_run_reuses", {}, 5),+ ("read_only_run_clones_fresh", {"github_read_access": True}, None),+ ("scoped_token_run_clones_fresh", {"github_token_scope": "push"}, None),])def test_repository_snapshot_reuse_is_refused_for_read_only_runs(- _name: str, read_access: bool, expected: int | None+ _name: str, state: dict[str, bool], expected: int | None) -> None:# A repository snapshot keeps its creator's write-capable token in every `.git/config` and is# never fetched again, so restoring one for a read-only run hands the agent a write token and@@ -140,7 +143,7 @@ def test_repository_snapshot_reuse_is_refused_for_read_only_runs(github_integration_id=5,repository="acme/app",distinct_id="d",- state={"github_read_access": read_access},+ state=state,)assert _repository_snapshot_integration_id(ctx, has_repo=True) == expected@@ -396,3 +399,40 @@ def test_readonly_token_scopes_repositories_without_widening_permissions(repositelse:assert token is Noneintegration.mint_scoped_installation_token.assert_not_called()+++ "repositories, expected",+ [+ ([], None),+ (["Acme/API", "acme/web"], ["api", "web"]),+ (["PostHog/.github"], None),+ ],+ ids=["repo_less", "pinned_repositories", "public_bootstrap_only"],+)+def test_scoped_token_is_always_pinned_to_run_repositories(repositories, expected):+ integration = _team_integration()+ with (+ patch("products.tasks.backend.temporal.process_task.utils.Integration.objects.get"),+ patch("products.tasks.backend.temporal.process_task.utils.GitHubIntegration", return_value=integration),+ ):+ token = get_scoped_github_token(5, repositories, PUSH_SANDBOX_GITHUB_PERMISSIONS)+ if expected:+ assert token == integration.mint_scoped_installation_token.return_value+ integration.mint_scoped_installation_token.assert_called_once_with(+ PUSH_SANDBOX_GITHUB_PERMISSIONS, repositories=expected+ )+ else:+ assert token is None+ integration.mint_scoped_installation_token.assert_not_called()+++def test_scoped_token_mint_failure_reaches_the_caller():+ integration = _team_integration()+ integration.mint_scoped_installation_token.side_effect = GitHubRateLimitError("rate limited", retry_after=30)+ with (+ patch("products.tasks.backend.temporal.process_task.utils.Integration.objects.get"),+ patch("products.tasks.backend.temporal.process_task.utils.GitHubIntegration", return_value=integration),+ pytest.raises(GitHubRateLimitError),+ ):+ get_scoped_github_token(5, ["acme/api"], READONLY_SANDBOX_GITHUB_PERMISSIONS)