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): preserve refreshed GitHub credentials in sandboxes (#72540)

Alessandro Pogliaghie557a5cd9aae
diff --git a/products/tasks/backend/logic/services/agentsh.py b/products/tasks/backend/logic/services/agentsh.py
index ffe0a626ec64..93b64cc67704 100644
--- a/products/tasks/backend/logic/services/agentsh.py
+++ b/products/tasks/backend/logic/services/agentsh.py
@@ -5,12 +5,16 @@ from django.conf import settings
import yaml
+from products.tasks.backend.constants import SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS
+
AGENTSH_DAEMON_PORT = 18080
SESSION_ID_FILE = "/tmp/agentsh-session-id"
ENV_FILE = "/tmp/agent-env"
+GITHUB_ENV_FILE = "/tmp/agent-github-env"
+OAUTH_ENV_FILE = "/tmp/agent-oauth-env"
ENV_WRAPPER_SCRIPT = "/tmp/agentsh-env-wrapper.sh"
# Sourced via BASH_ENV on every `bash -c` the agent runs, so git/gh pick up a
-# mid-session GitHub credential refresh (the backend rewrites ENV_FILE in place).
+# mid-session GitHub credential refresh from its dedicated credential file.
BASH_ENV_SCRIPT = "/tmp/agentsh-bash-env.sh"
AGENTSH_AUDIT_DB = "/var/lib/agentsh/events.db"
INFRASTRUCTURE_DOMAINS = [
@@ -93,7 +97,22 @@ def _get_debug_only_ports() -> list[int]:
return ports
-def generate_env_wrapper() -> str:
+_MANAGED_CREDENTIAL_ENV_KEYS = ("GH_TOKEN", "GITHUB_TOKEN", "POSTHOG_PERSONAL_API_KEY")
+_EXCLUDED_AGENT_ENV_KEYS = (
+ *SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS,
+ "BASH_ENV",
+ "PROMPT_COMMAND",
+ "PYTHONSTARTUP",
+ "PERL5OPT",
+ "RUBYOPT",
+)
+
+
+def generate_env_wrapper(
+ env_file: str = ENV_FILE,
+ github_env_file: str = GITHUB_ENV_FILE,
+ oauth_env_file: str = OAUTH_ENV_FILE,
+) -> str:
"""Generate a wrapper that restores the full sandbox environment.
``agentsh exec`` starts child processes with a heavily stripped
@@ -104,25 +123,107 @@ def generate_env_wrapper() -> str:
Network policy enforcement happens at the syscall level (ptrace) —
it does not depend on proxy environment variables.
"""
+ quoted_env_file = shlex.quote(env_file)
+ quoted_github_env_file = shlex.quote(github_env_file)
+ quoted_oauth_env_file = shlex.quote(oauth_env_file)
+ excluded_names = " ".join((*_MANAGED_CREDENTIAL_ENV_KEYS, *_EXCLUDED_AGENT_ENV_KEYS))
+ excluded_entries = "|".join(f"{name}=*" for name in (*_MANAGED_CREDENTIAL_ENV_KEYS, *_EXCLUDED_AGENT_ENV_KEYS))
return f"""\
#!/bin/bash
+unset {excluded_names}
+while IFS= read -r -d $'\\0' line; do
+ case "$line" in
+ {excluded_entries}) ;;
+ *) export "$line" ;;
+ esac
+done < {quoted_env_file} 2>/dev/null
+
+while IFS= read -r -d $'\\0' line; do
+ case "$line" in
+ GH_TOKEN=*|GITHUB_TOKEN=*) export "$line" ;;
+ esac
+done < {quoted_github_env_file} 2>/dev/null
+
while IFS= read -r -d $'\\0' line; do
- export "$line"
-done < {ENV_FILE}
+ case "$line" in
+ POSTHOG_PERSONAL_API_KEY=*) export "$line" ;;
+ esac
+done < {quoted_oauth_env_file} 2>/dev/null
exec "$@"
"""
-def generate_bash_env_script() -> str:
+def generate_bash_env_script(
+ env_file: str = ENV_FILE,
+ github_env_file: str = GITHUB_ENV_FILE,
+ oauth_env_file: str = OAUTH_ENV_FILE,
+) -> str:
"""
- Generate the script sourced via ``BASH_ENV``.
+ Generate the script sourced via ``BASH_ENV`` and used to initialize its env file.
+
+ The explicit invocation runs before the background agent-server launch. It
+ atomically replaces the full environment with the current sandbox process
+ environment, excluding launch hooks and credentials. Credential files are
+ initialized only when absent, so a backend refresh that happened before startup
+ wins. Sourced invocations stay cheap and only export GitHub credentials.
"""
+ quoted_env_file = shlex.quote(env_file)
+ quoted_github_env_file = shlex.quote(github_env_file)
+ quoted_oauth_env_file = shlex.quote(oauth_env_file)
+ excluded_entries = "|".join(f"{name}=*" for name in (*_MANAGED_CREDENTIAL_ENV_KEYS, *_EXCLUDED_AGENT_ENV_KEYS))
return f"""\
+if [[ "${{BASH_SOURCE[0]}}" == "$0" ]]; then
+ set -euo pipefail
+ umask 077
+ env_tmp="$(mktemp {quoted_env_file}.tmp.XXXXXX)"
+ github_tmp="$(mktemp {quoted_github_env_file}.tmp.XXXXXX)"
+ oauth_tmp="$(mktemp {quoted_oauth_env_file}.tmp.XXXXXX)"
+ trap 'rm -f "$env_tmp" "$github_tmp" "$oauth_tmp"' EXIT
+
+ while IFS= read -r -d $'\\0' kv 2>/dev/null; do
+ case "$kv" in
+ {excluded_entries}) ;;
+ *) printf '%s\\0' "$kv" >> "$env_tmp" ;;
+ esac
+ done < <(env -0)
+ chmod 600 "$env_tmp"
+ mv "$env_tmp" {quoted_env_file}
+
+ github_token="${{GITHUB_TOKEN:-${{GH_TOKEN:-}}}}"
+ if [[ -n "$github_token" ]]; then
+ printf 'GITHUB_TOKEN=%s\\0GH_TOKEN=%s\\0' "$github_token" "$github_token" > "$github_tmp"
+ fi
+ chmod 600 "$github_tmp"
+ if [[ -e {quoted_github_env_file} || -L {quoted_github_env_file} ]]; then
+ [[ -f {quoted_github_env_file} && ! -L {quoted_github_env_file} ]]
+ chmod 600 {quoted_github_env_file}
+ else
+ if ! ln "$github_tmp" {quoted_github_env_file} 2>/dev/null; then
+ [[ -f {quoted_github_env_file} && ! -L {quoted_github_env_file} ]]
+ fi
+ fi
+
+ if [[ -n "${{POSTHOG_PERSONAL_API_KEY:-}}" ]]; then
+ printf 'POSTHOG_PERSONAL_API_KEY=%s\\0' "$POSTHOG_PERSONAL_API_KEY" > "$oauth_tmp"
+ fi
+ chmod 600 "$oauth_tmp"
+ if [[ -e {quoted_oauth_env_file} || -L {quoted_oauth_env_file} ]]; then
+ [[ -f {quoted_oauth_env_file} && ! -L {quoted_oauth_env_file} ]]
+ chmod 600 {quoted_oauth_env_file}
+ else
+ if ! ln "$oauth_tmp" {quoted_oauth_env_file} 2>/dev/null; then
+ [[ -f {quoted_oauth_env_file} && ! -L {quoted_oauth_env_file} ]]
+ fi
+ fi
+ exit 0
+fi
+
+unset GH_TOKEN GITHUB_TOKEN
while IFS= read -r -d $'\\0' kv 2>/dev/null; do
case "$kv" in
GH_TOKEN=*|GITHUB_TOKEN=*) export "$kv" ;;
esac
-done < {ENV_FILE} 2>/dev/null
+done < {quoted_github_env_file} 2>/dev/null
"""
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index e33ab3035573..598ae9db63bd 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -34,7 +34,6 @@ from products.tasks.backend.models import SandboxSnapshot
from .agentsh import (
BASH_ENV_SCRIPT,
- ENV_FILE,
ENV_WRAPPER_SCRIPT,
SESSION_ID_FILE,
build_exec_prefix,
@@ -852,16 +851,15 @@ class DockerSandbox(SandboxBase):
'export NO_PROXY="host.docker.internal,${NO_PROXY:-localhost,127.0.0.1}"; export no_proxy="$NO_PROXY"; '
)
inner = f"cd /scripts && {no_proxy_export}{server_cmd} > /tmp/agent-server.log 2>&1"
+ initialize_env_file = f"bash {shlex.quote(BASH_ENV_SCRIPT)}"
if allowed_domains is not None:
return (
- f"cd /scripts && env -0 > {ENV_FILE} && "
- f"{build_exec_prefix()} {ENV_WRAPPER_SCRIPT} bash -c {shlex.quote(inner)} &"
+ f"cd /scripts && {initialize_env_file} && "
+ f"({build_exec_prefix()} {ENV_WRAPPER_SCRIPT} bash -c {shlex.quote(inner)} &)"
)
else:
- # Write the env file even without agentsh so BASH_ENV (and the
- # in-process token resolver) can re-read a backend-refreshed token.
- return f"cd /scripts && env -0 > {ENV_FILE} && nohup {server_cmd} > /tmp/agent-server.log 2>&1 &"
+ return f"cd /scripts && {initialize_env_file} && (nohup {server_cmd} > /tmp/agent-server.log 2>&1 &)"
def _launch_and_check(self, command: str) -> bool:
"""Execute the agent-server command and wait for the health check.
diff --git a/products/tasks/backend/logic/services/local_packages.py b/products/tasks/backend/logic/services/local_packages.py
index dcfdc6a5c055..2ee70c13ed8d 100644
--- a/products/tasks/backend/logic/services/local_packages.py
+++ b/products/tasks/backend/logic/services/local_packages.py
@@ -18,6 +18,8 @@ from pathlib import Path
from django.conf import settings
+import yaml
+
logger = logging.getLogger(__name__)
BUILD_OUTPUT_SUBDIR = "dist"
@@ -81,6 +83,7 @@ def get_local_posthog_code_packages() -> tuple[LocalPackage, ...] | None:
def get_local_package_runtime_dependencies(packages: tuple[LocalPackage, ...]) -> dict[str, dict[str, str]]:
"""Collect registry dependencies needed by the overlaid local package builds."""
dependencies: dict[str, dict[str, str]] = {}
+ dependency_catalogs: dict[Path, tuple[dict[str, str], dict[str, dict[str, str]]]] = {}
for package in packages:
manifest_path = package.source_path / "package.json"
@@ -95,6 +98,57 @@ def get_local_package_runtime_dependencies(packages: tuple[LocalPackage, ...]) -
raise ValueError(f"Expected dependency names and versions to be strings in {manifest_path}")
if version.startswith("workspace:"):
continue
+ if version.startswith("catalog:"):
+ workspace_manifest_path = next(
+ (
+ parent / "pnpm-workspace.yaml"
+ for parent in package.source_path.parents
+ if (parent / "pnpm-workspace.yaml").is_file()
+ ),
+ None,
+ )
+ if workspace_manifest_path is None:
+ raise ValueError(f"Could not resolve catalog dependency {name} from {manifest_path}")
+
+ if workspace_manifest_path not in dependency_catalogs:
+ workspace_manifest = yaml.safe_load(workspace_manifest_path.read_text())
+ catalog = workspace_manifest.get("catalog", {}) if isinstance(workspace_manifest, dict) else None
+ catalogs = workspace_manifest.get("catalogs", {}) if isinstance(workspace_manifest, dict) else None
+ if not isinstance(catalog, dict) or not all(
+ isinstance(catalog_name, str) and isinstance(catalog_version, str)
+ for catalog_name, catalog_version in catalog.items()
+ ):
+ raise ValueError(
+ f"Expected catalog to contain string dependencies in {workspace_manifest_path}"
+ )
+ if not isinstance(catalogs, dict) or not all(
+ isinstance(catalog_name, str)
+ and isinstance(named_catalog, dict)
+ and all(
+ isinstance(dependency_name, str) and isinstance(dependency_version, str)
+ for dependency_name, dependency_version in named_catalog.items()
+ )
+ for catalog_name, named_catalog in catalogs.items()
+ ):
+ raise ValueError(
+ f"Expected catalogs to contain named string dependencies in {workspace_manifest_path}"
+ )
+ dependency_catalogs[workspace_manifest_path] = (catalog, catalogs)
+
+ catalog, catalogs = dependency_catalogs[workspace_manifest_path]
+ catalog_reference = version.removeprefix("catalog:")
+ if catalog_reference in {"", "*"}:
+ selected_catalog = catalog
+ else:
+ named_catalog = catalogs.get(catalog_reference)
+ if named_catalog is None:
+ raise ValueError(f"Catalog {catalog_reference} is missing from {workspace_manifest_path}")
+ selected_catalog = named_catalog
+
+ resolved_version = selected_catalog.get(name)
+ if resolved_version is None:
+ raise ValueError(f"Catalog dependency {name} is missing from {workspace_manifest_path}")
+ version = resolved_version
runtime_dependencies[name] = version
if runtime_dependencies:
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 73dc8767c185..61f3b55f87c7 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -55,7 +55,6 @@ from products.tasks.backend.exceptions import (
from products.tasks.backend.logic.services.agentsh import (
AGENTSH_DAEMON_PORT,
BASH_ENV_SCRIPT,
- ENV_FILE,
ENV_WRAPPER_SCRIPT,
SESSION_ID_FILE,
_hostname_from_url,
@@ -1000,14 +999,15 @@ class ModalSandbox(SandboxBase):
server_cmd = f"bash -c {shlex.quote(wait_for_repo)}"
inner = f"cd /scripts && {server_cmd} > /tmp/agent-server.log 2>&1"
+ initialize_env_file = f"bash {shlex.quote(BASH_ENV_SCRIPT)}"
if allowed_domains is not None:
return (
- f"cd /scripts && env -0 > {ENV_FILE} && "
- f"{build_exec_prefix()} {ENV_WRAPPER_SCRIPT} bash -c {shlex.quote(inner)} &"
+ f"cd /scripts && {initialize_env_file} && "
+ f"({build_exec_prefix()} {ENV_WRAPPER_SCRIPT} bash -c {shlex.quote(inner)} &)"
)
else:
- return f"cd /scripts && env -0 > {ENV_FILE} && nohup {server_cmd} > /tmp/agent-server.log 2>&1 &"
+ return f"cd /scripts && {initialize_env_file} && (nohup {server_cmd} > /tmp/agent-server.log 2>&1 &)"
def _diagnose_startup_failure(self, allowed_domains: list[str] | None) -> dict[str, str]:
diagnostics: dict[str, str] = {}
diff --git a/products/tasks/backend/logic/services/tests/test_local_packages.py b/products/tasks/backend/logic/services/tests/test_local_packages.py
index 809769c41e0c..944634707c68 100644
--- a/products/tasks/backend/logic/services/tests/test_local_packages.py
+++ b/products/tasks/backend/logic/services/tests/test_local_packages.py
@@ -8,6 +8,8 @@ from unittest.mock import patch
from products.tasks.backend.logic.services.local_packages import (
BUILD_OUTPUT_SUBDIR,
PACKAGE_NAMES,
+ LocalPackage,
+ get_local_package_runtime_dependencies,
get_local_posthog_code_packages,
)
@@ -67,3 +69,37 @@ class TestGetLocalPosthogCodePackages:
assert packages[0].sandbox_install_path == "/scripts/node_modules/@posthog/agent"
assert packages[0].sandbox_build_output_path == "/scripts/node_modules/@posthog/agent/dist"
assert packages[0].build_output_path == fake_monorepo / "packages" / "agent" / "dist"
+
+
+def test_resolves_default_catalog_runtime_dependencies(fake_monorepo: Path) -> None:
+ (fake_monorepo / "pnpm-workspace.yaml").write_text(
+ "catalog:\n"
+ " catalog-runtime: 1.2.3\n"
+ " star-catalog-runtime: 2.3.4\n"
+ "catalogs:\n"
+ " build:\n"
+ " named-catalog-runtime: 3.4.5\n"
+ )
+ agent_source_path = fake_monorepo / "packages" / "agent"
+ (agent_source_path / "package.json").write_text(
+ '{"dependencies":{'
+ '"catalog-runtime":"catalog:",'
+ '"star-catalog-runtime":"catalog:*",'
+ '"named-catalog-runtime":"catalog:build",'
+ '"registry-runtime":"^4.5.6"'
+ "}}"
+ )
+ package = LocalPackage(
+ name="agent",
+ source_path=agent_source_path,
+ sandbox_install_path="/scripts/node_modules/@posthog/agent",
+ )
+
+ assert get_local_package_runtime_dependencies((package,)) == {
+ "agent": {
+ "catalog-runtime": "1.2.3",
+ "named-catalog-runtime": "3.4.5",
+ "registry-runtime": "^4.5.6",
+ "star-catalog-runtime": "2.3.4",
+ }
+ }
diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
index 78ad1c937925..679265c42090 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -487,7 +487,7 @@ class TestModalSandboxAgentServer:
command = _agent_server_launch_command(mock_sandbox.execute)
assert "--createPr true" in command
assert "agentsh exec --client-timeout 2h --timeout 2h" in command
- assert "env -0 > /tmp/agent-env" in command
+ assert "bash /tmp/agentsh-bash-env.sh" in command
assert "/tmp/agentsh-env-wrapper.sh" in command
assert "./node_modules/.bin/agent-server" in command
@@ -509,7 +509,7 @@ class TestModalSandboxAgentServer:
command = _agent_server_launch_command(mock_sandbox.execute)
assert "--allowedDomains" not in command
assert "agentsh exec --client-timeout 2h --timeout 2h" in command
- assert "env -0 > /tmp/agent-env" in command
+ assert "bash /tmp/agentsh-bash-env.sh" in command
@pytest.mark.parametrize(
("create_pr", "expected_flag"),
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index c152f098e93d..c3303a71c893 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -11,7 +11,7 @@ from posthog.temporal.common.utils import asyncify
from products.tasks.backend.constants import SNAPSHOT_KIND_FILESYSTEM, filter_user_sandbox_env_vars
from products.tasks.backend.exceptions import GitHubAuthenticationError, OAuthTokenError, TaskNotFoundError
-from products.tasks.backend.logic.services.agentsh import ENV_FILE, INFRASTRUCTURE_DOMAINS, _get_debug_only_domains
+from products.tasks.backend.logic.services.agentsh import INFRASTRUCTURE_DOMAINS, _get_debug_only_domains
from products.tasks.backend.logic.services.connection_token import (
SANDBOX_JWT_STATE_KID_KEY,
get_primary_sandbox_jwt_kid,
@@ -27,7 +27,10 @@ from products.tasks.backend.temporal.metrics import (
)
from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_run, create_wizard_oauth_access_token
from products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution
-from products.tasks.backend.temporal.process_task.sandbox_credentials import set_git_remote_token
+from products.tasks.backend.temporal.process_task.sandbox_credentials import (
+ replace_sandbox_credentials,
+ set_git_remote_token,
+)
from products.tasks.backend.temporal.process_task.utils import (
get_git_identity_env_vars,
get_readonly_github_token,
@@ -756,33 +759,13 @@ def inject_fresh_tokens_on_resume(input: InjectFreshTokensOnResumeInput) -> None
sandbox = Sandbox.get_by_id(input.sandbox_id)
- if github_token and input.repository:
- set_git_remote_token(sandbox, input.repository, github_token)
-
- # Pre-seed the agentsh env file so any wrapped command that runs between
- # resume and start_agent_server (diagnostics, branch checkout) sees the
- # fresh tokens instead of the stale snapshot values. start_agent_server
- # re-dumps the full process env over this, so a partial overwrite is fine
- # here (unlike the mid-run refresh, which must preserve the live env).
- fresh_env_vars: dict[str, str] = {}
- if github_token:
- fresh_env_vars["GITHUB_TOKEN"] = github_token
- fresh_env_vars["GH_TOKEN"] = github_token
- if access_token:
- fresh_env_vars["POSTHOG_PERSONAL_API_KEY"] = access_token
-
- if fresh_env_vars:
- env_payload = b"".join(f"{k}={v}\x00".encode() for k, v in fresh_env_vars.items())
- overwrite_result = sandbox.write_file(ENV_FILE, env_payload)
- if overwrite_result.exit_code != 0:
- logger.warning(
- "Failed to refresh agentsh env file on resume",
- extra={
- "sandbox_id": input.sandbox_id,
- "env_file": ENV_FILE,
- "stderr": overwrite_result.stderr,
- },
- )
+ if input.repository:
+ set_git_remote_token(sandbox, input.repository, github_token or None)
+
+ # Replace both credential domains even when resolution returns no token,
+ # so revoked credentials cannot survive in a resumed filesystem snapshot.
+ if not replace_sandbox_credentials(sandbox, github_token or None, access_token or None):
+ raise RuntimeError("Failed to replace resumed sandbox credentials")
emit_agent_log(ctx.run_id, "debug", "Refreshed sandbox credentials after resume")
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py b/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py
index b9295001bba9..0740982fea72 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py
@@ -5,7 +5,7 @@ from asgiref.sync import async_to_sync
from posthog.models import OrganizationMembership, User
-from products.tasks.backend.logic.services.agentsh import ENV_FILE
+from products.tasks.backend.logic.services.agentsh import GITHUB_ENV_FILE, OAUTH_ENV_FILE
from products.tasks.backend.logic.services.sandbox import ExecutionResult
from products.tasks.backend.models import SandboxEnvironment
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
@@ -27,7 +27,9 @@ class TestInjectFreshTokensOnResumeActivity:
fake.write_file.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)
return fake
- def test_refreshes_git_remote_url_and_env_file(self, activity_environment, task_context, test_task, sandbox):
+ def test_refreshes_git_remote_url_and_credential_files(
+ self, activity_environment, task_context, test_task, sandbox
+ ):
with (
patch(
"products.tasks.backend.temporal.process_task.activities.provision_sandbox.Sandbox.get_by_id",
@@ -51,23 +53,22 @@ class TestInjectFreshTokensOnResumeActivity:
),
)
- assert sandbox.execute.call_count == 1
- remote_command = sandbox.execute.call_args[0][0]
+ assert sandbox.execute.call_count == 3
+ remote_command = sandbox.execute.call_args_list[0].args[0]
assert "git remote set-url origin" in remote_command
assert "x-access-token:ghs_new" in remote_command
assert task_context.repository in remote_command
- assert sandbox.write_file.call_count == 1
- path, payload = sandbox.write_file.call_args[0]
- assert path == ENV_FILE
- decoded = payload.decode()
- # Null-separated `env -0` format.
- assert "\x00" in decoded
- assert "GITHUB_TOKEN=ghs_new" in decoded
- assert "GH_TOKEN=ghs_new" in decoded
- assert "POSTHOG_PERSONAL_API_KEY=oauth_new" in decoded
+ assert [call.args for call in sandbox.write_file.call_args_list] == [
+ (GITHUB_ENV_FILE, b"GITHUB_TOKEN=ghs_new\x00GH_TOKEN=ghs_new\x00"),
+ (OAUTH_ENV_FILE, b"POSTHOG_PERSONAL_API_KEY=oauth_new\x00"),
+ ]
+ assert [call.args[0] for call in sandbox.execute.call_args_list[1:]] == [
+ f"chmod 600 {GITHUB_ENV_FILE}",
+ f"chmod 600 {OAUTH_ENV_FILE}",
+ ]
- def test_skips_git_remote_when_github_integration_missing(self, activity_environment, test_task, sandbox):
+ def test_clears_stale_github_credentials_when_integration_missing(self, activity_environment, test_task, sandbox):
context = TaskProcessingContext(
task_id=str(test_task.id),
run_id="run-id",
@@ -98,16 +99,21 @@ class TestInjectFreshTokensOnResumeActivity:
),
)
- sandbox.execute.assert_not_called()
- # OAuth env is still written so POSTHOG_PERSONAL_API_KEY refreshes.
- assert sandbox.write_file.call_count == 1
- _, payload = sandbox.write_file.call_args[0]
- decoded = payload.decode()
- assert "POSTHOG_PERSONAL_API_KEY=oauth_new" in decoded
- assert "GITHUB_TOKEN" not in decoded
+ assert sandbox.execute.call_count == 3
+ remote_command = sandbox.execute.call_args_list[0].args[0]
+ assert "https://github.com/" in remote_command
+ assert "x-access-token" not in remote_command
+ assert [call.args for call in sandbox.write_file.call_args_list] == [
+ (GITHUB_ENV_FILE, b""),
+ (OAUTH_ENV_FILE, b"POSTHOG_PERSONAL_API_KEY=oauth_new\x00"),
+ ]
def test_logs_warning_when_remote_url_update_fails(self, activity_environment, task_context, test_task, sandbox):
- sandbox.execute.return_value = ExecutionResult(stdout="", stderr="fatal: not a git repository", exit_code=128)
+ sandbox.execute.side_effect = [
+ ExecutionResult(stdout="", stderr="fatal: not a git repository", exit_code=128),
+ ExecutionResult(stdout="", stderr="", exit_code=0),
+ ExecutionResult(stdout="", stderr="", exit_code=0),
+ ]
with (
patch(
@@ -133,8 +139,8 @@ class TestInjectFreshTokensOnResumeActivity:
),
)
- assert sandbox.execute.call_count == 1
- assert sandbox.write_file.call_count == 1
+ assert sandbox.execute.call_count == 3
+ assert sandbox.write_file.call_count == 2
def test_prepare_sandbox_injects_user_github_token_without_repository(self, activity_environment, team, user):
from products.tasks.backend.models import Task
diff --git a/products/tasks/backend/temporal/process_task/sandbox_credentials.py b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
index 1b37fbcd18ba..976e494392bc 100644
--- a/products/tasks/backend/temporal/process_task/sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
@@ -1,7 +1,6 @@
"""Refresh long-lived credentials inside a running task sandbox by re-resolving and re-applying tokens in place."""
import shlex
-import base64
import logging
from dataclasses import dataclass
from typing import TYPE_CHECKING, Protocol
@@ -13,7 +12,7 @@ from posthog.models.user_integration import ReauthorizationRequired, UserGitHubI
from posthog.redis import get_client
from products.tasks.backend.exceptions import CredentialUnavailableError
-from products.tasks.backend.logic.services.agentsh import ENV_FILE
+from products.tasks.backend.logic.services.agentsh import GITHUB_ENV_FILE, OAUTH_ENV_FILE
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.process_task.utils import (
PrAuthorshipMode,
@@ -35,6 +34,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
GITHUB_ENV_KEYS = ("GITHUB_TOKEN", "GH_TOKEN")
+OAUTH_ENV_KEY = "POSTHOG_PERSONAL_API_KEY"
# 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
@@ -52,15 +52,18 @@ def github_refresh_interval_seconds(token: str) -> float:
return DEFAULT_REFRESH_INTERVAL_SECONDS
-def set_git_remote_token(sandbox: "SandboxBase", repository: str, github_token: str) -> bool:
- """Rewrite ``origin``'s remote URL with a fresh ``x-access-token``; git re-reads it on every op. No-ops pre-clone."""
+def set_git_remote_token(sandbox: "SandboxBase", repository: str, github_token: str | None) -> bool:
+ """Rewrite ``origin`` with the current credential state; git re-reads it on every operation."""
org, repo = repository.lower().split("/")
repo_path = f"/tmp/workspace/repos/{org}/{repo}"
+ if github_token:
+ remote_url = f"https://x-access-token:{github_token}@github.com/{repository}.git"
+ else:
+ remote_url = f"https://github.com/{repository}.git"
update_remote = (
f"if [ -d {shlex.quote(repo_path + '/.git')} ]; then "
f"cd {shlex.quote(repo_path)} && "
- f"git remote set-url origin "
- f"https://x-access-token:{shlex.quote(github_token)}@github.com/{shlex.quote(repository)}.git; "
+ f"git remote set-url origin {shlex.quote(remote_url)}; "
f"fi"
)
result = sandbox.execute(update_remote, timeout_seconds=30)
@@ -73,56 +76,44 @@ def set_git_remote_token(sandbox: "SandboxBase", repository: str, github_token:
return True
-def update_sandbox_env_file(sandbox: "SandboxBase", updates: dict[str, str]) -> bool:
- """Replace specific keys in the NUL-delimited agentsh env file, preserving all other entries.
-
- 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
-
- read = sandbox.execute(f"base64 -w0 {shlex.quote(ENV_FILE)} 2>/dev/null || true", timeout_seconds=30)
- existing: bytes = b""
- if read.exit_code == 0 and read.stdout.strip():
- try:
- existing = base64.b64decode(read.stdout.strip())
- except Exception:
- logger.warning("Could not decode existing sandbox env file; rewriting only the updated keys")
- existing = b""
-
- ordered_keys: list[str] = []
- values: dict[str, bytes] = {}
- for entry in existing.split(b"\x00"):
- if not entry:
- continue
- key_bytes, _, value_bytes = entry.partition(b"=")
- key = key_bytes.decode("utf-8", "replace")
- if key not in values:
- ordered_keys.append(key)
- values[key] = value_bytes
-
- for key, value in updates.items():
- if key not in values:
- ordered_keys.append(key)
- values[key] = value.encode("utf-8")
-
- payload = b"".join(f"{key}=".encode() + values[key] + b"\x00" for key in ordered_keys)
- write = sandbox.write_file(ENV_FILE, payload)
+def _write_sandbox_credential_file(sandbox: "SandboxBase", path: str, payload: bytes) -> bool:
+ """Atomically replace one credential domain without a cross-key read-modify-write."""
+ write = sandbox.write_file(path, payload)
if write.exit_code != 0:
logger.warning(
- "Failed to refresh agentsh env file",
- extra={"sandbox_id": sandbox.id, "env_file": ENV_FILE, "stderr": write.stderr},
+ "Failed to refresh sandbox credential file",
+ extra={"sandbox_id": sandbox.id, "credential_file": path, "stderr": write.stderr},
+ )
+ return False
+
+ chmod = sandbox.execute(f"chmod 600 {shlex.quote(path)}", timeout_seconds=30)
+ if chmod.exit_code != 0:
+ logger.warning(
+ "Failed to restrict sandbox credential file permissions",
+ extra={"sandbox_id": sandbox.id, "credential_file": path, "stderr": chmod.stderr},
)
return False
return True
+def replace_sandbox_credentials(
+ sandbox: "SandboxBase", github_token: str | None, oauth_access_token: str | None
+) -> bool:
+ """Replace every managed credential, including empty values that revoke stale snapshot state."""
+ github_payload = b"".join(f"{key}={github_token}\x00".encode() for key in GITHUB_ENV_KEYS) if github_token else b""
+ oauth_payload = f"{OAUTH_ENV_KEY}={oauth_access_token}\x00".encode() if oauth_access_token else b""
+
+ github_updated = _write_sandbox_credential_file(sandbox, GITHUB_ENV_FILE, github_payload)
+ oauth_updated = _write_sandbox_credential_file(sandbox, OAUTH_ENV_FILE, oauth_payload)
+ return github_updated and oauth_updated
+
+
def apply_github_credentials_to_sandbox(sandbox: "SandboxBase", repository: str | None, github_token: str) -> None:
"""Re-inject a GitHub token into both places a running sandbox reads it from."""
if repository:
set_git_remote_token(sandbox, repository, github_token)
- update_sandbox_env_file(sandbox, dict.fromkeys(GITHUB_ENV_KEYS, github_token))
+ github_payload = b"".join(f"{key}={github_token}\x00".encode() for key in GITHUB_ENV_KEYS)
+ _write_sandbox_credential_file(sandbox, GITHUB_ENV_FILE, github_payload)
USER_TOKEN_REFRESH_INTERVAL_SECONDS: float = _GITHUB_REFRESH_INTERVAL_BY_PREFIX["ghu_"]
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 014fd645ff43..87a68d11dcb0 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
@@ -1,8 +1,7 @@
-import base64
-
import pytest
from unittest.mock import MagicMock, patch
+from products.tasks.backend.logic.services.agentsh import GITHUB_ENV_FILE, OAUTH_ENV_FILE
from products.tasks.backend.logic.services.sandbox import ExecutionResult
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.sandbox_credentials import (
@@ -10,8 +9,8 @@ from products.tasks.backend.temporal.process_task.sandbox_credentials import (
GitHubSandboxCredential,
build_sandbox_credentials,
github_refresh_interval_seconds,
+ replace_sandbox_credentials,
set_git_remote_token,
- update_sandbox_env_file,
)
@@ -60,6 +59,16 @@ class TestSetGitRemoteToken:
assert "x-access-token:ghs_new" in command
assert "explore-science/paper-wizard-frontend" in command
+ def test_removes_stale_token_when_current_credential_is_missing(self):
+ sandbox = MagicMock()
+ sandbox.execute.return_value = _ok()
+
+ assert set_git_remote_token(sandbox, "owner/repo", None) is True
+
+ command = sandbox.execute.call_args[0][0]
+ assert "https://github.com/owner/repo.git" in command
+ assert "x-access-token" not in command
+
def test_returns_false_on_failure(self):
sandbox = MagicMock()
sandbox.execute.return_value = ExecutionResult(stdout="", stderr="not a git repo", exit_code=128)
@@ -67,39 +76,38 @@ class TestSetGitRemoteToken:
assert set_git_remote_token(sandbox, "owner/repo", "ghs_new") is False
-class TestUpdateSandboxEnvFile:
- def test_preserves_other_keys_and_replaces_updated_ones(self):
+class TestReplaceSandboxCredentials:
+ def test_replaces_each_credential_domain_without_reading_existing_state(self):
sandbox = MagicMock()
- existing = b"PATH=/usr/bin\x00GITHUB_TOKEN=ghs_old\x00HOME=/root\x00"
- sandbox.execute.return_value = _ok(base64.b64encode(existing).decode())
+ sandbox.execute.return_value = _ok()
sandbox.write_file.return_value = _ok()
- assert update_sandbox_env_file(sandbox, {"GITHUB_TOKEN": "ghs_new", "GH_TOKEN": "ghs_new"}) is True
+ assert replace_sandbox_credentials(sandbox, "ghs_new", "oauth_new") is True
- _, payload = sandbox.write_file.call_args[0]
- entries = {e.split(b"=", 1)[0]: e.split(b"=", 1)[1] for e in payload.split(b"\x00") if e}
- # Untouched keys survive, updated key is replaced, new key is appended.
- assert entries[b"PATH"] == b"/usr/bin"
- assert entries[b"HOME"] == b"/root"
- assert entries[b"GITHUB_TOKEN"] == b"ghs_new"
- assert entries[b"GH_TOKEN"] == b"ghs_new"
-
- def test_noop_when_no_updates(self):
- sandbox = MagicMock()
- assert update_sandbox_env_file(sandbox, {}) is True
- sandbox.execute.assert_not_called()
- sandbox.write_file.assert_not_called()
+ assert sandbox.write_file.call_args_list[0].args == (
+ GITHUB_ENV_FILE,
+ b"GITHUB_TOKEN=ghs_new\x00GH_TOKEN=ghs_new\x00",
+ )
+ assert sandbox.write_file.call_args_list[1].args == (
+ OAUTH_ENV_FILE,
+ b"POSTHOG_PERSONAL_API_KEY=oauth_new\x00",
+ )
+ assert [call.args[0] for call in sandbox.execute.call_args_list] == [
+ f"chmod 600 {GITHUB_ENV_FILE}",
+ f"chmod 600 {OAUTH_ENV_FILE}",
+ ]
- def test_writes_updates_when_env_file_absent(self):
+ def test_empty_current_credentials_clear_both_files(self):
sandbox = MagicMock()
- # base64 of empty file (the `|| true` path yields empty stdout).
- sandbox.execute.return_value = _ok("")
+ sandbox.execute.return_value = _ok()
sandbox.write_file.return_value = _ok()
- assert update_sandbox_env_file(sandbox, {"GH_TOKEN": "ghs_new"}) is True
+ assert replace_sandbox_credentials(sandbox, None, None) is True
- _, payload = sandbox.write_file.call_args[0]
- assert payload == b"GH_TOKEN=ghs_new\x00"
+ assert [call.args for call in sandbox.write_file.call_args_list] == [
+ (GITHUB_ENV_FILE, b""),
+ (OAUTH_ENV_FILE, b""),
+ ]
class TestGitHubSandboxCredential:
diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.py
index fb8423b08d05..d7e4d8524f14 100644
--- a/products/tasks/backend/tests/test_agentsh.py
+++ b/products/tasks/backend/tests/test_agentsh.py
@@ -1,9 +1,13 @@
+import os
import shlex
+import tempfile
+import subprocess
+from pathlib import Path
from typing import Any
from unittest.mock import Mock
-from django.test import TestCase, override_settings
+from django.test import SimpleTestCase, TestCase, override_settings
import yaml
from parameterized import parameterized
@@ -14,6 +18,7 @@ from products.tasks.backend.logic.services.agentsh import (
INFRASTRUCTURE_DOMAINS,
build_audit_query_command,
build_exec_prefix,
+ generate_bash_env_script,
generate_config_yaml,
generate_env_wrapper,
generate_policy_yaml,
@@ -227,14 +232,36 @@ class TestGeneratePolicyYaml(TestCase):
self.assertNotIn("deny-cloud-metadata", rule_names)
-class TestEnvWrapper(TestCase):
- def test_wrapper_restores_environment_dump(self):
- wrapper = generate_env_wrapper()
- self.assertIn("done < /tmp/agent-env", wrapper)
-
- def test_wrapper_execs_command(self):
- wrapper = generate_env_wrapper()
- self.assertIn('exec "$@"', wrapper)
+class TestEnvWrapper(SimpleTestCase):
+ def test_restores_safe_environment_and_only_managed_credentials(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ env_file = Path(temp_dir) / "agent env"
+ github_env_file = Path(temp_dir) / "github env"
+ oauth_env_file = Path(temp_dir) / "oauth env"
+ wrapper_file = Path(temp_dir) / "wrapper.sh"
+ env_file.write_bytes(
+ b"SAFE_BASE=kept\x00NODE_OPTIONS=--require=/tmp/payload.js\x00GITHUB_TOKEN=ghs_snapshot\x00"
+ )
+ github_env_file.write_bytes(b"GITHUB_TOKEN=ghs_fresh\x00GH_TOKEN=ghs_fresh\x00IGNORED=unsafe\x00")
+ oauth_env_file.write_bytes(b"POSTHOG_PERSONAL_API_KEY=oauth_fresh\x00IGNORED=unsafe\x00")
+ wrapper_file.write_text(generate_env_wrapper(str(env_file), str(github_env_file), str(oauth_env_file)))
+
+ result = subprocess.run(
+ [
+ "bash",
+ str(wrapper_file),
+ "bash",
+ "-c",
+ 'printf "%s|%s|%s|%s|%s" "$SAFE_BASE" "$GH_TOKEN" "$GITHUB_TOKEN" '
+ '"$POSTHOG_PERSONAL_API_KEY" "${NODE_OPTIONS:-}"',
+ ],
+ check=True,
+ capture_output=True,
+ text=True,
+ env={"PATH": os.environ["PATH"], "NODE_OPTIONS": "--require=/tmp/inherited.js"},
+ )
+
+ self.assertEqual(result.stdout, "kept|ghs_fresh|ghs_fresh|oauth_fresh|")
def test_wrapper_does_not_set_proxy_vars(self):
wrapper = generate_env_wrapper()
@@ -243,6 +270,100 @@ class TestEnvWrapper(TestCase):
self.assertNotIn("--use-env-proxy", wrapper)
+class TestBashEnvScript(SimpleTestCase):
+ def test_initialization_replaces_snapshot_env_and_preserves_refreshed_credentials(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ env_file = Path(temp_dir) / "agent env"
+ github_env_file = Path(temp_dir) / "github env"
+ oauth_env_file = Path(temp_dir) / "oauth env"
+ script_file = Path(temp_dir) / "bash env.sh"
+ env_file.write_bytes(
+ b"PATH=/snapshot\x00NODE_OPTIONS=--require=/tmp/payload.js\x00GITHUB_TOKEN=ghu_snapshot\x00"
+ )
+ github_env_file.write_bytes(b"GH_TOKEN=ghu_fresh\x00GITHUB_TOKEN=ghu_fresh\x00")
+ oauth_env_file.write_bytes(b"POSTHOG_PERSONAL_API_KEY=oauth_fresh\x00")
+ script_file.write_text(generate_bash_env_script(str(env_file), str(github_env_file), str(oauth_env_file)))
+
+ subprocess.run(
+ ["bash", str(script_file)],
+ check=True,
+ env={
+ "PATH": os.environ["PATH"],
+ "SAFE_BASE": "kept",
+ "GH_TOKEN": "ghu_process",
+ "POSTHOG_PERSONAL_API_KEY": "oauth_process",
+ "NODE_OPTIONS": "--require=/tmp/current.js",
+ },
+ )
+
+ entries = {
+ entry.split(b"=", 1)[0]: entry.split(b"=", 1)[1]
+ for entry in env_file.read_bytes().split(b"\x00")
+ if entry
+ }
+ self.assertEqual(entries[b"SAFE_BASE"], b"kept")
+ self.assertNotIn(b"NODE_OPTIONS", entries)
+ self.assertNotIn(b"GITHUB_TOKEN", entries)
+ self.assertNotIn(b"POSTHOG_PERSONAL_API_KEY", entries)
+ self.assertEqual(github_env_file.read_bytes(), b"GH_TOKEN=ghu_fresh\x00GITHUB_TOKEN=ghu_fresh\x00")
+ self.assertEqual(oauth_env_file.read_bytes(), b"POSTHOG_PERSONAL_API_KEY=oauth_fresh\x00")
+ for path in (env_file, github_env_file, oauth_env_file):
+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)
+
+ sourced = subprocess.run(
+ ["bash", "-c", 'printf "%s|%s" "$GH_TOKEN" "$GITHUB_TOKEN"'],
+ check=True,
+ capture_output=True,
+ text=True,
+ env={"PATH": os.environ["PATH"], "BASH_ENV": str(script_file)},
+ )
+ self.assertEqual(sourced.stdout, "ghu_fresh|ghu_fresh")
+
+ def test_initialization_creates_restrictive_credential_files_when_missing(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ env_file = Path(temp_dir) / "agent env"
+ github_env_file = Path(temp_dir) / "github env"
+ oauth_env_file = Path(temp_dir) / "oauth env"
+ script_file = Path(temp_dir) / "bash env.sh"
+ script_file.write_text(generate_bash_env_script(str(env_file), str(github_env_file), str(oauth_env_file)))
+
+ subprocess.run(
+ ["bash", str(script_file)],
+ check=True,
+ env={
+ "PATH": os.environ["PATH"],
+ "SAFE_BASE": "kept",
+ "GITHUB_TOKEN": "ghs_current",
+ "POSTHOG_PERSONAL_API_KEY": "oauth_current",
+ },
+ )
+
+ self.assertEqual(
+ github_env_file.read_bytes(),
+ b"GITHUB_TOKEN=ghs_current\x00GH_TOKEN=ghs_current\x00",
+ )
+ self.assertEqual(oauth_env_file.read_bytes(), b"POSTHOG_PERSONAL_API_KEY=oauth_current\x00")
+ for path in (env_file, github_env_file, oauth_env_file):
+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)
+
+ def test_initialization_fails_for_untrusted_credential_file_type(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ env_file = Path(temp_dir) / "agent env"
+ github_env_file = Path(temp_dir) / "github env"
+ oauth_env_file = Path(temp_dir) / "oauth env"
+ script_file = Path(temp_dir) / "bash env.sh"
+ github_env_file.mkdir()
+ script_file.write_text(generate_bash_env_script(str(env_file), str(github_env_file), str(oauth_env_file)))
+
+ result = subprocess.run(
+ ["bash", str(script_file)],
+ check=False,
+ env={"PATH": os.environ["PATH"]},
+ )
+
+ self.assertNotEqual(result.returncode, 0)
+
+
class TestBuildAuditQueryCommand(TestCase):
def test_references_audit_db(self):
cmd = build_audit_query_command()
@@ -285,9 +406,7 @@ class TestModalSandboxAgentShWrapping(TestCase):
create_pr=True,
)
self.assertNotIn("agentsh exec --client-timeout 2h --timeout 2h", cmd)
- # The env file is written at launch regardless of agentsh so the
- # mid-session credential refresh can re-source the token per command.
- self.assertIn("env -0 > /tmp/agent-env", cmd)
+ self.assertIn("bash /tmp/agentsh-bash-env.sh", cmd)
self.assertNotIn(ENV_WRAPPER_SCRIPT, cmd)
self.assertIn("nohup", cmd)
@@ -388,7 +507,7 @@ class TestModalSandboxAgentShWrapping(TestCase):
allowed_domains=["example.com", "api.example.com"],
)
self.assertIn("agentsh exec --client-timeout 2h --timeout 2h", cmd)
- self.assertIn("env -0 > /tmp/agent-env", cmd)
+ self.assertIn("bash /tmp/agentsh-bash-env.sh", cmd)
self.assertIn(ENV_WRAPPER_SCRIPT, cmd)
self.assertIn("--allowedDomains", cmd)
self.assertIn("example.com,api.example.com", cmd)