fix: harden ContainerCodeExecutor sandbox by default

Merge https://github.com/google/adk-python/pull/6074

## Summary

`ContainerCodeExecutor` runs model-generated code, which can be influenced by untrusted input (e.g. via prompt injection). It starts the container with default Docker networking and no capability restrictions, so the executed code can reach the cloud metadata endpoint (`169.254.169.254`) — which yields the host service-account token — reach internal services, or escalate privileges.

This is inconsistent with the isolation posture of every other ADK code executor:

- `GkeCodeExecutor` runs under gVisor with `cap_drop: ["ALL"]`, non-root, read-only root filesystem, and a strict security context.
- `BuiltInCodeExecutor` / `VertexAiCodeExecutor` / `AgentEngineSandboxCodeExecutor` run in managed server-side sandboxes.
- `UnsafeLocalCodeExecutor` is explicitly documented as unsafe.

`ContainerCodeExecutor` was the only executor running code with full network access and no isolation flags or warning.

## Change

- Start the container with networking disabled by default. This is exposed as a configurable `network_enabled` field — set it to `True` to re-enable networking when the executed code is trusted.
- Drop all Linux capabilities (`cap_drop=["ALL"]`) and forbid privilege escalation (`security_opt=["no-new-privileges"]`), matching `GkeCodeExecutor`.
- Document the security posture in the class docstring and point users to the sandboxed executors for untrusted code.
- Add unit tests covering the hardened defaults and the opt-in network path.

## Compatibility

Code that legitimately needs network access can opt back in with `ContainerCodeExecutor(..., network_enabled=True)`. Dropping capabilities and `no-new-privileges` do not affect normal Python code execution.

Co-authored-by: George Weale <gweale@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/6074 from adilburaksen:harden/container-code-executor-network f7eaec252d2369d710eb54ea6c51b2bc4e525e7a
PiperOrigin-RevId: 938260811
This commit is contained in:
Adil Burak Şen
2026-06-25 16:41:17 -07:00
committed by Copybara-Service
parent 4aeb7e2697
commit 0a9ce0f691
3 changed files with 89 additions and 0 deletions
+1
View File
@@ -195,6 +195,7 @@ optional-dependencies.test = [
"anyio>=4.9,<5",
"beautifulsoup4>=3.2.2",
"crewai[tools]; python_version>='3.11' and python_version<'3.12'", # For CrewaiTool tests; chromadb/pypika fail on 3.12+
"docker>=7", # For ContainerCodeExecutor tests
"e2b>=2,<3",
"gepa>=0.1",
"google-antigravity>=0.1,<0.2",
@@ -37,6 +37,15 @@ DEFAULT_IMAGE_TAG = 'adk-code-executor:latest'
class ContainerCodeExecutor(BaseCodeExecutor):
"""A code executor that uses a custom container to execute code.
Security note: this executor runs model-generated code, which may be
influenced by untrusted input (e.g. via prompt injection). By default the
container is started with networking disabled and all Linux capabilities
dropped so that the executed code cannot reach the network (including the
cloud metadata endpoint at ``169.254.169.254``) or escalate privileges. For
stronger, kernel-level isolation of untrusted code prefer
``GkeCodeExecutor`` (gVisor) or a managed executor
(``VertexAiCodeExecutor`` / ``AgentEngineSandboxCodeExecutor``).
Attributes:
base_url: Optional. The base url of the user hosted Docker client.
image: The tag of the predefined image or custom image to run on the
@@ -44,6 +53,9 @@ class ContainerCodeExecutor(BaseCodeExecutor):
docker_path: The path to the directory containing the Dockerfile. If set,
build the image from the dockerfile path instead of using the predefined
image. Either docker_path or image must be set.
network_enabled: Whether to start the container with networking enabled.
Defaults to False. Set to True only if the executed code must make network
requests and you trust it.
"""
base_url: Optional[str] = None
@@ -64,6 +76,17 @@ class ContainerCodeExecutor(BaseCodeExecutor):
predefined image. Either docker_path or image must be set.
"""
network_enabled: bool = False
"""
Whether to start the code execution container with networking enabled.
Defaults to False so that untrusted, model-generated code cannot reach the
network -- in particular the cloud metadata endpoint at 169.254.169.254
(which can yield the host's service-account credentials), internal services,
or arbitrary exfiltration destinations. Set to True only if the executed
code must make network requests and you trust it.
"""
# Overrides the BaseCodeExecutor attribute: this executor cannot be stateful.
stateful: bool = Field(default=False, frozen=True, exclude=True)
@@ -183,6 +206,13 @@ class ContainerCodeExecutor(BaseCodeExecutor):
image=self.image,
detach=True,
tty=True,
# Harden the sandbox for untrusted, model-generated code: no network
# (blocks metadata/SSRF/exfil), drop all Linux capabilities, and
# forbid privilege escalation. Networking can be re-enabled via
# `network_enabled=True` when the executed code is trusted.
network_disabled=not self.network_enabled,
cap_drop=['ALL'],
security_opt=['no-new-privileges'],
)
logger.info('Container %s started.', self._container.id)
@@ -0,0 +1,58 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the ContainerCodeExecutor container hardening defaults."""
from unittest import mock
from google.adk.code_executors.container_code_executor import ContainerCodeExecutor
def _mock_docker_client():
"""Returns a mock Docker client whose container passes python verification."""
client = mock.MagicMock()
container = mock.MagicMock()
# `_verify_python_installation` runs `exec_run(['which', 'python3'])` and
# checks `exit_code == 0`.
container.exec_run.return_value = mock.MagicMock(exit_code=0)
client.containers.run.return_value = container
return client
@mock.patch('google.adk.code_executors.container_code_executor.docker')
def test_container_is_hardened_by_default(mock_docker):
"""Networking is disabled and privileges are dropped by default."""
client = _mock_docker_client()
mock_docker.from_env.return_value = client
ContainerCodeExecutor(image='test-image')
_, kwargs = client.containers.run.call_args
# Untrusted model-generated code must not be able to reach the network
# (e.g. the cloud metadata endpoint) or escalate privileges by default.
assert kwargs['network_disabled']
assert kwargs['cap_drop'] == ['ALL']
assert kwargs['security_opt'] == ['no-new-privileges']
@mock.patch('google.adk.code_executors.container_code_executor.docker')
def test_container_network_can_be_explicitly_enabled(mock_docker):
"""Networking is left enabled when the caller opts in."""
client = _mock_docker_client()
mock_docker.from_env.return_value = client
ContainerCodeExecutor(image='test-image', network_enabled=True)
_, kwargs = client.containers.run.call_args
assert not kwargs['network_disabled']