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): block process-control env vars in sandbox environments (#66262)

Alessandro Pogliaghi2992cdcbf6a2
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index 7696e53af8db..c6374bb0a540 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -205,6 +205,63 @@ DEFAULT_TRUSTED_DOMAINS = [
"www.schemastore.org",
]
+RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS: frozenset[str] = frozenset(
+ {
+ "POSTHOG_PERSONAL_API_KEY",
+ "POSTHOG_API_URL",
+ "POSTHOG_PROJECT_ID",
+ "JWT_PUBLIC_KEY",
+ "GITHUB_TOKEN",
+ "GH_TOKEN",
+ "LLM_GATEWAY_URL",
+ "POSTHOG_RESUME_RUN_ID",
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
+ "DISABLE_TELEMETRY",
+ "DISABLE_ERROR_REPORTING",
+ }
+)
+
+BLOCKED_SANDBOX_ENVIRONMENT_VARIABLE_PREFIXES: tuple[str, ...] = ("LD_", "DYLD_", "GIT_")
+BLOCKED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS: frozenset[str] = frozenset(
+ {
+ "NODE_OPTIONS",
+ "NODE_REPL_EXTERNAL_MODULE",
+ "BASH_ENV",
+ "PROMPT_COMMAND",
+ "PYTHONSTARTUP",
+ "PERL5OPT",
+ "RUBYOPT",
+ }
+)
+
+SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS: tuple[str, ...] = (
+ "NODE_OPTIONS",
+ "NODE_REPL_EXTERNAL_MODULE",
+ "LD_PRELOAD",
+ "LD_LIBRARY_PATH",
+ "LD_AUDIT",
+ "DYLD_INSERT_LIBRARIES",
+ "DYLD_LIBRARY_PATH",
+)
+
+
+def is_blocked_sandbox_env_key(key: str) -> bool:
+ if key in BLOCKED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS:
+ return True
+ return any(key.startswith(prefix) for prefix in BLOCKED_SANDBOX_ENVIRONMENT_VARIABLE_PREFIXES)
+
+
+def filter_user_sandbox_env_vars(env_vars: dict[str, str]) -> tuple[dict[str, str], list[str]]:
+ safe: dict[str, str] = {}
+ skipped: list[str] = []
+ for key, value in env_vars.items():
+ if key in RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS or is_blocked_sandbox_env_key(key):
+ skipped.append(key)
+ continue
+ safe[key] = value
+ return safe, skipped
+
+
SETUP_REPOSITORY_PROMPT = """
Your goal is to setup the repository in the current environment.
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 02680e68ee98..69078f611718 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -32,6 +32,7 @@ from posthog.event_usage import groups
from posthog.models import User
from posthog.models.integration import Integration
+from products.tasks.backend.constants import RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS, is_blocked_sandbox_env_key
from products.tasks.backend.logic.code_workstreams.default_workflow import build_default_bindings
from products.tasks.backend.logic.code_workstreams.validation import validate_bindings
from products.tasks.backend.models import (
@@ -827,6 +828,22 @@ def is_valid_sandbox_env_var_key(key: str) -> bool:
return SandboxEnvironment.is_valid_env_var_key(key)
+def is_blocked_sandbox_env_var_key(key: str) -> bool:
+ return is_blocked_sandbox_env_key(key)
+
+
+def is_reserved_sandbox_env_var_key(key: str) -> bool:
+ return key in RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS
+
+
+def _validate_user_sandbox_env_vars(environment_variables: dict | None) -> None:
+ for key in environment_variables or {}:
+ if not SandboxEnvironment.is_valid_env_var_key(key):
+ raise ValueError(f"Invalid environment variable key: {key!r}")
+ if is_blocked_sandbox_env_key(key) or key in RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS:
+ raise ValueError(f"Environment variable key {key!r} is not allowed")
+
+
def _accessible_sandbox_envs(team_id: int, user_id: int):
return (
SandboxEnvironment.objects.filter(team_id=team_id)
@@ -859,6 +876,7 @@ def create_sandbox_environment(
private: bool,
) -> contracts.SandboxEnvironmentDTO:
"""Create a team environment owned by the user and return it as a DTO."""
+ _validate_user_sandbox_env_vars(environment_variables)
env = SandboxEnvironment.objects.create(
team_id=team_id,
created_by_id=user_id,
@@ -880,6 +898,8 @@ def update_sandbox_environment(
env = _accessible_sandbox_envs(team_id, user_id).filter(pk=env_id).first()
if env is None:
return None
+ if "environment_variables" in fields:
+ _validate_user_sandbox_env_vars(fields["environment_variables"])
for key, value in fields.items():
setattr(env, key, value)
env.save()
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index 894c64c75296..4dfef464d780 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -18,6 +18,7 @@ from django.conf import settings
if TYPE_CHECKING:
from products.tasks.backend.temporal.process_task.utils import McpServerConfig
+from products.tasks.backend.constants import SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS
from products.tasks.backend.exceptions import (
SandboxCleanupError,
SandboxExecutionError,
@@ -742,8 +743,9 @@ class DockerSandbox(SandboxBase):
# agent's per-command tool shells re-source the refreshed token. Backend maintenance
# execs (clone/checkout/token injection) must not source it — the script could be
# persisted in a resume snapshot, so sourcing it from a backend exec is a trust hole.
+ unset_flags = "".join(f"-u {name} " for name in SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS)
server_cmd = (
- f"env BASH_ENV={shlex.quote(BASH_ENV_SCRIPT)} "
+ f"env {unset_flags}BASH_ENV={shlex.quote(BASH_ENV_SCRIPT)} "
f"{env_prefix}./node_modules/.bin/agent-server --port {AGENT_SERVER_PORT}{repo_flag} "
f"--taskId {shlex.quote(task_id)} --runId {shlex.quote(run_id)} --mode {shlex.quote(mode)}"
f"{create_pr_flag}{branch_flag}{mcp_servers_arg}{domains_flag}"
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 0794ec097733..78dfef7b56a4 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -32,6 +32,7 @@ from modal.exception import (
from posthog.exceptions_capture import capture_exception
from posthog.settings import CLOUD_DEPLOYMENT
+from products.tasks.backend.constants import SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS
from products.tasks.backend.exceptions import (
SandboxCleanupError,
SandboxExecutionError,
@@ -710,8 +711,9 @@ class ModalSandbox(SandboxBase):
# agent's per-command tool shells re-source the refreshed token. Backend maintenance
# execs (clone/checkout/token injection) must not source it — the script could be
# persisted in a resume snapshot, so sourcing it from a backend exec is a trust hole.
+ unset_flags = "".join(f"-u {name} " for name in SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS)
server_cmd = (
- f"env BASH_ENV={shlex.quote(BASH_ENV_SCRIPT)} "
+ f"env {unset_flags}BASH_ENV={shlex.quote(BASH_ENV_SCRIPT)} "
f"{env_prefix}./node_modules/.bin/agent-server --port {AGENT_SERVER_PORT}{repo_flag} "
f"--taskId {shlex.quote(task_id)} --runId {shlex.quote(run_id)} --mode {shlex.quote(mode)}"
f"{create_pr_flag}{branch_flag}{mcp_servers_arg}{domains_flag}"
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 8b95516d6383..7eef5208edd0 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -1715,6 +1715,15 @@ class SandboxEnvironmentWriteSerializer(serializers.Serializer):
raise serializers.ValidationError(
f"Invalid environment variable key: {key!r}. Must match [A-Za-z_][A-Za-z0-9_]*"
)
+ if tasks_facade.is_blocked_sandbox_env_var_key(key):
+ raise serializers.ValidationError(
+ f"Environment variable key {key!r} is not allowed: it can change how sandbox "
+ "processes execute code (e.g. NODE_OPTIONS, LD_PRELOAD)."
+ )
+ if tasks_facade.is_reserved_sandbox_env_var_key(key):
+ raise serializers.ValidationError(
+ f"Environment variable key {key!r} is reserved and managed by PostHog; it cannot be set."
+ )
return value
diff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
index 03de15981ad5..75c0ed187c3e 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
@@ -8,6 +8,7 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
+from products.tasks.backend.constants import filter_user_sandbox_env_vars
from products.tasks.backend.exceptions import GitHubAuthenticationError, OAuthTokenError, TaskNotFoundError
from products.tasks.backend.logic.services.connection_token import (
SANDBOX_JWT_STATE_KID_KEY,
@@ -36,17 +37,6 @@ from .get_task_processing_context import TaskProcessingContext
logger = logging.getLogger(__name__)
-RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS = {
- "POSTHOG_PERSONAL_API_KEY",
- "POSTHOG_API_URL",
- "POSTHOG_PROJECT_ID",
- "JWT_PUBLIC_KEY",
- "GITHUB_TOKEN",
- "GH_TOKEN",
- "LLM_GATEWAY_URL",
- "POSTHOG_RESUME_RUN_ID",
-}
-
def _get_image_source_label(
*,
@@ -186,25 +176,19 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo
if ctx.sandbox_environment_id:
sandbox_environment = ctx.get_sandbox_environment()
if sandbox_environment and sandbox_environment.environment_variables:
- skipped_keys: list[str] = []
- added_keys = 0
- for key, value in sandbox_environment.environment_variables.items():
- if key in RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS:
- skipped_keys.append(key)
- continue
- environment_variables[key] = value
- added_keys += 1
+ safe_vars, skipped_keys = filter_user_sandbox_env_vars(sandbox_environment.environment_variables)
+ environment_variables.update(safe_vars)
emit_agent_log(
ctx.run_id,
"debug",
- f"Applied {added_keys} sandbox environment variable(s) from '{sandbox_environment.name}'",
+ f"Applied {len(safe_vars)} sandbox environment variable(s) from '{sandbox_environment.name}'",
)
if skipped_keys:
emit_agent_log(
ctx.run_id,
"debug",
- f"Skipped reserved sandbox environment variable keys from '{sandbox_environment.name}': {', '.join(sorted(skipped_keys))}",
+ f"Skipped reserved/blocked sandbox environment variable keys from '{sandbox_environment.name}': {', '.join(sorted(skipped_keys))}",
)
if github_token:
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 3fb6258dd8e6..adff0aef64b7 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -8,6 +8,7 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
+from products.tasks.backend.constants import 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.connection_token import (
@@ -33,21 +34,6 @@ from .get_task_processing_context import TaskProcessingContext
logger = logging.getLogger(__name__)
-RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS = {
- "POSTHOG_PERSONAL_API_KEY",
- "POSTHOG_API_URL",
- "POSTHOG_PROJECT_ID",
- "JWT_PUBLIC_KEY",
- "GITHUB_TOKEN",
- "GH_TOKEN",
- "LLM_GATEWAY_URL",
- "POSTHOG_RESUME_RUN_ID",
- "BASH_ENV",
- "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
- "DISABLE_TELEMETRY",
- "DISABLE_ERROR_REPORTING",
-}
-
NETWORK_RESTRICTED_AGENT_ENV = {
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
"DISABLE_TELEMETRY": "1",
@@ -204,25 +190,19 @@ def _build_environment_variables(
if ctx.sandbox_environment_id:
sandbox_environment = ctx.get_sandbox_environment()
if sandbox_environment and sandbox_environment.environment_variables:
- skipped_keys: list[str] = []
- added_keys = 0
- for key, value in sandbox_environment.environment_variables.items():
- if key in RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS:
- skipped_keys.append(key)
- continue
- environment_variables[key] = value
- added_keys += 1
+ safe_vars, skipped_keys = filter_user_sandbox_env_vars(sandbox_environment.environment_variables)
+ environment_variables.update(safe_vars)
emit_agent_log(
ctx.run_id,
"debug",
- f"Applied {added_keys} sandbox environment variable(s) from '{sandbox_environment.name}'",
+ f"Applied {len(safe_vars)} sandbox environment variable(s) from '{sandbox_environment.name}'",
)
if skipped_keys:
emit_agent_log(
ctx.run_id,
"debug",
- f"Skipped reserved sandbox environment variable keys from '{sandbox_environment.name}': {', '.join(sorted(skipped_keys))}",
+ f"Skipped reserved/blocked sandbox environment variable keys from '{sandbox_environment.name}': {', '.join(sorted(skipped_keys))}",
)
if github_token:
@@ -230,9 +210,9 @@ def _build_environment_variables(
environment_variables["GH_TOKEN"] = github_token
# BASH_ENV is intentionally NOT set in the container env: it's applied only to the
- # agent-server launch (see `_build_agent_server_command`) so backend maintenance execs
- # don't source a script that a resume snapshot could control. It stays in
- # RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS so a user-supplied env var can't add it here.
+ # agent-server launch (see the sandbox services) so backend maintenance execs don't source
+ # a script that a resume snapshot could control. It's blocked (constants.py) so a
+ # user-supplied env var can't add it here.
if settings.SANDBOX_LLM_GATEWAY_URL:
environment_variables["LLM_GATEWAY_URL"] = settings.SANDBOX_LLM_GATEWAY_URL
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 8aebfa275aeb..84fb5ac95810 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -15,7 +15,7 @@ from posthog.models.user_integration import ReauthorizationRequired, UserGitHubI
from posthog.temporal.oauth import TOKEN_EXPIRATION_SECONDS, PosthogMcpScopes, has_write_scopes
from products.mcp_store.backend.facade.api import get_active_installations
-from products.tasks.backend.constants import InitialPermissionMode
+from products.tasks.backend.constants import InitialPermissionMode, filter_user_sandbox_env_vars
from products.tasks.backend.redis import get_tasks_cache
if TYPE_CHECKING:
@@ -689,7 +689,8 @@ def build_sandbox_environment_variables(
env_vars: dict[str, str] = {}
if sandbox_environment and sandbox_environment.environment_variables:
- env_vars.update(sandbox_environment.environment_variables)
+ safe_vars, _ = filter_user_sandbox_env_vars(sandbox_environment.environment_variables)
+ env_vars.update(safe_vars)
if github_token:
env_vars["GITHUB_TOKEN"] = github_token
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 84132c7c0149..eae45f61a6ba 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -7159,6 +7159,49 @@ class TestSandboxEnvironmentAPI(BaseTaskAPITest):
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ @parameterized.expand(
+ [
+ ("NODE_OPTIONS",),
+ ("LD_PRELOAD",),
+ ("LD_LIBRARY_PATH",),
+ ("DYLD_INSERT_LIBRARIES",),
+ ("BASH_ENV",),
+ ("GIT_SSH_COMMAND",),
+ ("GIT_CONFIG_KEY_0",),
+ ("GIT_CONFIG_VALUE_0",),
+ ]
+ )
+ def test_blocked_process_control_env_var_key_rejected(self, key):
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Dangerous Env Vars",
+ "network_access_level": "full",
+ "environment_variables": {key: "value"},
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ @parameterized.expand(
+ [
+ ("GITHUB_TOKEN",),
+ ("POSTHOG_PERSONAL_API_KEY",),
+ ("JWT_PUBLIC_KEY",),
+ ]
+ )
+ def test_reserved_env_var_key_rejected(self, key):
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Reserved Env Vars",
+ "network_access_level": "full",
+ "environment_variables": {key: "value"},
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
def test_environment_variables_never_returned(self):
response = self.client.post(
self.base_url,
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index 9e6c0495a9b1..c75abd490956 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -1361,6 +1361,43 @@ class TestSandboxEnvironment(TestCase):
def test_is_valid_env_var_key(self, key, expected_valid):
self.assertEqual(SandboxEnvironment.is_valid_env_var_key(key), expected_valid)
+ @parameterized.expand(
+ [
+ ("NODE_OPTIONS", True),
+ ("NODE_REPL_EXTERNAL_MODULE", True),
+ ("LD_PRELOAD", True),
+ ("LD_LIBRARY_PATH", True),
+ ("DYLD_INSERT_LIBRARIES", True),
+ ("BASH_ENV", True),
+ ("GIT_SSH_COMMAND", True),
+ ("GIT_CONFIG_KEY_0", True),
+ ("GIT_CONFIG_VALUE_0", True),
+ ("NODE_ENV", False),
+ ("node_options", False),
+ ("MY_API_KEY", False),
+ ("LDAP_URL", False),
+ ("GITHUB_ACTOR", False),
+ ]
+ )
+ def test_is_blocked_sandbox_env_key(self, key, expected_blocked):
+ from products.tasks.backend.constants import is_blocked_sandbox_env_key
+
+ self.assertEqual(is_blocked_sandbox_env_key(key), expected_blocked)
+
+ def test_filter_user_sandbox_env_vars_drops_reserved_and_blocked(self):
+ from products.tasks.backend.constants import filter_user_sandbox_env_vars
+
+ safe, skipped = filter_user_sandbox_env_vars(
+ {
+ "SAFE_VAR": "ok",
+ "NODE_OPTIONS": "--import=evil",
+ "LD_PRELOAD": "/tmp/evil.so",
+ "GITHUB_TOKEN": "stolen",
+ }
+ )
+ self.assertEqual(safe, {"SAFE_VAR": "ok"})
+ self.assertEqual(sorted(skipped), ["GITHUB_TOKEN", "LD_PRELOAD", "NODE_OPTIONS"])
+
@parameterized.expand(
[
(SandboxEnvironment.NetworkAccessLevel.FULL, [], False, []),