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 network allowlists on Modal VMs (#79608)

Alessandro Pogliaghi8bca0dd6adc9
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index 44804c76789b..9d7c21ed000e 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -256,7 +256,7 @@ Agents should stage changes with `git add`, then use the `git_signed_commit` too
| | Production (Modal) | Local dev (Docker) |
| --------- | -------------------------------------- | --------------------------------------- |
-| Isolation | gVisor kernel-level sandboxing | Standard Docker container |
+| Isolation | gVisor container or VM microVM | Standard Docker container |
| Network | Configurable via `SandboxEnvironment` | Host network via `host.docker.internal` |
| Image | `ghcr.io/posthog/posthog-sandbox-base` | Local Dockerfile build |
| Auth | Modal connect token | No token needed |
@@ -330,8 +330,20 @@ the dockerd warmup overlaps the repo clone and the environment is usually
ready by the agent's first command. Running `bootstrap-dev-stack` again is still the right first
step — it is the synchronization point, blocking until the warmup completes.
-Runs with a restricted-egress `SandboxEnvironment` (a custom domain allowlist) always stay on gVisor —
-Modal's outbound domain allowlist is a gVisor-only feature.
+Restricted runs can use the VM runtime only when `tasks-modal-network-allowlist` is also enabled.
+The network flag interlock runs before state overrides, image-builder routing, custom-image routing,
+and the VM rollout flag. A trusted `use_modal_vm_sandbox` state value cannot bypass it.
+Modal is the authoritative network enforcement layer whenever that flag is enabled, including on VMs.
+AgentSH also applies the compiled policy to the agent-server process tree as defense in depth. The
+provider policy applies outside the sandbox, so it covers traffic from the VM and its Docker containers
+without relying on AgentSH process tracing.
+Modal applies domain restrictions using the requested hostname or TLS SNI. Raw IP connections without
+an allowed SNI fail, while a connection to an IP with an allowed SNI can pass the boundary. This is an
+SNI allowlist, not DNS-to-destination-IP binding. AgentSH repeats the domain policy for the processes it
+traces as a second layer. It is not authoritative for VM egress: traffic that bypasses its proxy or process
+tree is outside that layer, and AgentSH does not add strict hostname-to-destination binding. Use an externally
+enforced egress proxy with a provider CIDR allowlist if a workload needs that binding. Test both host and
+container traffic because their network paths differ.
The `use_modal_vm_sandbox` run-state key force-selects the VM runtime for trusted server-created runs
(image builders) and is never accepted from client input.
@@ -343,6 +355,15 @@ Network access is configured per-team via `SandboxEnvironment`:
- **Full** — unrestricted network access
- **Custom** — explicit allowlist of domains, optionally including the trusted defaults
+Allowed-domain values contain a domain name only, such as `example.com` or `*.example.com`.
+Schemes, paths, ports, IP addresses, rooted names, local host aliases, and wildcards in other positions
+are rejected when an environment is created or updated. Values are normalized to lowercase IDNA names,
+duplicates are removed, and each environment can contain up to 100 allowed domains.
+
+`None` is the internal representation for unrestricted access. A restricted empty list still includes
+the infrastructure domains required to run the sandbox. Modal and agentsh consume provider-specific
+forms of one compiled effective policy, including the same infrastructure domain coverage.
+
To apply network restrictions from your product code,
create a `SandboxEnvironment` and pass its ID to `Task.create_and_run`:
@@ -371,10 +392,11 @@ task = Task.create_and_run(
)
```
-The temporal workflow resolves the allowed domains at execution time from the environment,
-so updates to the environment take effect on the next run.
-Domain restrictions are enforced at the syscall level by `agentsh` via ptrace —
-the agent cannot bypass them through proxy settings or DNS tricks.
+The temporal workflow resolves and compiles allowed domains at execution time, so environment updates
+take effect on the next run. The compiled policy and its fingerprint stay fixed across activity retries.
+Modal enforces the network boundary on every restricted run when
+`tasks-modal-network-allowlist` is enabled. During the rollout, restricted runs without that flag stay
+on gVisor and use agentsh; they cannot route to a VM without the provider policy.
Environments can also be managed via the REST API (`SandboxEnvironmentViewSet`)
or the PostHog Desktop settings UI.
diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.py
index 12bc69dbb363..b9bd6ad39eb8 100644
--- a/products/tasks/backend/exceptions.py
+++ b/products/tasks/backend/exceptions.py
@@ -115,6 +115,10 @@ class ComputeBillingLimitError(ProcessTaskError, ComputeBillingLimitExceeded):
)
+class SandboxNetworkPolicyError(ProcessTaskFatalError):
+ pass
+
+
class SandboxNotFoundError(ProcessTaskFatalError):
"""Sandbox does not exist."""
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index f61b7a909426..2f46b3c4e090 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -78,6 +78,10 @@ from products.tasks.backend.logic.services.image_builder import (
is_custom_images_enabled,
read_spec_from_builder_sandbox,
)
+from products.tasks.backend.logic.services.network_policy import (
+ MAX_SANDBOX_ALLOWED_DOMAINS,
+ normalize_requested_domains,
+)
from products.tasks.backend.mentions import resolve_mentioned_user_ids
from products.tasks.backend.models import (
Channel,
@@ -1482,7 +1486,7 @@ def upsert_internal_sandbox_env(
"repositories": [],
}
if allowed_domains is not None:
- defaults["allowed_domains"] = allowed_domains
+ defaults["allowed_domains"] = normalize_sandbox_allowed_domains(allowed_domains)
defaults["include_default_domains"] = include_default_domains
try:
env, _ = SandboxEnvironment.objects.update_or_create(
@@ -1582,6 +1586,12 @@ def _validate_user_sandbox_env_vars(environment_variables: dict | None) -> None:
raise ValueError(f"Environment variable key {key!r} is not allowed")
+def normalize_sandbox_allowed_domains(allowed_domains: list[str]) -> list[str]:
+ if len(allowed_domains) > MAX_SANDBOX_ALLOWED_DOMAINS:
+ raise ValueError(f"You can allow up to {MAX_SANDBOX_ALLOWED_DOMAINS} domains")
+ return list(normalize_requested_domains(allowed_domains))
+
+
def _accessible_sandbox_envs(team_id: int, user_id: int):
return (
SandboxEnvironment.objects.filter(team_id=team_id)
@@ -1629,12 +1639,13 @@ def create_sandbox_environment(
"""Create a team environment owned by the user and return it as a DTO."""
_validate_user_sandbox_env_vars(environment_variables)
_validate_custom_image_id(team_id, user_id, custom_image_id)
+ normalized_allowed_domains = normalize_sandbox_allowed_domains(allowed_domains)
env = SandboxEnvironment.objects.create(
team_id=team_id,
created_by_id=user_id,
name=name,
network_access_level=network_access_level,
- allowed_domains=allowed_domains,
+ allowed_domains=normalized_allowed_domains,
include_default_domains=include_default_domains,
repositories=repositories,
environment_variables=environment_variables,
@@ -1655,6 +1666,8 @@ def update_sandbox_environment(
_validate_user_sandbox_env_vars(fields["environment_variables"])
if "custom_image_id" in fields:
_validate_custom_image_id(team_id, user_id, fields["custom_image_id"])
+ if "allowed_domains" in fields:
+ fields["allowed_domains"] = normalize_sandbox_allowed_domains(fields["allowed_domains"])
for key, value in fields.items():
setattr(env, key, value)
env.save()
@@ -5450,7 +5463,6 @@ def warm_task_sandbox(
extra_state: dict = {
"branch": branch,
"initial_permission_mode": initial_permission_mode,
- "use_modal_network_allowlist": False,
}
if sandbox_environment is not None:
extra_state["sandbox_environment_id"] = str(sandbox_environment.id)
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 8d97ba36fbc0..1023ff261412 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -28,6 +28,7 @@ import modal
import requests
from modal.exception import (
ConnectionError as ModalConnectionError,
+ InvalidError as ModalInvalidError,
ResourceExhaustedError as ModalResourceExhaustedError,
ServiceError as ModalServiceError,
TimeoutError as ModalTimeoutError,
@@ -48,6 +49,7 @@ from products.tasks.backend.constants import (
from products.tasks.backend.exceptions import (
SandboxCleanupError,
SandboxExecutionError,
+ SandboxNetworkPolicyError,
SandboxNotFoundError,
SandboxNotRunningError,
SandboxProvisionError,
@@ -191,6 +193,20 @@ SESSION_INIT_PROBE_HOSTS = (
"api.anthropic.com",
)
+_MODAL_NETWORK_POLICY_REJECTION_MARKERS = (
+ "outbound_domain_allowlist",
+ "outbound domain allowlist",
+ "domain allowlist",
+ "allowed domains",
+)
+
+
+def _is_modal_network_policy_rejection(error: BaseException) -> bool:
+ if not isinstance(error, ModalInvalidError):
+ return False
+ message = str(error).casefold()
+ return any(marker in message for marker in _MODAL_NETWORK_POLICY_REJECTION_MARKERS)
+
def _session_init_probe_hosts() -> list[str]:
"""Hosts the startup-failure egress probe checks. Both gateway settings
@@ -824,7 +840,7 @@ class ModalSandbox(SandboxBase):
if config.block_network:
create_kwargs["block_network"] = True
- if config.outbound_domain_allowlist:
+ if config.outbound_domain_allowlist is not None:
create_kwargs["outbound_domain_allowlist"] = config.outbound_domain_allowlist
if secrets:
@@ -916,11 +932,13 @@ class ModalSandbox(SandboxBase):
return sandbox
+ except SandboxNetworkPolicyError:
+ raise
except Exception as e:
logger.exception(f"Failed to create sandbox: {e}")
raise SandboxProvisionError(
"Failed to create sandbox", {"config_name": config.name, "error": str(e)}, cause=e
- )
+ ) from e
@staticmethod
def _create_from_image_candidates(
@@ -936,12 +954,22 @@ class ModalSandbox(SandboxBase):
re-enter this chain (the wedged-restore recovery) can describe what they landed on.
"""
for index, candidate in enumerate(candidates):
- create_kwargs["image"] = candidate.image
+ attempt_kwargs = {**create_kwargs, "image": candidate.image}
try:
modal_output: StringIO | None
with capture_modal_output_if_debug() as modal_output:
- sb = modal.Sandbox.create(**create_kwargs) # type: ignore[arg-type]
+ sb = modal.Sandbox.create(**attempt_kwargs) # type: ignore[arg-type]
except Exception as e:
+ if config.outbound_domain_allowlist is not None and _is_modal_network_policy_rejection(e):
+ raise SandboxNetworkPolicyError(
+ "Modal rejected the requested sandbox network policy.",
+ {
+ "config_name": config.name,
+ "network_policy_fingerprint": config.network_policy_fingerprint,
+ "error": str(e),
+ },
+ cause=e,
+ ) from e
if index == len(candidates) - 1:
raise
logger.warning(
@@ -1364,6 +1392,8 @@ class ModalSandbox(SandboxBase):
raise RuntimeError("Sandbox not in running state.")
if self._agent_server_is_healthy():
+ if wait_for_health:
+ self.wait_for_agent_server_ready(allowed_domains)
logger.info(f"Agent-server already healthy in sandbox {self.id}; skipping relaunch")
return
self._free_agent_server_port()
@@ -1451,6 +1481,12 @@ class ModalSandbox(SandboxBase):
def wait_for_agent_server_ready(self, allowed_domains: list[str] | None = None) -> None:
if self._wait_for_health_check():
+ if allowed_domains is not None and not self._agentsh_daemon_is_healthy():
+ raise SandboxExecutionError(
+ "Failed to verify agentsh network enforcement",
+ {"sandbox_id": self.id},
+ cause=RuntimeError("agentsh daemon health check failed"),
+ )
logger.info(f"Agent-server ready in sandbox {self.id}")
return
diagnostics = self._diagnose_startup_failure(allowed_domains)
diff --git a/products/tasks/backend/logic/services/network_policy.py b/products/tasks/backend/logic/services/network_policy.py
new file mode 100644
index 000000000000..6b4bbc66d940
--- /dev/null
+++ b/products/tasks/backend/logic/services/network_policy.py
@@ -0,0 +1,191 @@
+import json
+import hashlib
+import ipaddress
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass
+
+from django.core.exceptions import ValidationError
+from django.core.validators import DomainNameValidator
+
+import idna
+
+_domain_name_validator = DomainNameValidator(accept_idna=False)
+_MODAL_UNSUPPORTED_HOSTS = {"localhost", "host.docker.internal"}
+MAX_SANDBOX_ALLOWED_DOMAINS = 100
+
+
+@dataclass(frozen=True, kw_only=True)
+class InvalidDomain:
+ index: int
+ value: str
+ reason: str
+
+
+class NetworkPolicyValidationError(ValueError):
+ def __init__(self, invalid_domains: Sequence[InvalidDomain]) -> None:
+ self.invalid_domains = tuple(invalid_domains)
+ positions = ", ".join(str(item.index + 1) for item in self.invalid_domains)
+ super().__init__(f"Invalid allowed domain at position {positions}")
+
+
+@dataclass(frozen=True, kw_only=True)
+class EffectiveNetworkPolicy:
+ requested_domains: tuple[str, ...]
+ infrastructure_domains: tuple[str, ...]
+ modal_domains: tuple[str, ...]
+ agentsh_domains: tuple[str, ...]
+ agentsh_debug_domains: tuple[str, ...]
+ agentsh_debug_ports: tuple[int, ...]
+ fingerprint: str
+
+
+def normalize_domain(domain: str) -> str:
+ normalized = domain.strip().lower()
+ if not normalized:
+ raise ValueError("Domain cannot be empty")
+
+ wildcard = normalized.startswith("*.")
+ hostname = normalized[2:] if wildcard else normalized
+ if "*" in hostname:
+ raise ValueError("Wildcards are only supported as the leftmost '*.' label")
+
+ try:
+ hostname = idna.encode(hostname, uts46=True).decode("ascii")
+ except idna.IDNAError as error:
+ raise ValueError("Domain is not valid IDNA") from error
+
+ if hostname in _MODAL_UNSUPPORTED_HOSTS:
+ raise ValueError("Local host aliases are not supported")
+ if hostname.endswith("."):
+ raise ValueError("Rooted domain names are not supported")
+
+ try:
+ ipaddress.ip_address(hostname)
+ except ValueError:
+ pass
+ else:
+ raise ValueError("IP addresses are not supported")
+
+ if "." not in hostname:
+ raise ValueError("Domain must contain at least two labels")
+
+ try:
+ _domain_name_validator(hostname)
+ except ValidationError as error:
+ raise ValueError("Domain name is malformed") from error
+
+ return f"*.{hostname}" if wildcard else hostname
+
+
+def normalize_requested_domains(domains: Sequence[str]) -> tuple[str, ...]:
+ normalized: list[str] = []
+ seen: set[str] = set()
+ invalid: list[InvalidDomain] = []
+ for index, domain in enumerate(domains):
+ try:
+ value = normalize_domain(domain)
+ except ValueError as error:
+ invalid.append(InvalidDomain(index=index, value=domain, reason=str(error)))
+ continue
+ if value not in seen:
+ normalized.append(value)
+ seen.add(value)
+ if invalid:
+ raise NetworkPolicyValidationError(invalid)
+ return tuple(normalized)
+
+
+def domain_pattern_matches(pattern: str, hostname: str) -> bool:
+ normalized_hostname = hostname.rstrip(".").lower()
+ if pattern.startswith("*."):
+ base = pattern[2:]
+ return normalized_hostname == base or normalized_hostname.endswith(f".{base}")
+ return normalized_hostname == pattern
+
+
+def _deduplicate(domains: Iterable[str]) -> tuple[str, ...]:
+ return tuple(dict.fromkeys(domains))
+
+
+def _collapse_modal_domains(domains: Sequence[str]) -> tuple[str, ...]:
+ wildcard_bases = {domain[2:] for domain in domains if domain.startswith("*.")}
+ result: list[str] = []
+ seen: set[str] = set()
+
+ def is_covered_by_parent_wildcard(base: str) -> bool:
+ _, separator, parent = base.partition(".")
+ while separator:
+ if parent in wildcard_bases:
+ return True
+ _, separator, parent = parent.partition(".")
+ return False
+
+ for domain in domains:
+ base = domain[2:] if domain.startswith("*.") else domain
+ covered = is_covered_by_parent_wildcard(base)
+ if not domain.startswith("*."):
+ covered = covered or base in wildcard_bases
+ if not covered and domain not in seen:
+ result.append(domain)
+ seen.add(domain)
+ return tuple(result)
+
+
+def _expand_agentsh_wildcard_apex(domains: Sequence[str]) -> tuple[str, ...]:
+ result: list[str] = []
+ seen: set[str] = set()
+ for domain in domains:
+ if domain not in seen:
+ result.append(domain)
+ seen.add(domain)
+ if domain.startswith("*.") and domain[2:] not in seen:
+ apex = domain[2:]
+ result.append(apex)
+ seen.add(apex)
+ return tuple(result)
+
+
+def compile_network_policy(
+ requested_domains: Sequence[str],
+ *,
+ infrastructure_domains: Sequence[str],
+ debug_domains: Sequence[str] = (),
+ debug_ports: Sequence[int] = (),
+) -> EffectiveNetworkPolicy:
+ requested = normalize_requested_domains(requested_domains)
+ infrastructure = normalize_requested_domains(infrastructure_domains)
+ external_domains = _deduplicate((*requested, *infrastructure))
+
+ modal_debug_domains: list[str] = []
+ seen_modal_debug_domains: set[str] = set()
+ for domain in debug_domains:
+ try:
+ normalized = normalize_domain(domain)
+ except ValueError:
+ continue
+ if normalized not in seen_modal_debug_domains:
+ modal_debug_domains.append(normalized)
+ seen_modal_debug_domains.add(normalized)
+
+ modal_domains = _collapse_modal_domains((*external_domains, *modal_debug_domains))
+ agentsh_domains = _expand_agentsh_wildcard_apex(external_domains)
+ normalized_debug_ports = tuple(dict.fromkeys(int(port) for port in debug_ports))
+ fingerprint_payload = {
+ "agentsh_debug_domains": list(debug_domains),
+ "agentsh_debug_ports": normalized_debug_ports,
+ "agentsh_domains": agentsh_domains,
+ "modal_domains": modal_domains,
+ "version": 1,
+ }
+ fingerprint = hashlib.sha256(
+ json.dumps(fingerprint_payload, separators=(",", ":"), sort_keys=True).encode()
+ ).hexdigest()
+ return EffectiveNetworkPolicy(
+ requested_domains=requested,
+ infrastructure_domains=infrastructure,
+ modal_domains=modal_domains,
+ agentsh_domains=agentsh_domains,
+ agentsh_debug_domains=tuple(debug_domains),
+ agentsh_debug_ports=normalized_debug_ports,
+ fingerprint=fingerprint,
+ )
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index f1c927a3cf71..686a066f2726 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -161,8 +161,8 @@ class SandboxConfig(BaseModel):
cpu_request_cores: float = BURSTABLE_REQUEST_CPU_CORES
memory_request_mb: int = BURSTABLE_REQUEST_MEMORY_MB
vm_runtime: bool = False
- # gVisor only — Modal rejects this under vm_runtime.
outbound_domain_allowlist: list[str] | None = None
+ network_policy_fingerprint: str | None = None
# gVisor only. An empty domain allowlist means unrestricted network in
# Modal, so callers that require no egress must state it explicitly.
block_network: bool = False
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 90c3302181d4..85338528c898 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -12,6 +12,7 @@ from django.test import override_settings
from modal.exception import (
ConnectionError as ModalConnectionError,
+ InvalidError as ModalInvalidError,
ResourceExhaustedError as ModalResourceExhaustedError,
ServiceError as ModalServiceError,
TimeoutError as ModalTimeoutError,
@@ -21,6 +22,7 @@ from requests.exceptions import ConnectionError, Timeout
from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_DIRECTORY
from products.tasks.backend.exceptions import (
SandboxExecutionError,
+ SandboxNetworkPolicyError,
SandboxProvisionError,
SnapshotCreationError,
SnapshotFileLimitExceededError,
@@ -766,6 +768,7 @@ class TestModalSandboxAgentServer:
with (
patch.object(mock_sandbox, "_agent_server_is_healthy", return_value=True),
+ patch.object(mock_sandbox, "wait_for_agent_server_ready") as wait_for_ready,
patch.object(mock_sandbox, "_free_agent_server_port") as mock_free,
):
mock_sandbox.start_agent_server(
@@ -773,11 +776,21 @@ class TestModalSandboxAgentServer:
task_id="task-123",
run_id="run-456",
mode="background",
+ allowed_domains=["example.com"],
)
+ wait_for_ready.assert_called_once_with(["example.com"])
mock_free.assert_not_called()
mock_sandbox.execute.assert_not_called()
+ def test_wait_for_agent_server_ready_rejects_unhealthy_agentsh(self, mock_sandbox: Any):
+ with (
+ patch.object(mock_sandbox, "_wait_for_health_check", return_value=True),
+ patch.object(mock_sandbox, "_agentsh_daemon_is_healthy", return_value=False),
+ ):
+ with pytest.raises(SandboxExecutionError, match="Failed to verify agentsh network enforcement"):
+ mock_sandbox.wait_for_agent_server_ready(["example.com"])
+
def test_start_agent_server_frees_port_before_relaunch(self, mock_sandbox: Any):
mock_sandbox.execute = MagicMock(
side_effect=[
@@ -1185,6 +1198,13 @@ class TestModalSandboxCreateAllowlist:
assert "outbound_domain_allowlist" not in mock_create.call_args.kwargs
+ def test_create_forwards_empty_allowlist_when_explicitly_set(self):
+ config = SandboxConfig(name="t", outbound_domain_allowlist=[])
+
+ mock_create = self._create_with_config(config)
+
+ assert mock_create.call_args.kwargs["outbound_domain_allowlist"] == []
+
def test_create_sets_vm_runtime_experimental_option(self):
config = SandboxConfig(name="t", vm_runtime=True)
@@ -1265,6 +1285,97 @@ class TestModalSandboxCreateImageFallback:
assert sandbox.config.snapshot_restored is True
assert sandbox.config.image_fallback is not None
+ def test_unrelated_invalid_error_preserves_vm_network_policy_on_fallback(self):
+ config = SandboxConfig(
+ name="t",
+ template=SandboxTemplate.VM_BASE,
+ custom_image_name="posthog-dev-stack",
+ outbound_domain_allowlist=["example.com", "*.posthog.com"],
+ network_policy_fingerprint="policy-hash",
+ )
+ bare_custom = MagicMock(name="bare_custom")
+ overlaid_custom = MagicMock(name="overlaid_custom")
+ mock_sb = MagicMock(object_id="sb-created")
+ attempts: list[dict[str, Any]] = []
+
+ def sandbox_create(**kwargs: Any) -> Any:
+ attempts.append(kwargs)
+ if kwargs["image"] is overlaid_custom:
+ raise ModalInvalidError("invalid image reference")
+ return mock_sb
+
+ with (
+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),
+ patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox._get_template_image",
+ return_value=MagicMock(name="base"),
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_name",
+ return_value=bare_custom,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox._attach_local_package_mounts",
+ return_value=overlaid_custom,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create",
+ side_effect=sandbox_create,
+ ),
+ patch("products.tasks.backend.logic.services.modal_sandbox.capture_exception"),
+ ):
+ ModalSandbox.create(config)
+
+ assert len(attempts) == 3
+ assert all(attempt["experimental_options"] == {"vm_runtime": True} for attempt in attempts)
+ assert all(attempt["outbound_domain_allowlist"] == ["example.com", "*.posthog.com"] for attempt in attempts)
+
+ def test_network_policy_rejection_is_fatal_without_image_fallback(self):
+ config = SandboxConfig(
+ name="t",
+ template=SandboxTemplate.VM_BASE,
+ custom_image_name="posthog-dev-stack",
+ outbound_domain_allowlist=["example.com"],
+ network_policy_fingerprint="policy-hash",
+ )
+ bare_custom = MagicMock(name="bare_custom")
+ overlaid_custom = MagicMock(name="overlaid_custom")
+ attempts: list[dict[str, Any]] = []
+
+ def sandbox_create(**kwargs: Any) -> Any:
+ attempts.append(kwargs)
+ raise ModalInvalidError("outbound_domain_allowlist is incompatible with vm_runtime")
+
+ with (
+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),
+ patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox._get_template_image",
+ return_value=MagicMock(name="base"),
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_name",
+ return_value=bare_custom,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox._attach_local_package_mounts",
+ return_value=overlaid_custom,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create",
+ side_effect=sandbox_create,
+ ),
+ patch("products.tasks.backend.exceptions.capture_exception"),
+ ):
+ with pytest.raises(SandboxNetworkPolicyError) as error:
+ ModalSandbox.create(config)
+
+ assert error.value.non_retryable is True
+ assert len(attempts) == 1
+ assert attempts[0]["outbound_domain_allowlist"] == ["example.com"]
+ assert attempts[0]["experimental_options"] == {"vm_runtime": True}
+
def _create_with_probe(
self,
config: SandboxConfig,
diff --git a/products/tasks/backend/logic/services/tests/test_network_policy.py b/products/tasks/backend/logic/services/tests/test_network_policy.py
new file mode 100644
index 000000000000..205228aac171
--- /dev/null
+++ b/products/tasks/backend/logic/services/tests/test_network_policy.py
@@ -0,0 +1,81 @@
+import pytest
+
+from parameterized import parameterized
+
+from products.tasks.backend.logic.services.network_policy import (
+ NetworkPolicyValidationError,
+ compile_network_policy,
+ domain_pattern_matches,
+ normalize_requested_domains,
+)
+
+
+ [
+ ("empty", ""),
+ ("localhost", "localhost"),
+ ("docker_host", "host.docker.internal"),
+ ("scheme", "https://example.com"),
+ ("path", "example.com/path"),
+ ("port", "example.com:443"),
+ ("rooted", "example.com."),
+ ("unicode_rooted", "example.com。"),
+ ("ipv4", "127.0.0.1"),
+ ("ipv6", "2001:db8::1"),
+ ("single_label", "example"),
+ ("wildcard_only", "*"),
+ ("misplaced_wildcard", "api.*.example.com"),
+ ("malformed_label", "-api.example.com"),
+ ]
+)
+def test_requested_domains_reject_values_modal_cannot_enforce(_name: str, domain: str) -> None:
+ with pytest.raises(NetworkPolicyValidationError):
+ normalize_requested_domains([domain])
+
+
+ [
+ ("case_whitespace_and_duplicates", [" EXAMPLE.com ", "example.com"], ("example.com",)),
+ ("idna_label", ["täst.example"], ("xn--tst-qla.example",)),
+ ("idna_2008_deviation", ["faß.de"], ("xn--fa-hia.de",)),
+ ("unicode_label_separator", ["example。com"], ("example.com",)),
+ ]
+)
+def test_requested_domains_are_canonicalized_without_changing_host_coverage(
+ _name: str, domains: list[str], expected: tuple[str, ...]
+) -> None:
+ assert normalize_requested_domains(domains) == expected
+
+
+def test_effective_policy_matches_external_host_coverage_across_layers() -> None:
+ policy = compile_network_policy(
+ ["*.example.com", "api.service.test"],
+ infrastructure_domains=["*.posthog.com", "api.anthropic.com", "gateway.us.posthog.com"],
+ )
+
+ assert policy.modal_domains == ("*.example.com", "api.service.test", "*.posthog.com", "api.anthropic.com")
+ assert "example.com" in policy.agentsh_domains
+ assert "posthog.com" in policy.agentsh_domains
+
+ for hostname in (
+ "example.com",
+ "api.example.com",
+ "deep.api.example.com",
+ "api.service.test",
+ "posthog.com",
+ "gateway.us.posthog.com",
+ "api.anthropic.com",
+ "notexample.com",
+ "example.org",
+ ):
+ modal_allows = any(domain_pattern_matches(pattern, hostname) for pattern in policy.modal_domains)
+ agentsh_allows = any(domain_pattern_matches(pattern, hostname) for pattern in policy.agentsh_domains)
+ assert modal_allows is agentsh_allows
+
+
+def test_empty_requested_policy_still_contains_infrastructure_domains() -> None:
+ policy = compile_network_policy([], infrastructure_domains=["api.example.com"])
+
+ assert policy.requested_domains == ()
+ assert policy.modal_domains == ("api.example.com",)
+ assert policy.agentsh_domains == ("api.example.com",)
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index d689d69d3181..4bb59c291151 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -3300,6 +3300,8 @@ class SandboxEnvironmentWriteSerializer(serializers.Serializer):
child=serializers.CharField(max_length=255),
required=False,
default=list,
+ max_length=tasks_facade.MAX_SANDBOX_ALLOWED_DOMAINS,
+ error_messages={"max_length": f"You can allow up to {tasks_facade.MAX_SANDBOX_ALLOWED_DOMAINS} domains."},
help_text="Allowed domains for custom network access.",
)
include_default_domains = serializers.BooleanField(
@@ -3348,6 +3350,14 @@ class SandboxEnvironmentWriteSerializer(serializers.Serializer):
)
return value
+ def validate_allowed_domains(self, value: list[str]) -> list[str]:
+ try:
+ return tasks_facade.normalize_sandbox_allowed_domains(value)
+ except ValueError as error:
+ raise serializers.ValidationError(
+ f"{error}. Enter domain names such as example.com or *.example.com without a scheme, path, or port."
+ ) from error
+
class SandboxCustomImageSerializer(DataclassSerializer):
"""Detail response for a custom sandbox base image."""
diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.py
index d59aa1c23376..42d25b6ae5dc 100644
--- a/products/tasks/backend/temporal/metrics.py
+++ b/products/tasks/backend/temporal/metrics.py
@@ -3,6 +3,7 @@ import datetime as dt
from collections.abc import Mapping
from typing import Any
+import posthoganalytics
from temporalio import activity
from temporalio.common import MetricMeter
@@ -83,6 +84,20 @@ def sandbox_runtime_label(use_vm_sandbox: bool) -> str:
return "vm" if use_vm_sandbox else "gvisor"
+def record_network_enforcement(stage: str, runtime: str, layer: str, outcome: str) -> None:
+ try:
+ client = posthoganalytics.default_client
+ if client is None:
+ return
+ client.metrics.count(
+ "tasks.sandbox.network_enforcement",
+ 1,
+ attributes={"stage": stage, "runtime": runtime, "layer": layer, "outcome": outcome},
+ )
+ except Exception:
+ pass
+
+
def _runtime_adapter_label(value: str | None) -> str:
"""Bounded label: unexpected values collapse to "other" to cap cardinality."""
if not value:
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 c9873e134278..41389337025b 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
@@ -26,9 +26,19 @@ from products.tasks.backend.constants import (
vm_sandbox_origin_in_rollout,
vm_sandbox_origin_rollout_percentages,
)
-from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyError
+from products.tasks.backend.exceptions import SandboxNetworkPolicyError, TaskInvalidStateError, TaskRunNotReadyError
from products.tasks.backend.facade.api import ensure_task_run_session
from products.tasks.backend.feature_flags import is_agent_otel_telemetry_enabled
+from products.tasks.backend.logic.services.agentsh import (
+ _get_debug_only_domains,
+ _get_debug_only_ports,
+ enforced_egress_domains,
+)
+from products.tasks.backend.logic.services.network_policy import (
+ EffectiveNetworkPolicy,
+ NetworkPolicyValidationError,
+ compile_network_policy,
+)
from products.tasks.backend.logic.services.sandbox_config import (
MAX_SANDBOX_CPU_CORES,
MAX_SANDBOX_MEMORY_GB,
@@ -53,7 +63,7 @@ class GetTaskProcessingContextInput:
create_pr: bool = True
-@dataclass
+@dataclass(frozen=False)
class TaskProcessingContext:
"""
Serializable context object passed to all activities in the task processing workflow.
@@ -79,6 +89,9 @@ class TaskProcessingContext:
_branch: str | None = None
sandbox_environment_name: str | None = None
allowed_domains: list[str] | None = None
+ modal_domain_allowlist: list[str] | None = None
+ agentsh_domain_allowlist: list[str] | None = None
+ network_policy_fingerprint: str | None = None
json_schema: dict | None = None
ci_prompt: str | None = None
# Captured at workflow start so snapshot creation is deterministic across
@@ -448,7 +461,7 @@ class VmSandboxDecision:
use_vm_sandbox: bool
# Modal image name from the flag payload that VM runs fall back to when no custom
# image was picked. None whenever the payload was not consulted (state override,
- # flag error, restricted egress) or defines no default — image-builder runs must
+ # flag error, network interlock) or defines no default — image-builder runs must
# keep layering on the plain VM base, never on a prebaked default.
default_custom_image: str | None = None
@@ -460,10 +473,13 @@ def _resolve_modal_vm_sandbox(
run_id: str,
origin_product: str | None,
allowed_domains: list[str] | None,
+ use_modal_network_allowlist: bool = False,
custom_image_available: bool = False,
state: dict | None = None,
) -> VmSandboxDecision:
- if allowed_domains is not None:
+ if allowed_domains is not None and not use_modal_network_allowlist:
+ # Restricted VMs require Modal's provider policy, so routing cannot consult overrides
+ # or rollout flags until that independent policy flag is enabled.
log_with_activity_context(
"modal_vm_sandbox_skipped_restricted_egress",
run_id=run_id,
@@ -640,6 +656,17 @@ def _is_modal_network_allowlist_enabled(
return enabled
+def _compile_effective_network_policy(allowed_domains: list[str]) -> EffectiveNetworkPolicy:
+ debug_domains = _get_debug_only_domains() if settings.DEBUG else []
+ debug_ports = _get_debug_only_ports() if settings.DEBUG else []
+ return compile_network_policy(
+ allowed_domains,
+ infrastructure_domains=enforced_egress_domains(),
+ debug_domains=debug_domains,
+ debug_ports=debug_ports,
+ )
+
+
def _is_modal_directory_resume_snapshots_enabled(
*,
distinct_id: str,
@@ -881,12 +908,47 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
run_id=run_id,
state=state,
)
+ 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",
+ )
+
+ effective_network_policy: EffectiveNetworkPolicy | None = None
+ if allowed_domains is not None:
+ try:
+ effective_network_policy = _compile_effective_network_policy(allowed_domains)
+ except NetworkPolicyValidationError as error:
+ log_with_activity_context(
+ "sandbox_network_policy_invalid",
+ run_id=run_id,
+ sandbox_environment_id=sandbox_environment_id,
+ invalid_domain_positions=[item.index + 1 for item in error.invalid_domains],
+ )
+ if use_modal_network_allowlist:
+ raise SandboxNetworkPolicyError(
+ "This sandbox environment contains an invalid allowed domain. Update its network settings and run the task again.",
+ {
+ "run_id": run_id,
+ "sandbox_environment_id": sandbox_environment_id,
+ "invalid_domain_positions": [item.index + 1 for item in error.invalid_domains],
+ },
+ cause=error,
+ ) from error
+
vm_sandbox_decision = _resolve_modal_vm_sandbox(
distinct_id=distinct_id,
organization_id=organization_id,
run_id=run_id,
origin_product=task.origin_product,
allowed_domains=allowed_domains,
+ use_modal_network_allowlist=use_modal_network_allowlist,
custom_image_available=environment_custom_image_name is not None,
state=state,
)
@@ -914,17 +976,6 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
# this image is missing or unloadable.
custom_image_name = vm_sandbox_decision.default_custom_image
emit_agent_log(run_id, "debug", f"Using the organization's default custom base image: {custom_image_name}")
- 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",
- )
burstable_sandbox_resources_enabled = _is_burstable_sandbox_resources_enabled(
run_id=run_id,
state=state,
@@ -1010,6 +1061,15 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
_branch=task_run.branch,
sandbox_environment_name=sandbox_environment_name,
allowed_domains=allowed_domains,
+ modal_domain_allowlist=(
+ list(effective_network_policy.modal_domains) if effective_network_policy is not None else None
+ ),
+ agentsh_domain_allowlist=(
+ list(effective_network_policy.agentsh_domains) if effective_network_policy is not None else None
+ ),
+ network_policy_fingerprint=(
+ effective_network_policy.fingerprint if effective_network_policy is not None else None
+ ),
json_schema=task.json_schema,
ci_prompt=task.ci_prompt,
use_modal_resume_snapshots=settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS or use_modal_directory_resume_snapshots,
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 0f62bfda8985..77bacdd10a8d 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -24,15 +24,25 @@ from products.tasks.backend.exceptions import (
CredentialUnavailableError,
GitHubAuthenticationError,
OAuthTokenError,
+ SandboxNetworkPolicyError,
TaskNotFoundError,
)
-from products.tasks.backend.logic.services.agentsh import _get_debug_only_domains, enforced_egress_domains
+from products.tasks.backend.logic.services.agentsh import (
+ _get_debug_only_domains,
+ _get_debug_only_ports,
+ enforced_egress_domains,
+)
from products.tasks.backend.logic.services.compute_quota import get_compute_quota_denial_reason
from products.tasks.backend.logic.services.connection_token import (
SANDBOX_JWT_STATE_KID_KEY,
get_primary_sandbox_jwt_kid,
get_sandbox_jwt_public_key,
)
+from products.tasks.backend.logic.services.network_policy import (
+ EffectiveNetworkPolicy,
+ NetworkPolicyValidationError,
+ compile_network_policy,
+)
from products.tasks.backend.logic.services.sandbox import (
ExecutionResult,
Sandbox,
@@ -49,6 +59,7 @@ from products.tasks.backend.temporal.metrics import (
StepTimer,
increment_snapshot_restore,
increment_snapshot_usage,
+ record_network_enforcement,
record_sandbox_created,
sandbox_runtime_label,
)
@@ -197,44 +208,53 @@ class InvalidateResumeSnapshotInput:
snapshot_external_id: str | None = None
-def _is_covered_by_wildcard(host: str, wildcard_bases: set[str]) -> bool:
- base = host[2:] if host.startswith("*.") else host
- for wildcard_base in wildcard_bases:
- if host.startswith("*.") and base == wildcard_base:
- continue
- if base == wildcard_base or base.endswith("." + wildcard_base):
- return True
- return False
+def _compile_sandbox_network_policy(allowed_domains: list[str]) -> EffectiveNetworkPolicy:
+ return compile_network_policy(
+ allowed_domains,
+ infrastructure_domains=enforced_egress_domains(),
+ debug_domains=_get_debug_only_domains() if settings.DEBUG else [],
+ debug_ports=_get_debug_only_ports() if settings.DEBUG else [],
+ )
def _to_modal_domain_allowlist(allowed_domains: list[str]) -> list[str]:
- """Translate the agentsh allowlist into Modal's outbound_domain_allowlist.
+ return list(_compile_sandbox_network_policy(allowed_domains).modal_domains)
- Modal fences the whole sandbox and supports `*.` wildcards that match the
- apex and any subdomain, so union in the shared egress source set (infra
- plus settings-derived sandbox hosts) the agent needs, drop loopback
- aliases Modal rejects as invalid domains, and collapse entries already
- covered by a wildcard.
- """
- domains = list(allowed_domains)
- extra = enforced_egress_domains()
- if settings.DEBUG:
- extra += _get_debug_only_domains()
- for domain in extra:
- if domain not in domains:
- domains.append(domain)
-
- fqdns = [d for d in domains if "." in d and d != "host.docker.internal"]
- wildcard_bases = {d[2:] for d in fqdns if d.startswith("*.")}
- result: list[str] = []
- seen: set[str] = set()
- for domain in fqdns:
- if domain in seen or _is_covered_by_wildcard(domain, wildcard_bases):
- continue
- seen.add(domain)
- result.append(domain)
- return result
+def _apply_modal_network_policy(
+ config: SandboxConfig,
+ ctx: TaskProcessingContext,
+ *,
+ use_vm_sandbox: bool,
+) -> None:
+ if ctx.allowed_domains is None:
+ return
+ if use_vm_sandbox and not ctx.use_modal_network_allowlist:
+ record_network_enforcement("configuration_validation", "vm", "modal", "failure")
+ raise SandboxNetworkPolicyError(
+ "A restricted sandbox cannot start on the VM runtime without Modal network enforcement.",
+ {"run_id": ctx.run_id, "network_policy_fingerprint": ctx.network_policy_fingerprint},
+ cause=RuntimeError("restricted VM network interlock failed"),
+ )
+ if not ctx.use_modal_network_allowlist:
+ return
+ if ctx.modal_domain_allowlist is None or ctx.network_policy_fingerprint is None:
+ try:
+ policy = _compile_sandbox_network_policy(ctx.allowed_domains)
+ except NetworkPolicyValidationError as error:
+ record_network_enforcement(
+ "configuration_validation", sandbox_runtime_label(use_vm_sandbox), "modal", "failure"
+ )
+ raise SandboxNetworkPolicyError(
+ "This sandbox environment has no valid Modal network policy. Update its network settings and run the task again.",
+ {"run_id": ctx.run_id, "sandbox_environment_id": ctx.sandbox_environment_id},
+ cause=error,
+ ) from error
+ config.outbound_domain_allowlist = list(policy.modal_domains)
+ config.network_policy_fingerprint = policy.fingerprint
+ return
+ config.outbound_domain_allowlist = list(ctx.modal_domain_allowlist)
+ config.network_policy_fingerprint = ctx.network_policy_fingerprint
def _resolve_sandbox_github_token(
@@ -664,30 +684,39 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr
f"{int(config.memory_gb * 1024)} MiB",
)
- # 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)
+ runtime = sandbox_runtime_label(use_vm_sandbox)
+ _apply_modal_network_policy(config, ctx, use_vm_sandbox=use_vm_sandbox)
+ if config.outbound_domain_allowlist is not None:
emit_agent_log(
ctx.run_id,
"debug",
- f"Using Modal outbound_domain_allowlist ({len(config.outbound_domain_allowlist)} domains) instead of agentsh",
+ f"Requesting Modal network enforcement for {len(config.outbound_domain_allowlist)} domains",
)
- runtime = sandbox_runtime_label(use_vm_sandbox)
- with StepTimer(
- "sandbox_creation",
- used_snapshot=prepared.used_snapshot,
- origin_product=ctx.origin_product,
- runtime=runtime,
- ) as sandbox_creation_timer:
- sandbox = Sandbox.create(config)
- # The provider's TTL clock starts here — the usage ledger anchors its
- # kill deadline on this boundary, not on when the row is opened below.
- sandbox_created_at = timezone.now()
- actual_used_snapshot = bool(
- (prepared.snapshot_external_id or prepared.snapshot_id) and sandbox.config.snapshot_restored
- )
- sandbox_creation_timer.set_used_snapshot(actual_used_snapshot)
+ try:
+ with StepTimer(
+ "sandbox_creation",
+ used_snapshot=prepared.used_snapshot,
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ ) as sandbox_creation_timer:
+ sandbox = Sandbox.create(config)
+ # The provider's TTL clock starts here — the usage ledger anchors its
+ # kill deadline on this boundary, not on when the row is opened below.
+ sandbox_created_at = timezone.now()
+ actual_used_snapshot = bool(
+ (prepared.snapshot_external_id or prepared.snapshot_id) and sandbox.config.snapshot_restored
+ )
+ sandbox_creation_timer.set_used_snapshot(actual_used_snapshot)
+ except Exception:
+ if config.outbound_domain_allowlist is not None:
+ record_network_enforcement(
+ "sandbox_creation_with_policy_request", runtime, "modal_requested", "failure"
+ )
+ raise
+ if config.outbound_domain_allowlist is not None:
+ emit_agent_log(ctx.run_id, "debug", "Modal sandbox created with network policy requested")
+ record_network_enforcement("sandbox_creation_with_policy_request", runtime, "modal_requested", "success")
if sandbox.config.image_fallback:
emit_agent_log(
ctx.run_id,
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 d370377ba813..71742fec95f3 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
@@ -23,6 +23,7 @@ from products.tasks.backend.temporal.metrics import (
StepTimer,
record_agent_server_session_init_ms,
record_boot_total_ms,
+ record_network_enforcement,
sandbox_runtime_label,
)
from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_run
@@ -190,8 +191,23 @@ class _LaunchParams:
def _agentsh_domains_for(ctx: TaskProcessingContext) -> list[str] | None:
- # Modal enforces egress at the edge (gVisor only), so agentsh is skipped only when it does.
- return None if (ctx.use_modal_network_allowlist and not ctx.use_modal_vm_sandbox) else ctx.allowed_domains
+ if ctx.agentsh_domain_allowlist is not None:
+ return list(ctx.agentsh_domain_allowlist)
+ return ctx.allowed_domains
+
+
+def _network_enforcement_observation(ctx: TaskProcessingContext) -> str:
+ if ctx.allowed_domains is None:
+ return "unrestricted"
+ if ctx.use_modal_network_allowlist:
+ return "modal_requested_sandbox_created_agentsh_ready"
+ return "agentsh_ready"
+
+
+def _record_network_enforcement_observation(ctx: TaskProcessingContext) -> None:
+ runtime = sandbox_runtime_label(ctx.use_modal_vm_sandbox)
+ observation = _network_enforcement_observation(ctx)
+ record_network_enforcement("startup_observed", runtime, observation, "success")
def _include_personal_mcp_for_task(task: Task) -> bool:
@@ -297,12 +313,12 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandbo
)
agentsh_domains = _agentsh_domains_for(ctx)
- if ctx.use_modal_network_allowlist and not ctx.use_modal_vm_sandbox and ctx.allowed_domains is not None:
+ if ctx.use_modal_network_allowlist 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)",
+ f"Enforcing network allowlist for '{environment_name}' via Modal and agentsh",
)
elif agentsh_domains is not None:
environment_name = ctx.sandbox_environment_name or ctx.sandbox_environment_id or "selected environment"
@@ -475,6 +491,8 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
) as ready_timer:
_invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=None, wait_for_health=True)
+ _record_network_enforcement_observation(ctx)
+
emit_agent_log(ctx.run_id, "debug", f"Agent server started at {input.sandbox_url}")
activity.logger.info(f"Agent server started at {input.sandbox_url} for task {ctx.task_id}")
@@ -574,6 +592,8 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
_emit_agent_server_log_tail(ctx, sandbox)
raise
+ _record_network_enforcement_observation(ctx)
+
emit_agent_log(ctx.run_id, "debug", f"Agent server ready at {input.sandbox_url}")
activity.logger.info(f"Agent server ready at {input.sandbox_url} for task {ctx.task_id}")
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
index bb2099573f18..907e6c86782b 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
@@ -868,9 +868,8 @@ class TestGetTaskProcessingContextActivity:
payload_mock.assert_not_called()
def test_modal_vm_sandbox_restricted_egress_overrides_default_base(self):
- # Restricted egress must win over the default-base allowlist: VM can't enforce Modal's
- # outbound domain allowlist, so a default-base origin with a custom domain list stays on
- # gVisor and the flag is never consulted (the egress gate returns before the fetch).
+ # A restricted run cannot use any VM routing source until the independent network-policy
+ # flag is enabled, so the runtime flag is not consulted on this path.
with patch(
VM_FLAG_PAYLOAD_TARGET,
return_value='{"default_base_origin_products": ["user_created"]}',
@@ -888,6 +887,54 @@ class TestGetTaskProcessingContextActivity:
payload_mock.assert_not_called()
+ def test_modal_vm_sandbox_restricted_egress_uses_vm_when_provider_policy_is_enabled(self):
+ with patch(
+ VM_FLAG_PAYLOAD_TARGET,
+ return_value='{"origin_products": ["user_created"]}',
+ ):
+ decision = _resolve_modal_vm_sandbox(
+ distinct_id="distinct-id",
+ organization_id="organization-id",
+ run_id="run-id",
+ origin_product="user_created",
+ allowed_domains=["github.com"],
+ use_modal_network_allowlist=True,
+ custom_image_available=True,
+ )
+
+ assert decision.use_vm_sandbox is True
+
+ def test_modal_vm_sandbox_restricted_state_override_requires_provider_policy(self):
+ with patch(VM_FLAG_PAYLOAD_TARGET, return_value=None) as payload_mock:
+ decision = _resolve_modal_vm_sandbox(
+ distinct_id="distinct-id",
+ organization_id="organization-id",
+ run_id="run-id",
+ origin_product="image_builder",
+ allowed_domains=["github.com"],
+ use_modal_network_allowlist=True,
+ state={"use_modal_vm_sandbox": True},
+ )
+
+ assert decision.use_vm_sandbox is True
+ payload_mock.assert_not_called()
+
+ def test_modal_vm_sandbox_restricted_default_base_requires_provider_policy(self):
+ with patch(
+ VM_FLAG_PAYLOAD_TARGET,
+ return_value='{"default_base_origin_products": ["user_created"]}',
+ ):
+ decision = _resolve_modal_vm_sandbox(
+ distinct_id="distinct-id",
+ organization_id="organization-id",
+ run_id="run-id",
+ origin_product="user_created",
+ allowed_domains=["github.com"],
+ use_modal_network_allowlist=True,
+ )
+
+ assert decision.use_vm_sandbox is True
+
def test_modal_vm_sandbox_false_state_override_forces_gvisor_over_default_base(self):
# A trusted server-set use_modal_vm_sandbox=False forces gVisor even when the org's payload
# would place this origin on the VM base; the bool override also skips the flag fetch.
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index c07e94cdf9ff..1164db54a72e 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -6,8 +6,10 @@ from products.tasks.backend.logic.services.sandbox import ExecutionResult, sandb
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.activities.start_agent_server import (
StartAgentServerInput,
+ _agentsh_domains_for,
_ensure_repository_on_disk,
_include_personal_mcp_for_task,
+ _network_enforcement_observation,
_record_boot_total,
_resolve_protected_base_branch,
start_agent_server,
@@ -45,6 +47,11 @@ def _context(
repository: str | None = None,
branch: str | None = None,
state: dict | None = None,
+ allowed_domains: list[str] | None = None,
+ agentsh_domain_allowlist: list[str] | None = None,
+ network_policy_fingerprint: str | None = None,
+ use_modal_vm_sandbox: bool = False,
+ use_modal_network_allowlist: bool = False,
) -> TaskProcessingContext:
return TaskProcessingContext(
task_id="task-id",
@@ -57,10 +64,95 @@ def _context(
distinct_id="distinct-id",
state=state,
sandbox_event_ingest_enabled=sandbox_event_ingest_enabled,
+ allowed_domains=allowed_domains,
+ agentsh_domain_allowlist=agentsh_domain_allowlist,
+ network_policy_fingerprint=network_policy_fingerprint,
+ use_modal_vm_sandbox=use_modal_vm_sandbox,
+ use_modal_network_allowlist=use_modal_network_allowlist,
_branch=branch,
)
+ "context,expected_observation,expected_agentsh_domains",
+ [
+ (_context(), "unrestricted", None),
+ (_context(allowed_domains=["example.com"]), "agentsh_ready", ["example.com"]),
+ (
+ _context(
+ allowed_domains=["example.com"],
+ agentsh_domain_allowlist=["example.com", "api.posthog.com"],
+ ),
+ "agentsh_ready",
+ ["example.com", "api.posthog.com"],
+ ),
+ (
+ _context(
+ allowed_domains=["example.com"],
+ agentsh_domain_allowlist=["example.com", "api.posthog.com"],
+ use_modal_network_allowlist=True,
+ ),
+ "modal_requested_sandbox_created_agentsh_ready",
+ ["example.com", "api.posthog.com"],
+ ),
+ (
+ _context(
+ allowed_domains=["example.com"],
+ agentsh_domain_allowlist=["example.com", "api.posthog.com"],
+ use_modal_vm_sandbox=True,
+ use_modal_network_allowlist=True,
+ network_policy_fingerprint="policy-hash",
+ ),
+ "modal_requested_sandbox_created_agentsh_ready",
+ ["example.com", "api.posthog.com"],
+ ),
+ ],
+)
+def test_network_enforcement_observation_matches_completed_checks(
+ context: TaskProcessingContext,
+ expected_observation: str,
+ expected_agentsh_domains: list[str] | None,
+) -> None:
+ assert _network_enforcement_observation(context) == expected_observation
+ assert _agentsh_domains_for(context) == expected_agentsh_domains
+
+
+async def test_start_failure_does_not_report_network_enforcement_observation(mocker) -> None:
+ context = _context(
+ allowed_domains=["example.com"],
+ agentsh_domain_allowlist=["example.com", "api.posthog.com"],
+ use_modal_vm_sandbox=True,
+ use_modal_network_allowlist=True,
+ network_policy_fingerprint="policy-hash",
+ )
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.Sandbox.get_by_id",
+ return_value=mocker.Mock(),
+ )
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server._prepare_launch",
+ return_value=mocker.Mock(),
+ )
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server._invoke_start_agent_server",
+ side_effect=RuntimeError("health check failed"),
+ )
+ record_observation = mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server._record_network_enforcement_observation"
+ )
+
+ with pytest.raises(RuntimeError, match="health check failed"):
+ await start_agent_server(
+ StartAgentServerInput(
+ context=context,
+ sandbox_id="sandbox-id",
+ sandbox_url="https://sandbox.example",
+ )
+ )
+
+ record_observation.assert_not_called()
+
+
def _mock_github_integration(mocker, pr_base: str | None):
integration = mocker.Mock()
integration.access_token_expired.return_value = False
diff --git a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py
index 7c0ffaf2c9d3..b540f4e975fb 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py
@@ -6,12 +6,14 @@ from unittest.mock import MagicMock, patch
from django.test import override_settings
-from products.tasks.backend.logic.services.sandbox import ExecutionResult
+from products.tasks.backend.exceptions import SandboxNetworkPolicyError
+from products.tasks.backend.logic.services.sandbox import ExecutionResult, SandboxConfig
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.activities.provision_sandbox import (
CheckoutBranchInSandboxInput,
CheckoutBranchInSandboxOutput,
PrepareSandboxForRepositoryOutput,
+ _apply_modal_network_policy,
_build_environment_variables,
_build_sandbox_tags,
_to_modal_domain_allowlist,
@@ -126,7 +128,7 @@ def test_build_sandbox_tags_drops_none_values():
["*.posthog.com", "api.anthropic.com"],
),
(
- ["github.com", "localhost", "host.docker.internal", "registry.npmjs.org"],
+ ["github.com", "registry.npmjs.org"],
["github.com", "registry.npmjs.org", "*.posthog.com", "api.anthropic.com"],
),
(
@@ -187,6 +189,75 @@ def test_to_modal_domain_allowlist_still_admits_hyphenated_host():
assert "ai-gateway.dev.posthog.dev" in _to_modal_domain_allowlist([])
+def test_restricted_vm_cannot_bypass_modal_network_flag() -> None:
+ config = SandboxConfig(name="restricted-vm", vm_runtime=True)
+ context = _context(
+ allowed_domains=["example.com"],
+ agentsh_domain_allowlist=["example.com", "api.posthog.com"],
+ modal_domain_allowlist=["example.com", "api.posthog.com"],
+ network_policy_fingerprint="policy-hash",
+ use_modal_vm_sandbox=True,
+ use_modal_network_allowlist=False,
+ )
+
+ with pytest.raises(SandboxNetworkPolicyError) as error:
+ _apply_modal_network_policy(config, context, use_vm_sandbox=True)
+
+ assert error.value.non_retryable is True
+ assert config.outbound_domain_allowlist is None
+
+
+def test_restricted_vm_applies_compiled_modal_policy() -> None:
+ config = SandboxConfig(name="restricted-vm", vm_runtime=True)
+ context = _context(
+ allowed_domains=[],
+ agentsh_domain_allowlist=["api.posthog.com"],
+ modal_domain_allowlist=["api.posthog.com"],
+ network_policy_fingerprint="policy-hash",
+ use_modal_vm_sandbox=True,
+ use_modal_network_allowlist=True,
+ )
+
+ _apply_modal_network_policy(config, context, use_vm_sandbox=True)
+
+ assert config.outbound_domain_allowlist == ["api.posthog.com"]
+ assert config.network_policy_fingerprint == "policy-hash"
+
+
+@override_settings(DEBUG=False)
+def test_restricted_vm_recompiles_modal_policy_for_legacy_context() -> None:
+ config = SandboxConfig(name="restricted-vm", vm_runtime=True)
+ context = _context(
+ allowed_domains=["example.com"],
+ use_modal_vm_sandbox=True,
+ use_modal_network_allowlist=True,
+ )
+
+ _apply_modal_network_policy(config, context, use_vm_sandbox=True)
+
+ assert config.outbound_domain_allowlist is not None
+ assert "example.com" in config.outbound_domain_allowlist
+ assert "*.posthog.com" in config.outbound_domain_allowlist
+ assert "api.anthropic.com" in config.outbound_domain_allowlist
+ assert config.network_policy_fingerprint is not None
+
+
+@override_settings(DEBUG=False)
+def test_restricted_vm_rejects_invalid_legacy_context() -> None:
+ config = SandboxConfig(name="restricted-vm", vm_runtime=True)
+ context = _context(
+ allowed_domains=["https://example.com/path"],
+ use_modal_vm_sandbox=True,
+ use_modal_network_allowlist=True,
+ )
+
+ with pytest.raises(SandboxNetworkPolicyError) as error:
+ _apply_modal_network_policy(config, context, use_vm_sandbox=True)
+
+ assert error.value.non_retryable is True
+ assert config.outbound_domain_allowlist is None
+
+
@patch(f"{_PROVISION}.get_git_identity_env_vars", return_value={})
@patch(f"{_PROVISION}.get_sandbox_jwt_public_key", return_value="pub")
@patch(f"{_PROVISION}.get_sandbox_api_url", return_value="https://api.example")
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index bbda25f6998e..f69846fb53f3 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -10948,6 +10948,20 @@ class TestSandboxEnvironmentAPI(BaseTaskAPITest):
self.assertIn("api.example.com", data["effective_domains"])
self.assertIn("github.com", data["effective_domains"])
+ def test_create_environment_rejects_invalid_allowed_domain(self):
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Invalid network policy",
+ "network_access_level": "custom",
+ "allowed_domains": ["https://example.com"],
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["attr"], "allowed_domains")
+
def test_create_environment_sets_created_by(self):
response = self.client.post(
self.base_url,
diff --git a/products/tasks/backend/tests/test_presentation_serializers.py b/products/tasks/backend/tests/test_presentation_serializers.py
index 3cc7d2446dc7..29917d6a7124 100644
--- a/products/tasks/backend/tests/test_presentation_serializers.py
+++ b/products/tasks/backend/tests/test_presentation_serializers.py
@@ -6,13 +6,53 @@ from django.test import SimpleTestCase
from parameterized import parameterized
+from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.presentation.serializers import (
+ SandboxEnvironmentWriteSerializer,
TaskRunCreateRequestSerializer,
TaskRunLivingArtifactCreateRequestSerializer,
TaskWriteSerializer,
)
+class TestSandboxEnvironmentWriteSerializer(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("scheme", "https://example.com"),
+ ("path", "example.com/path"),
+ ("port", "example.com:443"),
+ ("ip", "127.0.0.1"),
+ ("malformed_wildcard", "api.*.example.com"),
+ ]
+ )
+ def test_rejects_domains_that_cannot_be_enforced(self, _name: str, domain: str) -> None:
+ serializer = SandboxEnvironmentWriteSerializer(data={"name": "Restricted", "allowed_domains": [domain]})
+
+ assert not serializer.is_valid()
+ assert "allowed_domains" in serializer.errors
+
+ def test_normalizes_valid_domains(self) -> None:
+ serializer = SandboxEnvironmentWriteSerializer(
+ data={"name": "Restricted", "allowed_domains": [" EXAMPLE.com ", "example.com"]}
+ )
+
+ assert serializer.is_valid(), serializer.errors
+ assert serializer.validated_data["allowed_domains"] == ["example.com"]
+
+ def test_rejects_too_many_allowed_domains(self) -> None:
+ domains = [f"host-{index}.example.com" for index in range(tasks_facade.MAX_SANDBOX_ALLOWED_DOMAINS + 1)]
+ serializer = SandboxEnvironmentWriteSerializer(data={"name": "Restricted", "allowed_domains": domains})
+
+ assert not serializer.is_valid()
+ assert serializer.errors["allowed_domains"][0].code == "max_length"
+
+ def test_facade_rejects_too_many_allowed_domains(self) -> None:
+ domains = [f"host-{index}.example.com" for index in range(tasks_facade.MAX_SANDBOX_ALLOWED_DOMAINS + 1)]
+
+ with self.assertRaisesRegex(ValueError, "You can allow up to 100 domains"):
+ tasks_facade.normalize_sandbox_allowed_domains(domains)
+
+
class TestTaskWriteSerializerOriginProduct(SimpleTestCase):
@parameterized.expand(
[
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index 96ff8e24a843..ef0b372f0a01 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -176,6 +176,7 @@ class TestWarmTaskSandbox(APIBaseTest):
run = TaskRun.objects.get(id=result.run_id)
assert run.state["sandbox_environment_id"] == str(sandbox_environment.id)
assert run.state["custom_image_id"] == str(custom_image.id)
+ assert "use_modal_network_allowlist" not in run.state
def test_births_draft_task_and_returns_warm_dto(self):
def fake_warm(self_warmer, **kwargs):
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 77b010023de4..0da815226e2a 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -873,6 +873,7 @@ export interface SandboxEnvironmentWriteApi {
network_access_level?: NetworkAccessLevelEnumApi
/**
* Allowed domains for custom network access.
+ * @maxItems 100
* @items.maxLength 255
*/
allowed_domains?: string[]
@@ -911,6 +912,7 @@ export interface PatchedSandboxEnvironmentWriteApi {
network_access_level?: NetworkAccessLevelEnumApi
/**
* Allowed domains for custom network access.
+ * @maxItems 100
* @items.maxLength 255
*/
allowed_domains?: string[]
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 0f6a51c1ed24..06eeb2db49d8 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -768,6 +768,8 @@ export const sandboxCreateBodyNameMax = 255
export const sandboxCreateBodyNetworkAccessLevelDefault = `full`
export const sandboxCreateBodyAllowedDomainsItemMax = 255
+export const sandboxCreateBodyAllowedDomainsMax = 100
+
export const sandboxCreateBodyIncludeDefaultDomainsDefault = false
export const sandboxCreateBodyRepositoriesItemMax = 255
@@ -785,6 +787,7 @@ export const SandboxCreateBody = /* @__PURE__ */ zod
),
allowed_domains: zod
.array(zod.string().max(sandboxCreateBodyAllowedDomainsItemMax))
+ .max(sandboxCreateBodyAllowedDomainsMax)
.optional()
.describe('Allowed domains for custom network access.'),
include_default_domains: zod
@@ -820,6 +823,8 @@ export const sandboxPartialUpdateBodyNameMax = 255
export const sandboxPartialUpdateBodyNetworkAccessLevelDefault = `full`
export const sandboxPartialUpdateBodyAllowedDomainsItemMax = 255
+export const sandboxPartialUpdateBodyAllowedDomainsMax = 100
+
export const sandboxPartialUpdateBodyIncludeDefaultDomainsDefault = false
export const sandboxPartialUpdateBodyRepositoriesItemMax = 255
@@ -841,6 +846,7 @@ export const SandboxPartialUpdateBody = /* @__PURE__ */ zod
),
allowed_domains: zod
.array(zod.string().max(sandboxPartialUpdateBodyAllowedDomainsItemMax))
+ .max(sandboxPartialUpdateBodyAllowedDomainsMax)
.optional()
.describe('Allowed domains for custom network access.'),
include_default_domains: zod
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 615dc9d23ba4..65468a0063b7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -59339,6 +59339,7 @@ export namespace Schemas {
network_access_level?: NetworkAccessLevelEnum;
/**
* Allowed domains for custom network access.
+ * @maxItems 100
* @items.maxLength 255
*/
allowed_domains?: string[];
@@ -68906,6 +68907,7 @@ export namespace Schemas {
network_access_level?: NetworkAccessLevelEnum;
/**
* Allowed domains for custom network access.
+ * @maxItems 100
* @items.maxLength 255
*/
allowed_domains?: string[];