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): enforce sandbox egress via Modal domain allowlist (#62897)

Alessandro Pogliaghib2ff2898bed8
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index 7d8abc0ced15..4e63cb776168 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -2,6 +2,7 @@ from typing import Literal, get_args
SANDBOX_EVENT_INGEST_FEATURE_FLAG = "tasks-cloud-runs-sandbox-event-ingest"
MODAL_VM_SANDBOX_FEATURE_FLAG = "tasks-modal-vm-sandbox"
+MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG = "tasks-modal-network-allowlist"
ClaudePermissionMode = Literal["default", "acceptEdits", "plan", "bypassPermissions", "auto"]
CodexPermissionMode = Literal["auto", "read-only", "full-access"]
diff --git a/products/tasks/backend/services/modal_sandbox.py b/products/tasks/backend/services/modal_sandbox.py
index 289016d8aa8d..f4f88bfa788c 100644
--- a/products/tasks/backend/services/modal_sandbox.py
+++ b/products/tasks/backend/services/modal_sandbox.py
@@ -363,6 +363,9 @@ class ModalSandbox(SandboxBase):
if config.vm_runtime or config.template == SandboxTemplate.VM_BASE:
create_kwargs["experimental_options"] = {"vm_runtime": True}
+ if config.outbound_domain_allowlist:
+ create_kwargs["outbound_domain_allowlist"] = config.outbound_domain_allowlist
+
if secrets:
create_kwargs["secrets"] = secrets
@@ -805,7 +808,8 @@ class ModalSandbox(SandboxBase):
try:
# Modal can report the sandbox as running before filesystem snapshotting is ready.
self._sandbox.exec("true", timeout=30).wait()
- image = self._sandbox.snapshot_filesystem()
+ # ttl=None keeps indefinite retention; modal 1.5.0 otherwise defaults snapshots to a 30-day TTL.
+ image = self._sandbox.snapshot_filesystem(ttl=None)
snapshot_id = image.object_id
diff --git a/products/tasks/backend/services/sandbox.py b/products/tasks/backend/services/sandbox.py
index 6762c404c245..6b9b7378fcb6 100644
--- a/products/tasks/backend/services/sandbox.py
+++ b/products/tasks/backend/services/sandbox.py
@@ -78,6 +78,8 @@ class SandboxConfig(BaseModel):
cpu_cores: float = 4
disk_size_gb: float = 64
vm_runtime: bool = False
+ # gVisor only — Modal rejects this under vm_runtime.
+ outbound_domain_allowlist: list[str] | None = None
WORKING_DIR = "/tmp/workspace"
diff --git a/products/tasks/backend/services/tests/test_modal_sandbox.py b/products/tasks/backend/services/tests/test_modal_sandbox.py
index 704d27d85ab6..647b570b0acc 100644
--- a/products/tasks/backend/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/services/tests/test_modal_sandbox.py
@@ -530,7 +530,7 @@ class TestModalSandboxAgentServer:
image = MagicMock()
image.object_id = "snapshot-123"
- def snapshot_filesystem() -> Any:
+ def snapshot_filesystem(ttl: Any = None) -> Any:
events.append("snapshot")
return image
@@ -542,7 +542,7 @@ class TestModalSandboxAgentServer:
assert result == "snapshot-123"
mock_sandbox._sandbox.exec.assert_called_once_with("true", timeout=30)
exec_process.wait.assert_called_once_with()
- mock_sandbox._sandbox.snapshot_filesystem.assert_called_once_with()
+ mock_sandbox._sandbox.snapshot_filesystem.assert_called_once_with(ttl=None)
assert events == ["wait", "snapshot"]
diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.py
index b397e22baad8..a7f654dec5f6 100644
--- a/products/tasks/backend/temporal/metrics.py
+++ b/products/tasks/backend/temporal/metrics.py
@@ -67,6 +67,18 @@ def increment_credential_refresh(kind: str, outcome: str) -> None:
pass
+def increment_sandbox_created(runtime: str) -> None:
+ """Record a sandbox creation, labeled by runtime ("vm" or "gvisor")."""
+ try:
+ meter = _metric_meter({"runtime": runtime})
+ meter.create_counter(
+ "tasks_process_sandbox_created",
+ "Sandboxes created for process-task runs by runtime",
+ ).add(1)
+ except Exception:
+ pass
+
+
class StepTimer:
def __init__(self, step: str, used_snapshot: bool | None = None) -> None:
self.step = step
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index 9d054d0d32c9..8d9c2c588e58 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -9,7 +9,11 @@ from temporalio import activity
from posthog.models import Team
from posthog.temporal.common.utils import asyncify, close_db_connections
-from products.tasks.backend.constants import MODAL_VM_SANDBOX_FEATURE_FLAG, SANDBOX_EVENT_INGEST_FEATURE_FLAG
+from products.tasks.backend.constants import (
+ MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG,
+ MODAL_VM_SANDBOX_FEATURE_FLAG,
+ SANDBOX_EVENT_INGEST_FEATURE_FLAG,
+)
from products.tasks.backend.exceptions import TaskInvalidStateError, TaskNotFoundError
from products.tasks.backend.models import SandboxEnvironment, Task, TaskRun
from products.tasks.backend.temporal.observability import emit_agent_log, log_with_activity_context
@@ -60,6 +64,7 @@ class TaskProcessingContext:
# deterministic for the full run.
sandbox_event_ingest_enabled: bool = False
use_modal_vm_sandbox: bool = False
+ use_modal_network_allowlist: bool = False
@property
def mode(self) -> str:
@@ -220,6 +225,45 @@ def _is_modal_vm_sandbox_enabled(
return enabled
+def _is_modal_network_allowlist_enabled(
+ *,
+ distinct_id: str,
+ organization_id: str,
+ run_id: str,
+ state: dict | None = None,
+) -> bool:
+ state_override = (state or {}).get("use_modal_network_allowlist")
+ if isinstance(state_override, bool):
+ log_with_activity_context(
+ "modal_network_allowlist_state_override",
+ run_id=run_id,
+ use_modal_network_allowlist=state_override,
+ )
+ return state_override
+
+ try:
+ enabled = bool(
+ posthoganalytics.feature_enabled(
+ MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG,
+ distinct_id=distinct_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ log_with_activity_context("modal_network_allowlist_flag_check_failed", run_id=run_id, error=str(e))
+ return False
+
+ log_with_activity_context(
+ "modal_network_allowlist_flag_checked",
+ run_id=run_id,
+ use_modal_network_allowlist=enabled,
+ )
+ return enabled
+
+
@activity.defn
@asyncify
@close_db_connections
@@ -331,6 +375,17 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
"debug",
f"use_modal_vm_sandbox: {use_modal_vm_sandbox} for this task run",
)
+ use_modal_network_allowlist = _is_modal_network_allowlist_enabled(
+ distinct_id=distinct_id,
+ organization_id=organization_id,
+ run_id=run_id,
+ state=state,
+ )
+ emit_agent_log(
+ run_id,
+ "debug",
+ f"use_modal_network_allowlist: {use_modal_network_allowlist} for this task run",
+ )
user_github_integration_id = str(task.github_user_integration_id) if task.github_user_integration_id else None
if user_github_integration_id is None and get_pr_authorship_mode(task, state).value == "user":
user_github_integration = resolve_user_github_integration_for_task(task, allow_refresh=False)
@@ -361,4 +416,5 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
use_modal_resume_snapshots=settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS,
sandbox_event_ingest_enabled=sandbox_event_ingest_enabled,
use_modal_vm_sandbox=use_modal_vm_sandbox,
+ use_modal_network_allowlist=use_modal_network_allowlist,
)
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 048116dde65e..b70e94ecbde2 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -10,14 +10,14 @@ from posthog.temporal.common.utils import asyncify
from products.tasks.backend.exceptions import GitHubAuthenticationError, OAuthTokenError, TaskNotFoundError
from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
-from products.tasks.backend.services.agentsh import ENV_FILE
+from products.tasks.backend.services.agentsh import ENV_FILE, INFRASTRUCTURE_DOMAINS, _get_debug_only_domains
from products.tasks.backend.services.connection_token import (
SANDBOX_JWT_STATE_KID_KEY,
get_primary_sandbox_jwt_kid,
get_sandbox_jwt_public_key,
)
from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
-from products.tasks.backend.temporal.metrics import StepTimer, increment_snapshot_usage
+from products.tasks.backend.temporal.metrics import StepTimer, increment_sandbox_created, increment_snapshot_usage
from products.tasks.backend.temporal.oauth import create_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
@@ -107,6 +107,22 @@ class InjectFreshTokensOnResumeInput:
repository: str | None
+def _to_modal_domain_allowlist(allowed_domains: list[str]) -> list[str]:
+ """Translate the agentsh allowlist into Modal's outbound_domain_allowlist.
+
+ Modal fences the whole sandbox, so union in the infra (and local tunnel) domains
+ the agent needs, and drop loopback aliases Modal rejects as invalid domains.
+ """
+ domains = list(allowed_domains)
+ extra = list(INFRASTRUCTURE_DOMAINS)
+ if settings.DEBUG:
+ extra += _get_debug_only_domains()
+ for domain in extra:
+ if domain not in domains:
+ domains.append(domain)
+ return [d for d in domains if "." in d and d != "host.docker.internal"]
+
+
def _load_task(ctx: TaskProcessingContext) -> Task:
try:
return Task.objects.select_related("created_by", "github_integration", "github_user_integration").get(
@@ -366,9 +382,20 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cre
vm_runtime=use_vm_sandbox,
)
+ # gVisor only — Modal's domain allowlist breaks vm_runtime.
+ if ctx.use_modal_network_allowlist and not use_vm_sandbox and ctx.allowed_domains is not None:
+ config.outbound_domain_allowlist = _to_modal_domain_allowlist(ctx.allowed_domains)
+ emit_agent_log(
+ ctx.run_id,
+ "debug",
+ f"Using Modal outbound_domain_allowlist ({len(config.outbound_domain_allowlist)} domains) instead of agentsh",
+ )
+
with StepTimer("sandbox_creation", used_snapshot=prepared.used_snapshot):
sandbox = Sandbox.create(config)
+ increment_sandbox_created("vm" if use_vm_sandbox else "gvisor")
+
credentials = sandbox.get_connect_credentials()
try:
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 44bc0fecbe89..bd34c09f561c 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -73,7 +73,7 @@ def _run_connectivity_diagnostics(ctx: TaskProcessingContext, sandbox: SandboxBa
" https://gateway.us.posthog.com/health 2>&1 || echo 'CURL_GATEWAY: failed'"
)
- if ctx.allowed_domains is not None:
+ if ctx.allowed_domains is not None and not (ctx.use_modal_network_allowlist and not ctx.use_modal_vm_sandbox):
cmd = (
f"cd /scripts && env -0 > {ENV_FILE} && "
f"{build_exec_prefix()} {ENV_WRAPPER_SCRIPT} bash -c {shlex.quote(checks)}"
@@ -182,12 +182,24 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
"No MCP configs were resolved for this run. PostHog MCP tools will be unavailable in the agent session.",
)
- if ctx.allowed_domains is not None:
+ # Modal enforces egress at the edge (gVisor only), so agentsh is skipped only when it does.
+ agentsh_domains = (
+ None if (ctx.use_modal_network_allowlist and not ctx.use_modal_vm_sandbox) else ctx.allowed_domains
+ )
+
+ if ctx.use_modal_network_allowlist and not ctx.use_modal_vm_sandbox and ctx.allowed_domains is not None:
+ environment_name = ctx.sandbox_environment_name or ctx.sandbox_environment_id or "selected environment"
+ emit_agent_log(
+ ctx.run_id,
+ "debug",
+ f"Enforcing network allowlist for '{environment_name}' via Modal (agentsh disabled)",
+ )
+ elif agentsh_domains is not None:
environment_name = ctx.sandbox_environment_name or ctx.sandbox_environment_id or "selected environment"
emit_agent_log(
ctx.run_id,
"debug",
- f"Applying agentsh network policy for '{environment_name}' with allowlist: {format_allowed_domains_for_log(ctx.allowed_domains)}",
+ f"Applying agentsh network policy for '{environment_name}' with allowlist: {format_allowed_domains_for_log(agentsh_domains)}",
)
elif ctx.sandbox_environment_id:
environment_name = ctx.sandbox_environment_name or ctx.sandbox_environment_id
@@ -211,7 +223,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
model=ctx.model,
reasoning_effort=ctx.reasoning_effort,
mcp_configs=mcp_configs or None,
- allowed_domains=ctx.allowed_domains,
+ allowed_domains=agentsh_domains,
event_ingest_token=event_ingest_token,
)
@@ -221,10 +233,10 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
mark_mcp_token_issued(ctx.run_id)
# emit agentsh logs
- if ctx.allowed_domains is not None:
+ if agentsh_domains is not None:
_emit_agentsh_log_tail(ctx, sandbox)
except Exception as e:
- if ctx.allowed_domains is not None:
+ if agentsh_domains is not None:
_emit_agentsh_log_tail(ctx, sandbox)
_emit_agent_server_log_tail(ctx, sandbox)
raise SandboxExecutionError(
@@ -238,7 +250,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
cause=e,
)
- if ctx.allowed_domains is not None:
+ if agentsh_domains is not None:
emit_agent_log(ctx.run_id, "debug", "agentsh policy initialized successfully")
_emit_agentsh_log_tail(ctx, sandbox)
_emit_agent_server_log_tail(ctx, sandbox)
diff --git a/pyproject.toml b/pyproject.toml
index ba71a728b56f..a444d37923e5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -176,7 +176,7 @@ dependencies = [
"playwright~=1.60.0",
"linkedin-api-client~=0.3.0",
"glom~=24.11.0",
- "modal~=1.4.1",
+ "modal~=1.5.0",
"databricks-sql-connector~=4.2.5",
"databricks-sdk~=0.102.0",
"free-email-domains~=1.0.1",
@@ -283,7 +283,7 @@ sentiment = [
required-version = ">=0.10.2"
add-bounds = "major"
exclude-newer = "7 days"
-exclude-newer-package = { hogql-parser = false, hogql-parser-rs = false, posthoganalytics = false, pixelhog = false, django = false }
+exclude-newer-package = { hogql-parser = false, hogql-parser-rs = false, posthoganalytics = false, pixelhog = false, django = false, modal = false }
constraint-dependencies = [
"langgraph-checkpoint<3",
]
diff --git a/uv.lock b/uv.lock
index 4620bdedd24f..c31ead88aab3 100644
--- a/uv.lock
+++ b/uv.lock
@@ -19,6 +19,7 @@ pixelhog = false
hogql-parser = false
posthoganalytics = false
django = false
+modal = false
hogql-parser-rs = false
[manifest]
@@ -4263,7 +4264,7 @@ wheels = [
[[package]]
name = "modal"
-version = "1.4.1"
+version = "1.5.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohttp" },
@@ -4275,15 +4276,14 @@ dependencies = [
{ name = "rich" },
{ name = "synchronicity" },
{ name = "toml" },
- { name = "typer" },
{ name = "types-certifi" },
{ name = "types-toml" },
{ name = "typing-extensions" },
{ name = "watchfiles" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/72/b2/cdc155ef06863e3ca325fb0d6ea8feb0acd9213ff7a8a32ff1adcc37e077/modal-1.4.1.tar.gz", hash = "sha256:aadbf31e82b9ace8c77de2ee4d2c431f76ee6af54a908640fae0bdee557fd9c5", size = 685664, upload-time = "2026-03-31T01:44:32.073Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/59/f9/87425e60db2a8597b248417772b409c49ca3a05ff6b1282a21cd7d856f09/modal-1.5.0.tar.gz", hash = "sha256:15033cf84f5f4f9f8a3dcf47a768cfcca36d1ad38ab7b3459fd3cbc29aa84a77", size = 771722, upload-time = "2026-06-09T22:37:27.5Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/62/9d/cba0aed472b303481dc931b8dea693db8ecc1fb720308a69d4c679a69a71/modal-1.4.1-py3-none-any.whl", hash = "sha256:3befc9c4ac1b18ac4bf5bcb92aa6b7a5fa966c799d1dbf0cfc78ea075b2ab030", size = 787809, upload-time = "2026-03-31T01:44:29.691Z" },
+ { url = "https://files.pythonhosted.org/packages/5c/71/85e476e7d32c0a648d5aa97c4335ac02357d059c2bb734cf175b08446597/modal-1.5.0-py3-none-any.whl", hash = "sha256:9c5687eff775d1372bd70b87e43499e40777a1de160f23786c00807bf342fcb6", size = 882122, upload-time = "2026-06-09T22:37:24.608Z" },
]
[[package]]
@@ -5790,7 +5790,7 @@ requires-dist = [
{ name = "mcp", specifier = "~=1.26.0" },
{ name = "mimesis", specifier = "==5.2.1" },
{ name = "mistralai", specifier = "==1.6.0" },
- { name = "modal", specifier = "~=1.4.1" },
+ { name = "modal", specifier = "~=1.5.0" },
{ name = "more-itertools", specifier = "==9.0.0" },
{ name = "nanoid", specifier = "==2.0.0" },
{ name = "natsort", specifier = "==8.4.0" },
@@ -7833,14 +7833,14 @@ wheels = [
[[package]]
name = "synchronicity"
-version = "0.12.2"
+version = "0.12.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/f9/5e/50ea27817003665c7cc4f5bdad309f13d6329037f657848ee87fe06c3740/synchronicity-0.12.2.tar.gz", hash = "sha256:6fd605a5035d1ec74ce48fffaca80ea00345c84ca34223914e2436fb4f162ff9", size = 60018, upload-time = "2026-04-06T15:06:15.447Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/ec/d5/e96e6082790c92480380f28aa53e111844cdac7b0f75846f4772cb535a43/synchronicity-0.12.3.tar.gz", hash = "sha256:0d4228b85eaf2805f23b4615b2039a9d24ea811646e2d9f8d0c033094eb85841", size = 60261, upload-time = "2026-05-28T12:33:50.206Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/41/44/4f6ba4e2c171847e6f9a460213b196bbf26edea43d0e66889c7ccc55d368/synchronicity-0.12.2-py3-none-any.whl", hash = "sha256:9dbaca81fb7f2b57c6dea326e514e1c80e9ccfd9c9618515e84fa6091026273b", size = 41312, upload-time = "2026-04-06T15:06:14.459Z" },
+ { url = "https://files.pythonhosted.org/packages/57/ea/531a6ea751cbd989da386144810b1b8f529b0aae8c1a9beda8b40966c9c2/synchronicity-0.12.3-py3-none-any.whl", hash = "sha256:e476818cd14102136f41622c619de548f0000c024485fc18521c8fe908ea7574", size = 40982, upload-time = "2026-05-28T12:33:49.125Z" },
]
[[package]]