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.

feat(tasks): pick up a personal GitHub connected mid-run (#80743)

Vojta Bartoše8e0c8a680d3
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index 58937f0b56b0..d0ed7a1d52f2 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -764,8 +764,10 @@ class DockerSandbox(SandboxBase):
encoded_payload = base64.b64encode(payload).decode("utf-8")
temp_path = f"{path}.tmp-{uuid.uuid4().hex}"
result = ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
- for index in range(0, len(encoded_payload), chunk_size):
- chunk = encoded_payload[index : index + chunk_size]
+ # An empty payload still has to produce an empty file: with no chunks the temp path is
+ # never created and the mv below fails. Blanking a credential file is exactly this case.
+ chunks = [encoded_payload[start : start + chunk_size] for start in range(0, len(encoded_payload), chunk_size)]
+ for index, chunk in enumerate(chunks or [""]):
write_mode = "wb" if index == 0 else "ab"
command = (
"python3 - <<'EOF_SANDBOX_WRITE'\n"
diff --git a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
index 8dc1de421144..80281f8d89ff 100644
--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
@@ -96,3 +96,23 @@ def test_start_agent_server_launch_failure_is_captured(sandbox: DockerSandbox):
# A genuine non-zero launch is a real fault — it still gets captured.
capture_exception.assert_called_once()
+
+
[email protected]([("empty", b""), ("with_content", b"GITHUB_TOKEN=ghs_x\x00")])
+def test_write_file_creates_the_temp_file_before_moving_it(_name: str, payload: bytes):
+ # Blanking a credential file writes an empty payload. Chunking over an empty string produces
+ # no writes at all, so the mv would rename a temp path that was never created.
+ config = SandboxConfig(name="test-sandbox")
+ sandbox = DockerSandbox(container_id="c" * 64, config=config, host_port=8000)
+ commands: list[str] = []
+
+ def _record(command: str, **kwargs) -> ExecutionResult:
+ commands.append(command)
+ return ExecutionResult(stdout="", stderr="", exit_code=0)
+
+ with patch.object(sandbox, "is_running", return_value=True), patch.object(sandbox, "execute", side_effect=_record):
+ result = sandbox.write_file("/tmp/creds.env", payload)
+
+ assert result.exit_code == 0
+ assert any("EOF_SANDBOX_WRITE" in command for command in commands), "temp file was never written"
+ assert commands[-1].startswith("mv ")
diff --git a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
index f94e5b16c520..45295feaebe6 100644
--- a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
@@ -1,3 +1,4 @@
+import dataclasses
from dataclasses import dataclass, field
from temporalio import activity
@@ -27,6 +28,22 @@ from .get_task_processing_context import TaskProcessingContext
logger = get_logger(__name__)
+def _with_current_authorship(ctx: TaskProcessingContext) -> TaskProcessingContext:
+ """Re-read the run's PR authorship, which `ctx.state` can no longer be trusted for.
+
+ The context is captured once at workflow start, but a run is promoted from bot to user
+ authorship mid-run when its creator connects GitHub. Reading the stale value here resolves
+ the run as bot-authored and re-applies the team installation token over the personal one —
+ handing the creator every repo that installation covers. Only this key is overlaid: the rest
+ of the snapshot (sandbox id, actor) is what the sandbox being refreshed was built against.
+ """
+ persisted = TaskRun.objects.filter(id=ctx.run_id).values_list("state", flat=True).first()
+ mode = (persisted or {}).get("pr_authorship_mode")
+ if not mode or mode == (ctx.state or {}).get("pr_authorship_mode"):
+ return ctx
+ return dataclasses.replace(ctx, state={**(ctx.state or {}), "pr_authorship_mode": mode})
+
+
def _notify_agent_server_of_refresh(ctx: TaskProcessingContext, task: Task, refreshed_kinds: list[str]) -> None:
"""Tell the running agent-server which credentials were re-injected so it logs them.
This is best-effort since the sandbox may be unreachable, so a failure here never fails the refresh itself.
@@ -102,6 +119,7 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
id=ctx.task_id
)
)
+ ctx = _with_current_authorship(ctx)
except Task.DoesNotExist:
logger.info(
"sandbox_credentials_refresh_stopped_task_gone",
diff --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.py
index 3b3fbf1ada45..507bfbfc8fa2 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
@@ -40,7 +40,6 @@ from products.tasks.backend.temporal.process_task.utils import (
get_actor_distinct_id,
get_imported_mcp_server_configs,
get_pr_authorship_mode,
- get_sandbox_github_identity_user,
get_sandbox_github_token,
get_sandbox_mcp_session_user,
get_sandbox_ph_mcp_configs,
@@ -52,6 +51,7 @@ from products.tasks.backend.temporal.process_task.utils import (
mark_sandbox_mcp_session,
record_message_actor,
sandbox_identity_scope,
+ upgrade_run_to_user_authorship,
)
from ee.hogai.sandbox import STOP_REASON_END_TURN, TURN_COMPLETE_METHOD
@@ -482,11 +482,11 @@ def _resolve_live_sandbox(state: dict[str, Any] | None) -> Any:
def _refresh_sandbox_github(task_run: TaskRun, actor_user: Any, state: dict[str, Any] | None) -> bool:
"""Bind the sandbox's in-place GitHub credentials to this message's actor.
- On an actor transition: re-inject the new actor's token if they have usable
- access, otherwise log the sandbox out (strip the token from the git remote
- and env) so the previous actor's GitHub identity can never be used by a
- follow-up actor who lacks access. Reauthorization for that actor is surfaced
- by the existing credential-refresh path, unchanged.
+ Runs on every turn, for every actor: re-inject the acting user's token if they
+ have usable access, otherwise log the sandbox out (strip the token from the git
+ remote and env). Someone can connect or disconnect their GitHub between any two
+ messages, so the sandbox is never assumed to still reflect the last turn — and a
+ follow-up actor can never inherit the previous actor's identity.
Only USER-authored runs carry per-actor identity — BOT runs share one
installation token, so every actor is already the same identity. This
@@ -494,22 +494,30 @@ def _refresh_sandbox_github(task_run: TaskRun, actor_user: Any, state: dict[str,
keeps a continuous actor's token rotated between transitions.
Returns ``True`` when the sandbox safely reflects this actor (rebound, logged
- out, or nothing to do) and ``False`` only when we could neither rebind nor
- even clear — the previous actor's credentials may still be live, so the
- caller fails the follow-up closed.
+ out, or nothing to do) and ``False`` when we could neither rebind nor even
+ clear. That is fail-closed for everyone, including an actor who revoked their
+ own connection: deleting a `UserIntegration` does not revoke the token GitHub
+ already issued, so an unconfirmed clear can leave it usable in the sandbox.
"""
if actor_user is None:
return True
run_id = str(task_run.id)
- scope = sandbox_identity_scope(run_id, state)
- if get_sandbox_github_identity_user(scope) == actor_user.id:
- return True # sandbox already reflects this actor — cheapest check first
-
task = task_run.task
+ # A run that started before its actor connected GitHub is bot-authored, and the agent may
+ # have been the one that asked them to connect. Promote it so the turn that follows the
+ # connection is the one that gets their identity.
+ promoted_state = upgrade_run_to_user_authorship(task_run, actor_user, state)
+ if promoted_state is not None:
+ state = promoted_state
+
+ scope = sandbox_identity_scope(run_id, state)
if get_pr_authorship_mode(task, state) != PrAuthorshipMode.USER:
return True
+ # Re-established every turn rather than skipped when the actor is unchanged: they can connect
+ # or disconnect their GitHub between any two messages, and the sandbox can lose its token to a
+ # resume or snapshot restore. Apply the token whenever one resolves, clear it when none does.
sandbox = _resolve_live_sandbox(state)
if sandbox is None:
# We are past the same-actor fast path, so this is an unconfirmed transition. The
@@ -585,6 +593,10 @@ def _refresh_sandbox_github(task_run: TaskRun, actor_user: Any, state: dict[str,
logger.warning("refresh_github_logout_failed", run_id=run_id, user_id=actor_user.id, exc_info=True)
return False
if cleared:
+ # Still record the actor: the marker tells owner-scoped refreshes that this sandbox is
+ # bound away from the run owner, and clearing it would let the scheduled refresh inject
+ # the owner's token into this actor's session. It does not gate the rebind — every turn
+ # re-establishes — so a reconnect is still picked up.
mark_sandbox_github_identity(scope, actor_user.id)
logger.info("refresh_github_logged_out", run_id=run_id, user_id=actor_user.id)
return True
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
index ac4d1c68024a..150ce9479055 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
@@ -12,7 +12,7 @@ from posthog.models.integration import Integration
from products.tasks.backend.exceptions import SandboxExecutionError, SandboxNotFoundError, SandboxNotRunningError
from products.tasks.backend.logic.services.sandbox import ExecutionResult
-from products.tasks.backend.models import Task
+from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (
RefreshSandboxCredentialsInput,
refresh_sandbox_credentials,
@@ -64,6 +64,32 @@ class TestRefreshSandboxCredentialsActivity:
assert event_name == "sandbox_credentials_refreshed"
assert track_event.call_args.kwargs["properties"]["refreshed_kinds"] == ["github"]
+ def test_promoted_run_refreshes_as_user_not_the_team_installation(
+ self, activity_environment, task_context, test_task, test_task_run, sandbox
+ ):
+ # The context is captured at workflow start, so a run promoted to user authorship since
+ # then still reads as bot-authored here — and would get the team installation token
+ # re-applied over the user's, widening access to every repo that installation covers.
+ TaskRun.objects.filter(id=test_task_run.id).update(state={"pr_authorship_mode": "user"})
+
+ with (
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.Sandbox.get_by_id",
+ return_value=sandbox,
+ ),
+ patch(
+ "products.tasks.backend.temporal.process_task.sandbox_credentials.get_sandbox_github_token",
+ return_value="ghu_user",
+ ) as get_token,
+ patch("products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.track_event"),
+ ):
+ async_to_sync(activity_environment.run)(
+ refresh_sandbox_credentials,
+ RefreshSandboxCredentialsInput(context=task_context, sandbox_id="sandbox-abc"),
+ )
+
+ assert get_token.call_args.kwargs["state"]["pr_authorship_mode"] == "user"
+
def test_retries_transient_db_connection_drop(self, activity_environment, task_context, test_task, sandbox):
# A pooled pgbouncer connection dropped mid-request raises OperationalError on the
# activity's early Task read. The retry-once guard must evict the dead connection and
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.py
index 3c6d282dd89e..746d2d5b8ee3 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
@@ -390,27 +390,98 @@ class TestSessionIdentityGate:
_GH_MODULE = "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox"
+@patch(f"{_GH_MODULE}.upgrade_run_to_user_authorship", return_value=None)
@patch(f"{_GH_MODULE}.clear_github_credentials_from_sandbox")
@patch(f"{_GH_MODULE}.apply_github_credentials_to_sandbox")
@patch(f"{_GH_MODULE}.get_sandbox_github_token")
@patch(f"{_GH_MODULE}._resolve_live_sandbox")
@patch(f"{_GH_MODULE}.get_pr_authorship_mode")
class TestSandboxGithubIdentityGate:
- """On an actor transition the sandbox's GitHub credentials rebind to the new
- actor when they have access, otherwise the sandbox is logged out so the
- previous actor's identity can't be used."""
+ """Every turn re-establishes the sandbox's GitHub credentials for the acting user:
+ their token when they have access, otherwise a logout so no previous actor's
+ identity survives."""
- def test_same_actor_skips(self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear):
+ def test_same_actor_is_re_established_not_skipped(
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
+ ):
+ # The actor can connect or disconnect between messages, and a resume or snapshot restore
+ # can drop the token, so an unchanged actor is not evidence the sandbox still holds it.
mock_authorship.return_value = PrAuthorshipMode.USER
+ mock_resolve.return_value = MagicMock()
+ mock_get_token.return_value = "ghu_token"
+ mock_apply.return_value = True
mark_sandbox_github_identity("run-1", 42)
assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) is True
- mock_resolve.assert_not_called()
- mock_get_token.assert_not_called()
- mock_apply.assert_not_called()
+ mock_apply.assert_called_once()
+ assert mock_apply.call_args.args[2] == "ghu_token"
mock_clear.assert_not_called()
- def test_bot_authorship_skips(self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear):
+ def test_revoked_connection_logs_the_sandbox_out_on_the_same_actor(
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
+ ):
+ # Same actor as last turn, but their install no longer mints: the cheap skip must not
+ # leave their token live in the sandbox until the refresh loop next runs.
+ mock_authorship.return_value = PrAuthorshipMode.USER
+ mock_resolve.return_value = MagicMock()
+ mock_get_token.return_value = None
+ mock_clear.return_value = True
+ mark_sandbox_github_identity("run-1", 42)
+
+ assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) is True
+ mock_clear.assert_called_once()
+ mock_apply.assert_not_called()
+
+ def test_a_self_revoked_connection_that_cannot_clear_fails_closed(
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
+ ):
+ # Same actor, their own connection revoked, and the clear cannot be confirmed. Deleting the
+ # integration does not revoke the token GitHub already issued, so proceeding could leave it
+ # usable in the sandbox after the user disconnected.
+ mock_authorship.return_value = PrAuthorshipMode.USER
+ mock_resolve.return_value = MagicMock()
+ mock_get_token.return_value = None
+ mock_clear.return_value = False
+ mark_sandbox_github_identity("run-1", 42)
+
+ assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) is False
+
+ def test_a_transition_that_cannot_clear_still_fails_closed(
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
+ ):
+ # A different actor inheriting the previous one's live token is the case the gate exists for.
+ mock_authorship.return_value = PrAuthorshipMode.USER
+ mock_resolve.return_value = MagicMock()
+ mock_get_token.return_value = None
+ mock_clear.return_value = False
+ mark_sandbox_github_identity("run-1", 99)
+
+ assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) is False
+
+ def test_reconnecting_after_a_logout_rebinds_the_actor(
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
+ ):
+ # Revoke, then reconnect. The logout leaves the sandbox marked against this actor, and the
+ # reconnect must still be picked up — no marker check may short-circuit the rebind.
+ mock_authorship.return_value = PrAuthorshipMode.USER
+ mock_resolve.return_value = MagicMock()
+ mock_clear.return_value = True
+ mock_get_token.return_value = None
+ mark_sandbox_github_identity("run-1", 42)
+
+ assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) is True
+ assert get_sandbox_github_identity_user("run-1") == 42
+
+ mock_get_token.return_value = "ghu_reconnected"
+ mock_apply.return_value = True
+
+ assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) is True
+ mock_apply.assert_called_once()
+ assert mock_apply.call_args.args[2] == "ghu_reconnected"
+
+ def test_bot_authorship_skips(
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
+ ):
# BOT runs share a single installation token, so every actor is already
# the same GitHub identity — nothing to rebind.
mock_authorship.return_value = PrAuthorshipMode.BOT
@@ -422,7 +493,7 @@ class TestSandboxGithubIdentityGate:
mock_clear.assert_not_called()
def test_transition_with_access_rebinds(
- self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
):
mock_authorship.return_value = PrAuthorshipMode.USER
mock_resolve.return_value = MagicMock()
@@ -437,7 +508,7 @@ class TestSandboxGithubIdentityGate:
assert get_sandbox_github_identity_user("run-1") == 42
def test_transition_without_access_logs_out(
- self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
):
mock_authorship.return_value = PrAuthorshipMode.USER
mock_resolve.return_value = MagicMock()
@@ -448,10 +519,12 @@ class TestSandboxGithubIdentityGate:
assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) is True
mock_apply.assert_not_called()
mock_clear.assert_called_once()
+ # Still marked: owner-scoped refreshes read this to know the sandbox is bound away from the
+ # run owner, and must not inject the owner's token into this actor's session.
assert get_sandbox_github_identity_user("run-1") == 42
def test_apply_failure_falls_back_to_logout(
- self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
):
mock_authorship.return_value = PrAuthorshipMode.USER
mock_resolve.return_value = MagicMock()
@@ -465,7 +538,7 @@ class TestSandboxGithubIdentityGate:
mock_clear.assert_called_once() # fell through to logout so no stale creds remain
def test_apply_incomplete_falls_back_to_logout(
- self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
):
# A partial credential write (one location refused, no exception) is not a confirmed
# rebind: the prior actor's token may still be live in the other location, so log out
@@ -480,10 +553,12 @@ class TestSandboxGithubIdentityGate:
assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) is True
mock_apply.assert_called_once()
mock_clear.assert_called_once()
+ # Still marked: owner-scoped refreshes read this to know the sandbox is bound away from the
+ # run owner, and must not inject the owner's token into this actor's session.
assert get_sandbox_github_identity_user("run-1") == 42 # logout confirmed, bound to new actor
def test_no_sandbox_handle_fails_closed(
- self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
):
# The handle can't be resolved (dead sandbox or transient lookup failure), but a follow-up
# can still reach a live agent via the saved URL. Fail closed rather than run under the
@@ -498,7 +573,9 @@ class TestSandboxGithubIdentityGate:
mock_clear.assert_not_called()
assert get_sandbox_github_identity_user("run-1") == 99 # binding unchanged
- def test_logout_failure_fails_closed(self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear):
+ def test_logout_failure_fails_closed(
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
+ ):
# New actor has no access and the sandbox can't even be cleared — the
# previous actor's creds may still be live, so fail closed.
mock_authorship.return_value = PrAuthorshipMode.USER
@@ -510,7 +587,9 @@ class TestSandboxGithubIdentityGate:
assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) is False
assert get_sandbox_github_identity_user("run-1") == 99 # binding unchanged
- def test_logout_exception_fails_closed(self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear):
+ def test_logout_exception_fails_closed(
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
+ ):
# The clear itself raising (sandbox stopped/timed out between is_running and here) must
# fail closed, not escape uncontrolled.
mock_authorship.return_value = PrAuthorshipMode.USER
@@ -523,7 +602,7 @@ class TestSandboxGithubIdentityGate:
assert get_sandbox_github_identity_user("run-1") == 99 # binding unchanged
def test_credential_unavailable_logs_out(
- self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear
+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
):
# A disconnected/deleted integration mid-run yields no usable credential (not just
# ReauthorizationRequired): log out rather than let the exception escape.
@@ -538,6 +617,8 @@ class TestSandboxGithubIdentityGate:
assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) is True
mock_apply.assert_not_called()
mock_clear.assert_called_once()
+ # Still marked: owner-scoped refreshes read this to know the sandbox is bound away from the
+ # run owner, and must not inject the owner's token into this actor's session.
assert get_sandbox_github_identity_user("run-1") == 42
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 986cd107ee64..970c81974359 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -30,6 +30,7 @@ from products.tasks.backend.temporal.process_task.utils import (
get_user_mcp_server_configs,
is_caller_token_run,
loop_mcp_installation_allowlist,
+ upgrade_run_to_user_authorship,
)
@@ -1225,3 +1226,114 @@ class TestBuildSandboxEnvironmentVariables(SimpleTestCase):
env = build_sandbox_environment_variables(None, "access-token", 1)
assert not any(key.startswith("POSTHOG_AGENT_OTEL_") for key in env)
+
+
+class _AuthorshipFixture(TestCase):
+ def setUp(self) -> None:
+ from posthog.models import Organization, Team
+ from posthog.models.user import User
+
+ from products.tasks.backend.models import TaskRun
+
+ self.organization = Organization.objects.create(name="authorship-org")
+ self.team = Team.objects.create(organization=self.organization, name="authorship-team")
+ self.user = User.objects.create(email="[email protected]")
+ self.task = Task.objects.create(
+ team=self.team,
+ title="t",
+ description="d",
+ origin_product=Task.OriginProduct.SLACK,
+ created_by=self.user,
+ repository="posthog/posthog",
+ )
+ self.task_run = TaskRun.objects.create(task=self.task, team=self.team, state={"pr_authorship_mode": "bot"})
+
+ def connect_personal_github(self, *, usable: bool = True) -> None:
+ from posthog.models.user_integration import UserIntegration
+
+ UserIntegration.objects.create(
+ user=self.user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id="gh-1",
+ config={} if usable else {"user_refresh_token_expires_at": 1},
+ sensitive_config={"user_access_token": "at", "user_refresh_token": "rt"},
+ )
+
+
+class TestUpgradeRunToUserAuthorship(_AuthorshipFixture):
+ def test_a_connection_made_mid_run_promotes_the_run(self) -> None:
+ self.connect_personal_github()
+
+ promoted = upgrade_run_to_user_authorship(self.task_run, self.user, self.task_run.state)
+
+ assert promoted is not None
+ assert promoted["pr_authorship_mode"] == "user"
+ self.task_run.refresh_from_db()
+ self.task.refresh_from_db()
+ assert self.task_run.state["pr_authorship_mode"] == "user"
+ # Per-actor credential state stays off the shared task row.
+ assert self.task.github_user_integration_id is None
+
+ def test_the_state_passed_in_is_left_untouched(self) -> None:
+ self.connect_personal_github()
+ state = {"pr_authorship_mode": "bot"}
+
+ upgrade_run_to_user_authorship(self.task_run, self.user, state)
+
+ assert state == {"pr_authorship_mode": "bot"}
+
+ def _no_actor(self) -> None:
+ self.connect_personal_github()
+ self.actor = None
+
+ def _no_personal_install(self) -> None:
+ pass
+
+ def _stale_personal_install(self) -> None:
+ self.connect_personal_github(usable=False)
+
+ def _already_user_authored(self) -> None:
+ self.connect_personal_github()
+ self._set_state({"pr_authorship_mode": "user"})
+
+ def _caller_token_run(self) -> None:
+ self.connect_personal_github()
+ self._set_state({"pr_authorship_mode": "bot", "github_credential_source": "caller_token"})
+
+ def _a_different_actor_than_the_creator(self) -> None:
+ from posthog.models.user import User
+
+ self.connect_personal_github()
+ participant = User.objects.create(email="[email protected]")
+ participant.join(organization=self.organization)
+ self.actor = participant
+
+ def _signal_report_origin(self) -> None:
+ self.connect_personal_github()
+ self.task.origin_product = Task.OriginProduct.SIGNAL_REPORT
+ self.task.save(update_fields=["origin_product"])
+
+ def _set_state(self, state: dict) -> None:
+ self.task_run.state = state
+ self.task_run.save(update_fields=["state"])
+
+ @parameterized.expand(
+ [
+ ("no_actor",),
+ ("no_personal_install",),
+ ("stale_personal_install",),
+ ("already_user_authored",),
+ ("caller_token_run",),
+ ("signal_report_origin",),
+ ("a_different_actor_than_the_creator",),
+ ]
+ )
+ def test_nothing_is_promoted(self, case: str) -> None:
+ self.actor = self.user
+ getattr(self, f"_{case}")()
+ state_before = dict(self.task_run.state)
+
+ assert upgrade_run_to_user_authorship(self.task_run, self.actor, self.task_run.state) is None
+
+ self.task_run.refresh_from_db()
+ assert self.task_run.state == state_before
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index ac55448b1eed..ed7ab16c7378 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -66,6 +66,10 @@ class RunSource(StrEnum):
SIGNAL_REPORT = "signal_report"
+# Origins whose runs are meant to carry a human git identity; everything else is bot-authored.
+USER_AUTHORABLE_ORIGIN_PRODUCTS: tuple[str, ...] = ("user_created", "slack")
+
+
class RuntimeAdapter(StrEnum):
CLAUDE = "claude"
CODEX = "codex"
@@ -498,11 +502,13 @@ def get_sandbox_mcp_session_user(scope: str) -> int | None:
def mark_sandbox_github_identity(scope: str, user_id: int) -> None:
"""Record which actor the sandbox's in-place GitHub credentials reflect.
- The value is the actor whose token was applied, or who was logged out (no
- usable access) — either way the sandbox no longer carries a *different*
- actor's identity. Self-expires after MCP_TOKEN_REFRESH_INTERVAL_SECONDS; an
- absent entry reads as "must re-establish", which is always safe because
- re-establishing re-applies or clears rather than trusting stale creds.
+ The value is the actor whose token was applied, or who was logged out (no usable
+ access) — either way the sandbox no longer carries a *different* actor's identity,
+ which is what owner-scoped refreshes check before re-applying the owner's token.
+
+ Self-expires after MCP_TOKEN_REFRESH_INTERVAL_SECONDS; an absent entry reads as
+ "must re-establish", which is always safe because re-establishing re-applies or
+ clears rather than trusting stale creds.
"""
_mark_sandbox_identity("github-identity", scope, user_id)
@@ -1290,11 +1296,62 @@ def get_pr_authorship_mode(task: Task, state: dict[str, Any] | None = None) -> P
if task.origin_product == TaskModel.OriginProduct.SIGNAL_REPORT:
return PrAuthorshipMode.BOT
- return (
- PrAuthorshipMode.USER
- if task.origin_product in (TaskModel.OriginProduct.USER_CREATED, TaskModel.OriginProduct.SLACK)
- else PrAuthorshipMode.BOT
+ return PrAuthorshipMode.USER if task.origin_product in USER_AUTHORABLE_ORIGIN_PRODUCTS else PrAuthorshipMode.BOT
+
+
+def upgrade_run_to_user_authorship(
+ task_run: TaskRun, actor_user: User | None, state: dict[str, Any] | None
+) -> dict[str, Any] | None:
+ """Promote a run that fell back to bot authorship once its actor has a usable install.
+
+ A run started by someone with no personal GitHub is created as `BOT` and that value is
+ frozen in run state, so connecting GitHub mid-thread would otherwise never take effect —
+ the agent asks for the connection precisely when it needs the code, and the next turn has
+ to honor it. Only the fallback is promoted: a run that is bot-authored by design (signal
+ reports) or pinned to a caller-supplied token keeps the identity it was given.
+
+ There is no mirror image of this. A disconnection leaves the run on `USER` and lets token
+ resolution fail, which logs the sandbox out; falling back to the team installation would
+ hand broader access to someone who just revoked their own, and silently move PR authorship
+ onto the bot.
+
+ Returns the run's new persisted state when it was promoted, and None when nothing changed.
+ The state passed in is left untouched.
+ """
+ from products.tasks.backend.models import TaskRun as TaskRunModel
+
+ if actor_user is None:
+ return None
+ task = task_run.task
+ if task.origin_product not in USER_AUTHORABLE_ORIGIN_PRODUCTS:
+ return None
+ # Promotion is only for the creator. A thread participant's connection would retarget a run
+ # they don't own, and later turns by a creator without one would then resolve to nothing
+ # instead of the bot fallback they had. The cloud path refuses the same case outright.
+ if task.created_by_id != actor_user.id:
+ return None
+ if get_pr_authorship_mode(task, state) != PrAuthorshipMode.BOT:
+ return None
+ if is_caller_token_run(str(task_run.id), state):
+ return None
+
+ # Nothing is pinned to the task: `Task.github_user_integration` only disambiguates *which*
+ # install to use when a user has several, and token resolution finds this one on its own by
+ # scoping to the repository. Writing it would put per-actor credential state on a row shared
+ # by every run of the task, for no gain.
+ if not user_github_integration_is_usable(
+ resolve_user_github_integration_for_task(task, actor_user=actor_user, allow_refresh=False)
+ ):
+ return None
+
+ promoted_state = TaskRunModel.update_state_atomic(
+ task_run.id, updates={"pr_authorship_mode": PrAuthorshipMode.USER.value}
+ )
+ logger.info(
+ "run_promoted_to_user_authorship",
+ extra={"run_id": str(task_run.id), "task_id": str(task.id), "user_id": actor_user.id},
)
+ return promoted_state
def get_git_identity_env_vars(task: Task, state: dict[str, Any] | None = None) -> dict[str, str]: