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(tasks): isolate github user-token refresh across concurrent sandboxes (#62390)

Alessandro Pogliaghia045d512b192
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.py
index 75c4210c072f..72ac7528e525 100644
--- a/products/tasks/backend/api.py
+++ b/products/tasks/backend/api.py
@@ -153,6 +153,7 @@ from .temporal.client import (
signal_task_followup_message,
)
from .temporal.process_task.utils import (
+ GitHubCredentialSource,
PrAuthorshipMode,
RunSource,
cache_github_user_token,
@@ -226,6 +227,31 @@ def _resolve_cloud_pr_authorship_mode(
)
+def _github_credential_source_extra_state(
+ pr_authorship_mode: PrAuthorshipMode | str | None, github_user_token: str | None
+) -> dict[str, str]:
+ """Durable marker of which GitHub identity a run is pinned to, decided once at creation.
+
+ A caller-supplied token is owned by the caller and un-refreshable by us, so the refresh
+ loop must never swap it for the task creator's server integration. Persisting the source
+ in run state keeps that decision durable (the per-run token cache only lives ~6h).
+ """
+ if pr_authorship_mode != PrAuthorshipMode.USER:
+ return {}
+ source = GitHubCredentialSource.CALLER_TOKEN if github_user_token else GitHubCredentialSource.SERVER_INTEGRATION
+ return {"github_credential_source": source.value}
+
+
+# Run-state keys that are server-owned and must never be mutable through the PATCH endpoint:
+# - github_credential_source / pr_authorship_mode fix the run's GitHub identity at creation;
+# a caller could otherwise flip a caller-token run to ``server_integration`` and have the
+# task creator's server-side token injected into their sandbox.
+# - sandbox_id is the credential-propagation target; a caller could otherwise repoint a visible
+# run at a sandbox they control and capture the run owner's token on the next rotation.
+# All three are written only server-side (run creation + the temporal workflow), never via PATCH.
+_PROTECTED_RUN_STATE_KEYS = frozenset({"github_credential_source", "pr_authorship_mode", "sandbox_id"})
+
+
TASK_RUN_ARTIFACT_UPLOAD_FORM_OVERHEAD_BYTES = 64 * 1024
@@ -1102,6 +1128,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
pr_authorship_mode.value if hasattr(pr_authorship_mode, "value") else pr_authorship_mode
)
+ if credential_source := _github_credential_source_extra_state(pr_authorship_mode, github_user_token):
+ extra_state = extra_state or {}
+ extra_state.update(credential_source)
+
if sandbox_environment_id is not None:
sandbox_environment = SandboxEnvironment.get_accessible_for_task(
environment_id=sandbox_environment_id,
@@ -1392,6 +1422,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
pr_authorship_mode.value if hasattr(pr_authorship_mode, "value") else pr_authorship_mode
)
+ if credential_source := _github_credential_source_extra_state(pr_authorship_mode, github_user_token):
+ extra_state = extra_state or {}
+ extra_state.update(credential_source)
+
if sandbox_environment_id is not None:
sandbox_environment = SandboxEnvironment.get_accessible_for_task(
environment_id=sandbox_environment_id,
@@ -1543,7 +1577,14 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
task_run = cast(TaskRun, self.get_object())
has_output_merge = "output" in request.validated_data and isinstance(request.validated_data["output"], dict)
has_state_merge = "state" in request.validated_data and isinstance(request.validated_data["state"], dict)
- state_remove_keys = request.validated_data.get("state_remove_keys") or []
+ # Protected keys fix the run's GitHub identity at creation — callers cannot change or remove them.
+ if has_state_merge:
+ request.validated_data["state"] = {
+ k: v for k, v in request.validated_data["state"].items() if k not in _PROTECTED_RUN_STATE_KEYS
+ }
+ state_remove_keys = [
+ k for k in (request.validated_data.get("state_remove_keys") or []) if k not in _PROTECTED_RUN_STATE_KEYS
+ ]
has_state_mutation = has_state_merge or bool(state_remove_keys)
update_fields: set[str] = set()
diff --git a/products/tasks/backend/temporal/process_task/sandbox_credentials.py b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
index e6ae7047af38..cd189b07af91 100644
--- a/products/tasks/backend/temporal/process_task/sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
@@ -1,7 +1,4 @@
-"""
-Refresh long-lived credentials inside a running task sandbox.
-This module re-resolves a fresh token and re-applies it in place.
-"""
+"""Refresh long-lived credentials inside a running task sandbox by re-resolving and re-applying tokens in place."""
import shlex
import base64
@@ -9,9 +6,20 @@ import logging
from dataclasses import dataclass
from typing import TYPE_CHECKING, Protocol
-from products.tasks.backend.models import Task
+import redis
+
+from posthog.models.user_integration import UserGitHubIntegration
+from posthog.redis import get_client
+
+from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.services.agentsh import ENV_FILE
-from products.tasks.backend.temporal.process_task.utils import get_sandbox_github_token
+from products.tasks.backend.temporal.process_task.utils import (
+ PrAuthorshipMode,
+ get_pr_authorship_mode,
+ get_sandbox_github_token,
+ is_caller_token_run,
+ resolve_user_github_integration_for_task,
+)
if TYPE_CHECKING:
from products.tasks.backend.services.sandbox import SandboxBase
@@ -22,17 +30,12 @@ logger = logging.getLogger(__name__)
GITHUB_ENV_KEYS = ("GITHUB_TOKEN", "GH_TOKEN")
-# GitHub App tokens are refreshed server-side at their half-life, so a freshly
-# resolved token has at least ~half its TTL remaining. Refresh at half of that
-# floor again to guarantee the in-sandbox copy never lapses during an active run.
-# ghs_ = installation access token, ~1h TTL → refresh every 20 min
-# ghu_ = user-to-server token, ~8h TTL → refresh every 2 h
+# Refresh at half the token's server-side half-life so the in-sandbox copy never lapses mid-run.
+# ghs_ = installation token (~1h) → 20 min; ghu_ = user-to-server token (~8h) → 2 h
_GITHUB_REFRESH_INTERVAL_BY_PREFIX: dict[str, float] = {
"ghs_": 20 * 60,
"ghu_": 2 * 60 * 60,
}
-# Used before the first token is resolved, and for any unrecognized prefix —
-# short enough to stay under the 1h installation-token floor.
DEFAULT_REFRESH_INTERVAL_SECONDS: float = 20 * 60
@@ -44,12 +47,7 @@ def github_refresh_interval_seconds(token: str) -> float:
def set_git_remote_token(sandbox: "SandboxBase", repository: str, github_token: str) -> bool:
- """Rewrite ``origin``'s remote URL with a fresh ``x-access-token``.
-
- Takes effect immediately — git re-reads ``.git/config`` on every operation,
- so this fixes ``git fetch``/``push`` even mid-turn. Guards on ``.git`` so it
- no-ops when the snapshot predates the clone.
- """
+ """Rewrite ``origin``'s remote URL with a fresh ``x-access-token``; git re-reads it on every op. No-ops pre-clone."""
org, repo = repository.lower().split("/")
repo_path = f"/tmp/workspace/repos/{org}/{repo}"
update_remote = (
@@ -70,13 +68,10 @@ def set_git_remote_token(sandbox: "SandboxBase", repository: str, github_token:
def update_sandbox_env_file(sandbox: "SandboxBase", updates: dict[str, str]) -> bool:
- """Replace specific keys in the agentsh env file, preserving all other entries.
+ """Replace specific keys in the NUL-delimited agentsh env file, preserving all other entries.
- The env file is a NUL-delimited ``key=value`` list that the agentsh exec
- wrapper re-sources on every command, so updating it here propagates fresh
- tokens to the agent's subsequent ``gh``/``git`` invocations without a reboot.
- Read-modify-write (via base64 to survive NUL bytes) so we never clobber the
- rest of the captured environment.
+ Read-modify-write via base64 to survive NUL bytes. The exec wrapper re-sources the
+ file per command, so updates reach the agent's later ``gh``/``git`` calls without a reboot.
"""
if not updates:
return True
@@ -124,6 +119,104 @@ def apply_github_credentials_to_sandbox(sandbox: "SandboxBase", repository: str
update_sandbox_env_file(sandbox, dict.fromkeys(GITHUB_ENV_KEYS, github_token))
+USER_TOKEN_REFRESH_INTERVAL_SECONDS: float = _GITHUB_REFRESH_INTERVAL_BY_PREFIX["ghu_"]
+# TTL covers a slow mint + propagation; wait stays under the refresh activity's 2 min timeout.
+_ROTATION_LOCK_TTL_SECONDS = 120
+_ROTATION_LOCK_WAIT_SECONDS = 90
+
+
+def _rotation_lock_key(user_integration_id: int) -> str:
+ return f"tasks:gh_user_token_rotate:{user_integration_id}"
+
+
+def _live_sandboxes_for_user_integration(user_integration_id: int) -> list[tuple[str, str, str | None]]:
+ rows: list[tuple[str, str, str | None]] = []
+ runs = (
+ TaskRun.objects.filter(
+ status=TaskRun.Status.IN_PROGRESS,
+ task__github_user_integration_id=user_integration_id,
+ )
+ .select_related("task")
+ .only("id", "state", "task__repository", "task__github_user_integration_id", "task__origin_product")
+ )
+ for run in runs:
+ sandbox_id = (run.state or {}).get("sandbox_id")
+ if not sandbox_id:
+ continue
+ # Only user-authored runs use this integration's rotating token. Bot-authored runs use an
+ # installation token, and caller-supplied-token runs are pinned to their own credential —
+ # propagating over either would swap its identity.
+ if get_pr_authorship_mode(run.task, run.state) != PrAuthorshipMode.USER:
+ continue
+ if is_caller_token_run(str(run.id), run.state):
+ continue
+ rows.append((str(run.id), sandbox_id, run.task.repository))
+ return rows
+
+
+def _propagate_user_token(user_integration_id: int, token: str) -> int:
+ from products.tasks.backend.services.sandbox import Sandbox # noqa: PLC0415
+
+ applied = 0
+ for run_id, sandbox_id, repository in _live_sandboxes_for_user_integration(user_integration_id):
+ try:
+ sandbox = Sandbox.get_by_id(sandbox_id)
+ if sandbox.is_running():
+ apply_github_credentials_to_sandbox(sandbox, repository, token)
+ applied += 1
+ except Exception:
+ logger.warning(
+ "Failed to propagate refreshed GitHub user token to sibling sandbox",
+ extra={"integration_id": user_integration_id, "run_id": run_id, "sandbox_id": sandbox_id},
+ exc_info=True,
+ )
+ return applied
+
+
+def resolve_coordinated_user_token(integration: UserGitHubIntegration) -> str | None:
+ """Usable user-to-server token, with the rotating mint serialized per integration.
+
+ Refreshing a user token revokes the previous one, so concurrent callers sharing an
+ integration would revoke each other's in-flight token. Serialize the mint under a
+ per-integration lock and propagate the fresh token to live sandboxes.
+ """
+ if not integration.user_access_token_expired():
+ return integration.get_usable_user_access_token()
+
+ integration_id = integration.integration.id
+ lock = get_client().lock(
+ _rotation_lock_key(integration_id),
+ timeout=_ROTATION_LOCK_TTL_SECONDS,
+ blocking_timeout=_ROTATION_LOCK_WAIT_SECONDS,
+ )
+ if not lock.acquire():
+ # Waited out the budget — read the current token without minting; the holder's propagation self-heals.
+ integration.integration.refresh_from_db()
+ return UserGitHubIntegration(integration.integration).user_access_token
+
+ try:
+ integration.integration.refresh_from_db()
+ current = UserGitHubIntegration(integration.integration)
+ was_expired = current.user_access_token_expired()
+ # Mints only if still expired; a prior holder's fresh token is returned without rotating.
+ token = current.get_usable_user_access_token()
+ if was_expired and token:
+ propagated = _propagate_user_token(integration_id, token)
+ logger.info(
+ "Rotated and propagated GitHub user token",
+ extra={"integration_id": integration_id, "sibling_sandboxes_updated": propagated},
+ )
+ return token
+ finally:
+ try:
+ lock.release()
+ except redis.exceptions.LockError:
+ logger.warning(
+ "GitHub user-token rotation lock already expired/released",
+ extra={"integration_id": integration_id},
+ )
+
+
@dataclass
class CredentialRefreshOutcome:
kind: str
@@ -155,6 +248,15 @@ class GitHubSandboxCredential:
self.kind, refreshed=False, next_refresh_seconds=DEFAULT_REFRESH_INTERVAL_SECONDS
)
+ integration = None
+ if 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, repository=ctx.repository, allow_refresh=True)
+
+ if integration is not None:
+ return self._refresh_shared_user_integration(sandbox, ctx, integration)
+
token = get_sandbox_github_token(
ctx.github_integration_id,
run_id=ctx.run_id,
@@ -173,6 +275,16 @@ class GitHubSandboxCredential:
self.kind, refreshed=True, next_refresh_seconds=github_refresh_interval_seconds(token)
)
+ def _refresh_shared_user_integration(
+ self, sandbox: "SandboxBase", ctx: "TaskProcessingContext", integration: UserGitHubIntegration
+ ) -> CredentialRefreshOutcome:
+ token = resolve_coordinated_user_token(integration)
+ if token:
+ apply_github_credentials_to_sandbox(sandbox, ctx.repository, token)
+ return CredentialRefreshOutcome(
+ self.kind, refreshed=bool(token), next_refresh_seconds=USER_TOKEN_REFRESH_INTERVAL_SECONDS
+ )
+
def build_sandbox_credentials(ctx: "TaskProcessingContext") -> list[SandboxCredential]:
credentials: list[SandboxCredential] = []
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.py
index 3981ddd5ab2e..efa1899bf2b8 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
@@ -155,3 +155,217 @@ class TestBuildSandboxCredentials:
def test_empty_without_github_credentials(self):
ctx = _context(github_integration_id=None, github_user_integration_id=None)
assert build_sandbox_credentials(ctx) == []
+
+
+MODULE = "products.tasks.backend.temporal.process_task.sandbox_credentials"
+
+
+class TestSharedUserIntegrationRefresh:
+ def _as_user_integration_run(self, stack):
+ from products.tasks.backend.temporal.process_task.utils import PrAuthorshipMode
+
+ 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=False))
+
+ def test_refresh_applies_coordinated_token(self):
+ import contextlib
+
+ from products.tasks.backend.temporal.process_task.sandbox_credentials import USER_TOKEN_REFRESH_INTERVAL_SECONDS
+
+ with contextlib.ExitStack() as stack:
+ self._as_user_integration_run(stack)
+ stack.enter_context(patch(f"{MODULE}.resolve_user_github_integration_for_task", return_value=MagicMock()))
+ resolve = stack.enter_context(patch(f"{MODULE}.resolve_coordinated_user_token", return_value="ghu_fresh"))
+ apply = stack.enter_context(patch(f"{MODULE}.apply_github_credentials_to_sandbox"))
+
+ sandbox = MagicMock()
+ outcome = GitHubSandboxCredential().refresh(sandbox, _context(), MagicMock())
+
+ assert outcome.refreshed is True
+ assert outcome.next_refresh_seconds == USER_TOKEN_REFRESH_INTERVAL_SECONDS
+ resolve.assert_called_once()
+ apply.assert_called_once_with(sandbox, "explore-science/paper-wizard-frontend", "ghu_fresh")
+
+ def test_refresh_reports_not_refreshed_when_no_token(self):
+ import contextlib
+
+ with contextlib.ExitStack() as stack:
+ self._as_user_integration_run(stack)
+ stack.enter_context(patch(f"{MODULE}.resolve_user_github_integration_for_task", return_value=MagicMock()))
+ stack.enter_context(patch(f"{MODULE}.resolve_coordinated_user_token", return_value=None))
+ apply = stack.enter_context(patch(f"{MODULE}.apply_github_credentials_to_sandbox"))
+
+ outcome = GitHubSandboxCredential().refresh(MagicMock(), _context(), MagicMock())
+
+ assert outcome.refreshed is False
+ apply.assert_not_called()
+
+ def test_caller_token_run_skips_coordinated_path(self):
+ import contextlib
+
+ from products.tasks.backend.temporal.process_task.utils import PrAuthorshipMode
+
+ with 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))
+ 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"))
+ apply = stack.enter_context(patch(f"{MODULE}.apply_github_credentials_to_sandbox"))
+
+ sandbox = MagicMock()
+ sandbox.id = "sb-own"
+ outcome = GitHubSandboxCredential().refresh(sandbox, _context(), MagicMock())
+
+ assert outcome.refreshed is True
+ resolve.assert_not_called()
+ apply.assert_called_once_with(sandbox, "explore-science/paper-wizard-frontend", "ghu_caller")
+
+
+class TestResolveCoordinatedUserToken:
+ def _patch_lock(self, stack, *, acquired: bool):
+ lock = MagicMock()
+ lock.acquire.return_value = acquired
+ get_client = stack.enter_context(patch(f"{MODULE}.get_client"))
+ get_client.return_value.lock.return_value = lock
+ return lock
+
+ def test_valid_token_returned_without_locking(self):
+ import contextlib
+
+ from products.tasks.backend.temporal.process_task.sandbox_credentials import resolve_coordinated_user_token
+
+ with contextlib.ExitStack() as stack:
+ get_client = stack.enter_context(patch(f"{MODULE}.get_client"))
+ propagate = stack.enter_context(patch(f"{MODULE}._propagate_user_token"))
+ integration = MagicMock()
+ integration.user_access_token_expired.return_value = False
+ integration.get_usable_user_access_token.return_value = "ghu_current"
+
+ assert resolve_coordinated_user_token(integration) == "ghu_current"
+ get_client.return_value.lock.assert_not_called()
+ propagate.assert_not_called()
+
+ def test_expired_token_minted_and_propagated_under_lock(self):
+ import contextlib
+
+ from products.tasks.backend.temporal.process_task.sandbox_credentials import resolve_coordinated_user_token
+
+ with contextlib.ExitStack() as stack:
+ lock = self._patch_lock(stack, acquired=True)
+ integration = MagicMock()
+ integration.integration.id = 7
+ integration.user_access_token_expired.return_value = True
+ current = MagicMock()
+ current.user_access_token_expired.return_value = True
+ current.get_usable_user_access_token.return_value = "ghu_fresh"
+ stack.enter_context(patch(f"{MODULE}.UserGitHubIntegration", return_value=current))
+ propagate = stack.enter_context(patch(f"{MODULE}._propagate_user_token", return_value=2))
+
+ assert resolve_coordinated_user_token(integration) == "ghu_fresh"
+ current.get_usable_user_access_token.assert_called_once()
+ propagate.assert_called_once_with(7, "ghu_fresh")
+ lock.release.assert_called_once()
+
+ def test_acquired_but_already_fresh_does_not_propagate(self):
+ import contextlib
+
+ from products.tasks.backend.temporal.process_task.sandbox_credentials import resolve_coordinated_user_token
+
+ with contextlib.ExitStack() as stack:
+ lock = self._patch_lock(stack, acquired=True)
+ integration = MagicMock()
+ integration.integration.id = 7
+ integration.user_access_token_expired.return_value = True
+ current = MagicMock()
+ current.user_access_token_expired.return_value = False # a prior holder already minted
+ current.get_usable_user_access_token.return_value = "ghu_already_fresh"
+ stack.enter_context(patch(f"{MODULE}.UserGitHubIntegration", return_value=current))
+ propagate = stack.enter_context(patch(f"{MODULE}._propagate_user_token"))
+
+ assert resolve_coordinated_user_token(integration) == "ghu_already_fresh"
+ propagate.assert_not_called()
+ lock.release.assert_called_once()
+
+ def test_contended_lock_returns_current_without_minting(self):
+ import contextlib
+
+ from products.tasks.backend.temporal.process_task.sandbox_credentials import resolve_coordinated_user_token
+
+ with contextlib.ExitStack() as stack:
+ lock = self._patch_lock(stack, acquired=False)
+ integration = MagicMock()
+ integration.integration.id = 7
+ integration.user_access_token_expired.return_value = True
+ sibling = MagicMock()
+ sibling.user_access_token = "ghu_sibling_fresh"
+ stack.enter_context(patch(f"{MODULE}.UserGitHubIntegration", return_value=sibling))
+ propagate = stack.enter_context(patch(f"{MODULE}._propagate_user_token"))
+
+ assert resolve_coordinated_user_token(integration) == "ghu_sibling_fresh"
+ sibling.get_usable_user_access_token.assert_not_called()
+ propagate.assert_not_called()
+ lock.release.assert_not_called()
+
+
+class TestLiveSandboxRegistry:
+ def test_scopes_to_in_progress_runs_with_a_sandbox_for_the_integration(self):
+ from posthog.models import Organization, Team
+ from posthog.models.user import User
+ from posthog.models.user_integration import UserIntegration
+
+ from products.tasks.backend.models import Task, TaskRun
+ from products.tasks.backend.temporal.process_task.sandbox_credentials import (
+ _live_sandboxes_for_user_integration,
+ )
+
+ org = Organization.objects.create(name="o")
+ team = Team.objects.create(organization=org, name="t")
+ user = User.objects.create(email="[email protected]")
+ integration = UserIntegration.objects.create(
+ user=user, kind=UserIntegration.IntegrationKind.GITHUB, integration_id="i1", config={}, sensitive_config={}
+ )
+ other = UserIntegration.objects.create(
+ user=user, kind=UserIntegration.IntegrationKind.GITHUB, integration_id="i2", config={}, sensitive_config={}
+ )
+
+ def _task(repo):
+ return Task.objects.create(team=team, created_by=user, repository=repo, github_user_integration=integration)
+
+ live = _task("org/live")
+ live_run = TaskRun.objects.create(
+ task=live,
+ team=team,
+ status=TaskRun.Status.IN_PROGRESS,
+ state={"sandbox_id": "sb-live", "pr_authorship_mode": "user"},
+ )
+ no_sandbox = _task("org/nosandbox")
+ TaskRun.objects.create(task=no_sandbox, team=team, status=TaskRun.Status.IN_PROGRESS, state={})
+ done = _task("org/done")
+ TaskRun.objects.create(task=done, team=team, status=TaskRun.Status.COMPLETED, state={"sandbox_id": "sb-done"})
+ other_task = Task.objects.create(
+ team=team, created_by=user, repository="org/other", github_user_integration=other
+ )
+ TaskRun.objects.create(
+ task=other_task, team=team, status=TaskRun.Status.IN_PROGRESS, state={"sandbox_id": "sb-other"}
+ )
+ # Bot-authored — uses an installation token, never the user integration's rotating token.
+ bot = _task("org/bot")
+ TaskRun.objects.create(
+ task=bot,
+ team=team,
+ status=TaskRun.Status.IN_PROGRESS,
+ state={"sandbox_id": "sb-bot", "pr_authorship_mode": "bot"},
+ )
+ # Authorized by a caller-supplied token — excluded so we never overwrite its credential.
+ caller = _task("org/caller")
+ TaskRun.objects.create(
+ task=caller,
+ team=team,
+ status=TaskRun.Status.IN_PROGRESS,
+ state={"sandbox_id": "sb-caller", "pr_authorship_mode": "user", "github_credential_source": "caller_token"},
+ )
+
+ result = _live_sandboxes_for_user_integration(integration.id)
+
+ assert result == [(str(live_run.id), "sb-live", "org/live")]
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 46002dff4fe5..202d1653db96 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -7,11 +7,14 @@ from parameterized import parameterized
from products.mcp_store.backend.facade.contracts import ActiveInstallationInfo
from products.tasks.backend.models import Task
from products.tasks.backend.temporal.process_task.utils import (
+ GitHubCredentialSource,
McpServerConfig,
get_git_identity_env_vars,
+ get_github_credential_source,
get_sandbox_github_token,
get_sandbox_ph_mcp_configs,
get_user_mcp_server_configs,
+ is_caller_token_run,
)
@@ -394,6 +397,7 @@ class TestGetSandboxGitHubToken(TestCase):
("identity_without_token_falls_back_to_team_token", None, True, None, "empty_token", "ghs_team"),
]
)
+ @patch("products.tasks.backend.temporal.process_task.sandbox_credentials.resolve_coordinated_user_token")
@patch("products.tasks.backend.temporal.process_task.utils.get_cached_github_user_token")
@patch("products.tasks.backend.temporal.process_task.utils.get_user_github_integration")
@patch("products.tasks.backend.temporal.process_task.utils.get_github_token")
@@ -408,6 +412,7 @@ class TestGetSandboxGitHubToken(TestCase):
mock_get_github_token: MagicMock,
mock_get_identity: MagicMock,
mock_cached: MagicMock,
+ mock_resolve: MagicMock,
) -> None:
from posthog.models.user_integration import ReauthorizationRequired
@@ -415,9 +420,9 @@ class TestGetSandboxGitHubToken(TestCase):
creator = MagicMock(name="creator")
identity = MagicMock()
if error_case == "reauthorization":
- identity.get_usable_user_access_token.side_effect = ReauthorizationRequired("reauthorize GitHub")
+ mock_resolve.side_effect = ReauthorizationRequired("reauthorize GitHub")
else:
- identity.get_usable_user_access_token.return_value = identity_token
+ mock_resolve.return_value = identity_token
mock_get_identity.return_value = identity if has_identity else None
mock_get_github_token.return_value = expected_token
@@ -432,7 +437,7 @@ class TestGetSandboxGitHubToken(TestCase):
mock_cached.assert_called_once_with("run-1")
if cached_token:
mock_get_identity.assert_not_called()
- identity.get_usable_user_access_token.assert_not_called()
+ mock_resolve.assert_not_called()
else:
mock_get_identity.assert_called_once_with(
creator,
@@ -441,7 +446,7 @@ class TestGetSandboxGitHubToken(TestCase):
allow_refresh=True,
)
if has_identity:
- identity.get_usable_user_access_token.assert_called_once()
+ mock_resolve.assert_called_once_with(identity)
if error_case in ("missing", "reauthorization", "empty_token"):
mock_get_github_token.assert_called_once_with(123)
else:
@@ -453,6 +458,7 @@ class TestGetSandboxGitHubToken(TestCase):
("empty_token",),
]
)
+ @patch("products.tasks.backend.temporal.process_task.sandbox_credentials.resolve_coordinated_user_token")
@patch("products.tasks.backend.temporal.process_task.utils.get_cached_github_user_token")
@patch("products.tasks.backend.temporal.process_task.utils.get_user_github_integration")
def test_user_authorship_requires_reauthorization_without_team_fallback(
@@ -460,16 +466,16 @@ class TestGetSandboxGitHubToken(TestCase):
error_case: str,
mock_get_identity: MagicMock,
mock_cached: MagicMock,
+ mock_resolve: MagicMock,
) -> None:
from posthog.models.user_integration import ReauthorizationRequired
mock_cached.return_value = None
- identity = MagicMock()
+ mock_get_identity.return_value = MagicMock()
if error_case == "reauthorization":
- identity.get_usable_user_access_token.side_effect = ReauthorizationRequired("reauthorize GitHub")
+ mock_resolve.side_effect = ReauthorizationRequired("reauthorize GitHub")
else:
- identity.get_usable_user_access_token.return_value = None
- mock_get_identity.return_value = identity
+ mock_resolve.return_value = None
with self.assertRaises(ReauthorizationRequired):
get_sandbox_github_token(
@@ -511,6 +517,53 @@ class TestGetSandboxGitHubToken(TestCase):
assert result is None
+ @patch("products.tasks.backend.temporal.process_task.utils.get_github_token")
+ @patch("products.tasks.backend.temporal.process_task.utils.get_user_github_integration")
+ @patch("products.tasks.backend.temporal.process_task.utils.get_cached_github_user_token")
+ def test_caller_token_run_never_substitutes_server_integration(
+ self, mock_cached: MagicMock, mock_get_identity: MagicMock, mock_get_github_token: MagicMock
+ ) -> None:
+ mock_cached.return_value = None # caller-supplied token has expired from the cache
+
+ result = get_sandbox_github_token(
+ 123,
+ run_id="run-1",
+ state={"pr_authorship_mode": "user", "github_credential_source": "caller_token"},
+ created_by=MagicMock(name="creator"),
+ )
+
+ assert result is None
+ mock_get_identity.assert_not_called()
+ mock_get_github_token.assert_not_called()
+
+
+class TestGitHubCredentialSourceHelpers(TestCase):
+ def test_get_github_credential_source_reads_marker(self) -> None:
+ assert (
+ get_github_credential_source({"github_credential_source": "caller_token"})
+ == GitHubCredentialSource.CALLER_TOKEN
+ )
+ assert (
+ get_github_credential_source({"github_credential_source": "server_integration"})
+ == GitHubCredentialSource.SERVER_INTEGRATION
+ )
+ assert get_github_credential_source({}) is None
+ assert get_github_credential_source(None) is None
+
+ def test_marker_is_authoritative_over_cache(self) -> None:
+ with patch("products.tasks.backend.temporal.process_task.utils.get_cached_github_user_token") as mock_cached:
+ assert is_caller_token_run("run-1", {"github_credential_source": "caller_token"}) is True
+ assert is_caller_token_run("run-1", {"github_credential_source": "server_integration"}) is False
+ # Marker decides regardless of cache state — never falls through.
+ mock_cached.assert_not_called()
+
+ @parameterized.expand([("ghu_caller", True), (None, False)])
+ def test_unmarked_run_falls_back_to_cache(self, cached: str | None, expected: bool) -> None:
+ with patch(
+ "products.tasks.backend.temporal.process_task.utils.get_cached_github_user_token", return_value=cached
+ ):
+ assert is_caller_token_run("run-1", {}) is expected
+
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
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 8003e4279863..115824e628eb 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import logging
from dataclasses import dataclass, field
from enum import StrEnum
from typing import TYPE_CHECKING, Any, Optional
@@ -22,12 +23,21 @@ if TYPE_CHECKING:
from products.tasks.backend.models import Task
+logger = logging.getLogger(__name__)
+
class PrAuthorshipMode(StrEnum):
USER = "user"
BOT = "bot"
+class GitHubCredentialSource(StrEnum):
+ # Caller-supplied static token on the run request; owned by the caller, un-refreshable by us.
+ CALLER_TOKEN = "caller_token"
+ # Task creator's refreshable server-side UserIntegration.
+ SERVER_INTEGRATION = "server_integration"
+
+
class RunSource(StrEnum):
MANUAL = "manual"
SIGNAL_REPORT = "signal_report"
@@ -159,6 +169,7 @@ def get_reasoning_effort_error(
class RunState(BaseModel, extra="allow"):
pr_authorship_mode: PrAuthorshipMode | None = None
+ github_credential_source: GitHubCredentialSource | None = None
pr_base_branch: str | None = None
run_source: RunSource | None = None
signal_report_id: str | None = None
@@ -508,6 +519,22 @@ def get_cached_github_user_token(run_id: str) -> str | None:
return token if isinstance(token, str) and token else None
+def get_github_credential_source(state: dict[str, Any] | None) -> GitHubCredentialSource | None:
+ return parse_run_state(state).github_credential_source
+
+
+def is_caller_token_run(run_id: str, state: dict[str, Any] | None) -> bool:
+ """Whether a run is pinned to a caller-supplied static token (never the server integration).
+
+ The durable run-state marker is authoritative and outlives the token cache. Runs created
+ before the marker existed fall back to the legacy per-run cache while it is still populated.
+ """
+ source = get_github_credential_source(state)
+ if source is not None:
+ return source == GitHubCredentialSource.CALLER_TOKEN
+ return get_cached_github_user_token(run_id) is not None
+
+
def get_sandbox_github_token(
github_integration_id: int | None,
*,
@@ -545,6 +572,14 @@ def get_sandbox_github_token(
cached = get_cached_github_user_token(run_id)
if cached:
return cached
+ if get_github_credential_source(state) == GitHubCredentialSource.CALLER_TOKEN:
+ # Caller-supplied token expired from cache and is un-refreshable by us. Do NOT
+ # fall back to the creator's integration — that would silently swap identities.
+ logger.warning(
+ "Caller-supplied GitHub token unavailable; not substituting server integration",
+ extra={"run_id": run_id},
+ )
+ return None
if task is not None:
user_github_integration = resolve_user_github_integration_for_task(
task,
@@ -564,15 +599,21 @@ def get_sandbox_github_token(
f"User-authored run {run_id} requires a linked GitHub account with repo access."
)
return get_github_token(github_integration_id)
+ # 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
+ resolve_coordinated_user_token,
+ )
+
if github_integration_id is None:
- no_team_token: str | None = user_github_integration.get_usable_user_access_token()
+ no_team_token: str | None = resolve_coordinated_user_token(user_github_integration)
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()
+ token: str | None = resolve_coordinated_user_token(user_github_integration)
except ReauthorizationRequired:
token = None
if token is not None:
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 05535a039687..f87bf43b7f3c 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -1710,6 +1710,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert task_run.state["pr_authorship_mode"] == "user"
assert task_run.state["run_source"] == "manual"
assert task_run.state["pr_base_branch"] == "main"
+ assert task_run.state["github_credential_source"] == "server_integration"
task.refresh_from_db()
assert task.github_user_integration_id == user_integration.id
mock_workflow.assert_called_once()
@@ -1737,6 +1738,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert response.status_code == status.HTTP_200_OK
task_run = TaskRun.objects.get(id=response.json()["latest_run"]["id"])
assert get_cached_github_user_token(str(task_run.id)) == github_user_token
+ assert task_run.state["github_credential_source"] == "caller_token"
mock_workflow.assert_called_once()
@patch("products.tasks.backend.api.execute_task_processing_workflow")
@@ -3070,6 +3072,53 @@ class TestTaskRunAPI(BaseTaskAPITest):
mock_signal.assert_called_once()
mock_publish_stream_state_event.assert_called_once()
+ @patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")
+ def test_patch_cannot_mutate_protected_credential_state_keys(self, _mock_publish):
+ task = self.create_task()
+ run = TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ state={
+ "github_credential_source": "caller_token",
+ "pr_authorship_mode": "user",
+ "sandbox_id": "sb-real",
+ },
+ )
+
+ # A caller cannot escalate to the creator's integration, flip authorship, or repoint the
+ # credential-propagation target at a sandbox they control. Non-protected keys still merge.
+ response = self.client.patch(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",
+ {
+ "state": {
+ "github_credential_source": "server_integration",
+ "pr_authorship_mode": "bot",
+ "sandbox_id": "sb-attacker",
+ "scratch": "ok",
+ }
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ run.refresh_from_db()
+ assert run.state["github_credential_source"] == "caller_token"
+ assert run.state["pr_authorship_mode"] == "user"
+ assert run.state["sandbox_id"] == "sb-real"
+ assert run.state["scratch"] == "ok" # non-protected keys still merge
+
+ # Nor can a caller remove a protected key to force a fallback or unguarded path.
+ response = self.client.patch(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",
+ {"state": {}, "state_remove_keys": ["github_credential_source", "sandbox_id", "scratch"]},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ run.refresh_from_db()
+ assert run.state["github_credential_source"] == "caller_token" # protected key survives removal
+ assert run.state["sandbox_id"] == "sb-real" # protected key survives removal
+ assert "scratch" not in run.state # non-protected key removed
+
@patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
def test_update_run_status_to_completed_signals_workflow(self, mock_signal):
task = self.create_task()