All Products
Search
Document Center

Container Compute Service:Manage Agent Sandbox ingress traffic

Last Updated:Oct 15, 2026

SandboxGateway separates control plane traffic from data plane traffic for Agent Sandbox, and supports routing rules, ingress traffic authentication, and other capabilities. This enables access control for ingress traffic and helps prevent control plane component issues from affecting business communication.

Background

Starting with ack-sandbox-manager add-on v0.5.2, the SandboxGateway feature is available.

By default, Ingress forwards both control plane (api.{domain}) and data plane (*.{domain}) traffic to the sandbox-manager service. Because the control plane and data plane are not physically separated, an issue with a control plane component can affect the agent's business communication.

Once you switch the traffic, the sandbox-gateway service forwards data plane traffic. This decoupling reduces the impact of control plane failures on business data transfer.

Applicable scope

  • On the cluster Add-ons page, the ack-sandbox-manager add-on is upgraded to v0.5.2 or later.

  • In the sandbox-system namespace, the sandbox-gateway workload has at least one replica and its pods are in the ready state.

  • Inbound traffic on Transmission Control Protocol (TCP) port 7788 is allowed in the Control Plane Security Group, so that Ingress can forward traffic to sandbox-gateway.

  • If you use a TrafficPolicy to manage the network policy of the Sandbox, allow inbound traffic from the sandbox-gateway Service in the Sandbox-side policy. For more information, see Manage agent network access with TrafficPolicy.

How it works

After you switch the traffic, Ingress distributes traffic based on domain name matching rules:

  • Control plane traffic: Traffic accessed through api.{domain} is processed by sandbox-manager.

  • Data plane traffic: Traffic accessed through *.{domain} is handled by sandbox-gateway. The sandbox-gateway service queries its local routing registry and forwards requests to the target Sandbox Pod based on the routing rules.

The following table describes the traffic forwarding paths:

Domain name

Path

Forwarding service

Description

api.{domain}

/*

sandbox-manager:8080

Forwards control plane traffic.

*.{domain}

/*

sandbox-gateway:7788

Forwards data plane traffic.

image

Preparation

Verify the connectivity of SandboxGateway.

  1. Evaluate your business traffic and adjust the SandboxGateway instance configuration as needed to meet your workload requirements. For more information, see Limitations.

  2. On the details page of the target cluster, go to Workloads > Deployments. Switch to the sandbox-system namespace, and then click the sandbox-gateway workload name to open its details page. Verify that the replica count is 1 or greater and that the pods are in a ready state.

  3. Obtain the ClusterIP of the sandbox-gateway Service:

    kubectl get svc -n sandbox-system sandbox-gateway -o jsonpath='{.spec.clusterIP}'
  4. Send a request based on the following template. Replace the placeholders before you run the command:

    curl -v \
      --resolve "<PORT>-<NAMESPACE>--<NAME>.<DOMAIN>:7788:<SANDBOX-GATEWAY-SVC-IP>" \
      -H "e2b-sandbox-id: <NAMESPACE>--<NAME>" \
      -H "e2b-sandbox-port: <PORT>" \
      -H "X-Access-Token: <SANDBOX-TOKEN>" \
      http://<PORT>-<NAMESPACE>--<NAME>.<DOMAIN>:7788/health
    Expected output: HTTP/1.1 204 No Content, which indicates that sandbox-gateway has forwarded the request to the health check endpoint of envd in the Sandbox Pod.

    The placeholders are described as follows:

    • <PORT>: the port on which the Sandbox provides services. If no other service is enabled, use the default port of envd, which is 49983.

    • <NAMESPACE>: the namespace of the Sandbox that you want to verify.

    • <NAME>: the name of the Sandbox that you want to verify.

    • <DOMAIN>: the wildcard domain name that points to the gateway.

    • <SANDBOX-GATEWAY-SVC-IP>: the ClusterIP of the sandbox-gateway Service that you obtained in step 3.

    • <SANDBOX-TOKEN>: if Ingress traffic authentication is enabled, specify the envdAccessToken of the Sandbox. Otherwise, omit this request header.

This verification covers only the connectivity between sandbox-gateway and the Sandbox Pod. You must allow traffic from Ingress to sandbox-gateway in the security group.

Switching traffic

Important

Switching data plane traffic may interrupt your services. Perform the switch during off-peak hours. Before the switch, evaluate the traffic impact and complete the pre-switch verification described in Preparation to avoid network issues.

  1. In the console, go to the Add-ons page, select Configuration for ack-sandbox-manager, and switch dataplaneService to sandbox-gateway.

  2. (Optional) To access sandbox-manager over HTTP only (no Transport Layer Security (TLS) certificate is required), clear the Whether to enable TLS for ingress checkbox on the same configuration page.

  3. Verify that the forwarding path is switched to sandbox-gateway in the console of the associated load balancer.

    1. Find the associated Application Load Balancer (ALB) instance name in the Ingress resource:

      Console

      On the details page of the target cluster, go to Network > Ingresses. Switch to the sandbox-system namespace and view the Endpoint of the sandbox-manager Ingress. The prefix of the endpoint (for example, alb-xxx) is the name of the ALB instance.

      kubectl

      kubectl get ingress -nsandbox-system sandbox-manager -o jsonpath='{.status.loadBalancer.ingress[0].hostname}' | sed -E 's/^(alb-[^.]+).*/\1/'
    2. Go to the ALB console. Click the target instance name, and then go to Listener > ingress-auto-listener-443 > Forwarding Rules. Confirm that the forwarding action is changed to sandbox-system-sandbox-gateway-7788.

  4. In the left navigation bar of the target cluster, select Operations > Log Center, and switch to the Application Logs tab.

  5. On the Application Logs page, set the Logstore to ack-sandbox-gateway. Check the access log and runtime log for any abnormal status codes, such as response_code values outside the 2xx or 1xx range. To collect metrics yourself, see Metric reporting.

    To roll back the change, see How to roll back on service failure.

    Field descriptions

    Starting with the ack-sandbox-manager add-on v0.6.5, the sandbox-gateway access log provides more fields. The following table describes these fields. Earlier add-on versions may not include all fields. Check the actual log output in your environment.

    Field

    Description

    Request identifier and routing fields

    start_time

    The UTC timestamp when Envoy starts processing the request (receives the request line). By default, the timestamp is in ISO-8601 format with millisecond precision.

    method

    The HTTP method of the request, such as GET, POST, or CONNECT.

    path

    The full request path, including query parameters.

    user_agent

    The value of the User-Agent request header. The value is - if the header is missing.

    request_id

    The value of the x-request-id request header. Envoy automatically generates this ID if the client does not provide one. Use this ID to correlate logs across components.

    authority

    The HTTP/2 :authority pseudo-header (equivalent to the Host header in HTTP/1.1).

    route_name

    The name of the route that the request matched.

    requested_server_name

    The Server Name Indication (SNI) value carried in the TLS handshake. If the client does not carry SNI, the value is recorded as SNI_ONLY.

    Protocol and response fields

    protocol

    The protocol on the downstream side (from the client to sandbox-gateway), such as HTTP/1.1, HTTP/2, or HTTP/3. The value is empty if the connection does not enter the HTTP parsing phase.

    upstream_protocol

    The protocol on the upstream side (from sandbox-gateway to the Sandbox Pod), such as HTTP/1.1, HTTP/2, or HTTP/3.

    response_code

    The HTTP status code returned to the client. A value of 0 indicates that no response was sent, such as when the downstream client disconnects before response headers are sent.

    response_code_details

    Additional details about the response code, which indicate which component set the response and the reason.

    response_flags

    A code indicating special response conditions. Common values include: - (none), UH (no healthy upstream available), UF (upstream connection failure), UT (upstream timeout), DC (downstream connection termination).

    connection_termination_details

    Layer 4 connection termination details, which indicate why Envoy terminated the connection.

    Duration fields

    duration_ms

    The total request duration, in ms. The duration is measured from the start of the request to when Envoy sends the last byte to the downstream client, or to when a local reply is completed.

    request_duration_ms

    The duration from the start of the request to when Envoy finishes receiving the request body from the downstream client, in ms.

    request_tx_duration_ms

    The duration from the start of the request to when Envoy sends the last byte of the request to the upstream, in ms.

    response_duration_ms

    The duration from the start of the request to when Envoy reads the first response byte from the upstream, in ms.

    response_tx_duration_ms

    The duration from when Envoy reads the first response byte from the upstream to when it sends the last byte to the downstream client, in ms.

    Data transfer fields

    bytes_received

    The number of bytes in the request body received from the downstream client, excluding headers.

    bytes_sent

    The number of bytes in the response body sent to the downstream client, excluding headers.

    upstream_wire_bytes_sent

    The total number of bytes that Envoy sends to the upstream, including protocol overhead such as request headers.

    upstream_wire_bytes_received

    The total number of bytes that Envoy receives from the upstream, including protocol overhead such as response headers.

    downstream_wire_bytes_sent

    The total number of bytes that Envoy sends to the downstream client, including protocol overhead such as response headers.

    downstream_wire_bytes_received

    The total number of bytes that Envoy receives from the downstream client, including protocol overhead such as request headers.

    Connection fields

    upstream_cluster

    The name of the cluster to which the upstream host belongs. If alt_stat_name is configured for the cluster, its value is used.

    upstream_host

    The selected upstream endpoint address in IP:port format. For sandbox traffic, this is the IP address and port of the Sandbox Pod selected by the filter. A value of - indicates that no upstream was selected, such as for a local reply.

    upstream_local_address

    The local socket address that Envoy uses for the upstream connection, in IP:port format. This helps correlate with conntrack and Pod networking tools on the gateway's node.

    upstream_request_attempt_count

    The number of attempts that Envoy made to send the request to the upstream. A value of 0 indicates that Envoy did not attempt to access the upstream.

    downstream_local_address

    The local address of the downstream connection on the Envoy side, in IP:port format.

    downstream_remote_address

    The client socket address as seen by Envoy, in IP:port format. The value may be affected by the Proxy Protocol or X-Forwarded-For.

Limitations

By default, SandboxGateway is deployed with three replicas, each using an instance specification of 4 vCPU and 8 GiB. A single replica instance provides a total inbound and outbound bandwidth of 1.5 Gbit/s, which can support approximately 93.75 MB/s of service traffic. The total inbound and outbound bandwidth supported by a single ACS instance is subject to the ACS instance specification. For higher performance, see Adjust the SandboxGateway specification.

The capacity of a single 4 vCPU and 8 GiB instance is calculated as follows: 1.5 Gbit/s / 2 (for both inbound and outbound traffic) / 8 (for unit conversion) ≈ 93.75 MB/s.
The preceding data represents a theoretical maximum. Alibaba Cloud does not guarantee this performance level, which may vary based on your specific use case. Monitor your services for packet loss or check the gateway logs for 502 status codes to assess the actual performance.

Advanced operations

Configure routing rules

When processing a request, SandboxGateway first attempts a header-based match and then falls back to a domain-based match.

Header-based routing (matched first)

Header

Default name

Required

Description

Sandbox ID header

e2b-sandbox-id

Yes

The Sandbox ID.

Sandbox port header

e2b-sandbox-port

No

The target port within the Sandbox Pod. The default is 49983.

Example:

curl https://sandbox.domain/sandboxes \
  -H "e2b-sandbox-id: default--my-sandbox" \
  -H "e2b-sandbox-port: 49983"

Domain-based routing

If the Sandbox ID header is missing, SandboxGateway attempts to match the Host or authority field by using the {port}-{namespace}--{name}.{domain} format.

Note

Due to the DNS name format limits, the leftmost label of a domain name, {port}-{namespace}--{name}, cannot exceed 63 characters in total length. Otherwise, domain-based routing does not take effect.

Field

Description

Example

{port}

The target port on the Sandbox Pod.

49983

{namespace}

The Kubernetes namespace of the Sandbox.

default

{name}

The name of the Sandbox custom resource (CR).

my-app-v1

{domain}

The wildcard domain name that points to the gateway.

sandbox.example.com

Example:

curl https://3000-default--my-sandbox.domain \
  -H "Host: 3000-default--my-sandbox.domain"

Metric reporting

The sandbox-gateway service exposes a metrics endpoint on port 9902. This endpoint provides monitoring metrics in the Prometheus standard format. Collect metrics from the http://<pod_ip>:9902/metrics address (accessible only within the cluster).

Graceful shutdown

SandboxGateway supports graceful shutdown of instances. When an instance is shut down, the preStop hook calls POST http://127.0.0.1:9901/drain_listeners?graceful, which allows in-flight requests to complete as much as possible before the container exits. This reduces the impact of instance scale-in and upgrade operations on your services.

Ingress traffic authentication

Starting with ack-sandbox-manager add-on v0.6.6, sandbox-gateway can validate the access token of inbound requests. sandbox-gateway provides the following two authentication methods. Select a method based on how you manage business credentials:

  • Static access token authentication (v0.6.6 and later): Validates the X-Access-Token request header. The token value is the envdAccessToken returned in the response body when the Sandbox is created. This method applies if the credential is static and shares the same lifecycle as the Sandbox.

  • JWT-based dynamic token authentication (v0.6.8 and later) : Validates the E2B-Traffic-Access-Token request header. The token value is a JSON Web Token (JWT) issued by the ack-agent-identity add-on. This method applies if you need replay protection and multi-tenant isolation, and want credentials to expire within a short validity period configured in the issuance parameters.

Authentication method comparison

Dimension

Static access token authentication

JWT-based dynamic token authentication

Credential purpose

Reuses the access credential of the runtime or envd.

A dedicated access credential for the data plane proxy.

Token format

Random universally unique identifier (UUID).

Asymmetrically signed compact JWT.

Request header

X-Access-Token

E2B-Traffic-Access-Token

Issuer

sandbox-manager

The ack-agent-identity add-on

Validation method

Constant-time string comparison on the token.

Local validation of the JWT signature, the standard claims, and the binding to the Sandbox ID or UID.

Validity period

Remains static within the Sandbox lifecycle.

Controlled by the issuer parameters. The default validity period is 100 years. After the token expires, it can be reissued.

Replay window after leakage

Lasts until the Sandbox is destroyed.

Limited to the JWT validity period.

Persistence

Written to the agents.kruise.io/runtime-access-token annotation of the Sandbox CR.

Not written to the Sandbox CR. Retained only in the Claim response object.

How to enable

After you enable this method in the console, it takes effect for all access traffic. The scope that applies when it is selected together with JWT validation varies based on the ack-sandbox-manager version. For more information, see corresponding mapping between add-on versions and checkboxes.

After you enable this method in the console, it takes effect on a Sandbox only if the client passes the metadata key-value pair security.agents.kruise.io/enable-jwt-auth: "true" when creating the Sandbox.

Token retrieval field

The envdAccessToken field in the creation response.

The trafficAccessToken field in the creation response.

SDK usage

For the envd port, the E2B SDK automatically injects the header. For non-envd ports, you must set the request header manually.

For all ports, you must set the request header manually, or inject the header as described in the following Monkey Patch solution.

Validation failure response

HTTP 401.

HTTP 403.

Static access token authentication

Procedure

Important

After you enable ingress traffic authentication, existing traffic that does not carry the authentication request header is rejected with HTTP 401. Make sure that all clients send the authentication request header before you enable this feature. Make the change during off-peak hours.

  1. On the cluster Add-ons page, click Configuration for ack-sandbox-manager, select Whether to enable ingress traffic authentication, and then click Save.

    sandbox-gateway must restart to apply the change. During the restart, established persistent connections are disconnected. Service resumes after clients reconnect. Evaluate the impact of the change in advance.
  2. Create a Sandbox by using the E2B SDK, and then obtain _envd_access_token from the Sandbox object. The following example uses the Python SDK:

    Important

    _envd_access_token is a critical security credential for accessing the Agent Sandbox data plane. If the token is leaked, your business data and sandbox environment may be exposed to security risks. Store the token in encrypted form and never write it in plaintext to code or logs.

    from e2b_code_interpreter import Sandbox
    
    sbx = Sandbox.create(template="code-interpreter")
    
    # Obtain the token from the private attribute of the Sandbox instance (the Python SDK does not mask the token).
    access_token = sbx._envd_access_token
    When you call native SDK methods such as sbx.run_code, sbx.commands.run, and sbx.files.*, the E2B SDK automatically attaches _envd_access_token to the X-Access-Token request header. Manually include this request header only when you access a self-hosted HTTP service inside the Sandbox, such as a service on port 3000, as described in Step 3.
  3. When you access a self-hosted HTTP service inside the Sandbox, include the X-Access-Token request header. Example:

    curl https://<YOUR-DOMAIN>/ \
      -H "X-Access-Token: <ENVD-ACCESS-TOKEN>" \
      -H "e2b-sandbox-id: <NAMESPACE>--<NAME>" \
      -H "e2b-sandbox-port: <PORT>"
    The combination of request headers (header-based routing and domain-based routing) follows the routing matching rules of SandboxGateway. For more information, see Configure routing rules.

Authentication failure response

If the token carried by the request fails the validation, sandbox-gateway returns HTTP 401. The response body is:

unauthorized: invalid or missing access token

Compatibility

  • Ingress traffic authentication is disabled by default. Upgrading the add-on does not affect existing traffic. You must enable this feature manually.

  • If no envdAccessToken is generated when the Sandbox is created, sandbox-gateway skips token validation and forwards the request directly.

JWT-based dynamic token authentication

Applicable scope

After you enable this feature, sandbox-gateway validates the E2B-Traffic-Access-Token request header of each inbound request. The token value is the trafficAccessToken field in the response body returned when the Sandbox is created.

  • The ack-sandbox-manager add-on is upgraded to v0.6.8 or later.

  • The ack-agent-identity add-on (v0.4.1-rc.1 or later) is installed, and Enable token delegation is selected. This add-on issues and validates JWTs.

Procedure

Important

After you enable ingress traffic authentication, existing traffic that does not carry the authentication request header is rejected with HTTP 403. Make the change during off-peak hours.

  1. On the cluster Add-ons page, click Configuration for ack-sandbox-manager, select the following configuration items based on the add-on version, and then click Save.

    • Whether to enable JWT (TrafficAccessToken) verification

    • IdentityProvider plays a critical role in securing OpenKruise Agents through sandboxing

    Note

    The mapping between add-on versions and checkboxes, and the resulting differences, are as follows:

    • v0.6.12 and later: Select only Whether to enable JWT (TrafficAccessToken) verification to enable JWT authentication. If you also select Whether to enable ingress traffic authentication, for Sandboxes that do not enable enable-jwt-auth through metadata, the gateway falls back to X-Access-Token (static access token) authentication.

    • Versions earlier than v0.6.12: Select both Whether to enable ingress traffic authentication and Whether to enable JWT (TrafficAccessToken) verification. For Sandboxes that do not enable enable-jwt-auth through metadata, no gateway authentication is enabled.

    sandbox-gateway must restart to apply the change. During the restart, established persistent connections are disconnected. Service resumes after clients reconnect. Evaluate the impact of the change in advance.
  2. Enable JWT authentication explicitly by passing the metadata parameter when you create a Sandbox, and then obtain trafficAccessToken from the response. The following example uses the E2B Python SDK:

    Important

    E2B-Traffic-Access-Token is a critical security credential for accessing the Agent Sandbox data plane. If the token is leaked, your business data and sandbox environment may be exposed to security risks. Store the token in encrypted form and never write it in plaintext to code or logs.

    from e2b_code_interpreter import Sandbox
    
    sbx = Sandbox.create(
        template="code-interpreter",
        metadata={
            "security.agents.kruise.io/enable-jwt-auth": "true",
        },
    )
    
    # Obtain the JWT from the Sandbox object (the Python SDK does not mask the token).
    traffic_access_token = sbx.traffic_access_token
    In the current version, the JWT validity period is controlled by the sandbox-manager component, which passes issuance parameters to ack-agent-identity. The default validity period is 100 years. If the JWT expires, create a new Sandbox or call the issuance API to obtain a new token.
    To configure a short validity period for the token and enable automatic token rotation by the SDK, see Configure Agent Sandbox TrafficAccessToken auto-rotation.
  3. When you access a service inside the Sandbox, include the E2B-Traffic-Access-Token request header. The following example uses curl to access a service on a non-envd port:

    curl https://<YOUR-DOMAIN>/ \
      -H "E2B-Traffic-Access-Token: <TRAFFIC-ACCESS-TOKEN>" \
      -H "e2b-sandbox-id: <NAMESPACE>--<NAME>" \
      -H "e2b-sandbox-port: <PORT>"
    Note

    The native E2B SDK does not automatically inject trafficAccessToken into Sandbox data plane requests. To make native methods such as sbx.commands.run and sbx.files.* include this request header, use a Monkey Patch to write the token into the SDK's extra request header configuration. This solution depends on the internal implementation and private fields of the E2B SDK. Before you use the patch, make sure that your SDK version is compatible. Apply the patch before you create any Sandbox instance.

    Monkey Patch example

    The following code wraps SandboxBase.__init__ to inject the E2B-Traffic-Access-Token request header into ConnectionConfig after each Sandbox is created.

    from functools import wraps
    
    from e2b.sandbox.main import SandboxBase
    from e2b_code_interpreter import Sandbox
    
    
    def enable_traffic_access_token_header():
        """Inject trafficAccessToken into all E2B Sandbox data plane requests."""
        current_init = SandboxBase.__init__
    
        # Avoid repeated wrapping.
        if getattr(current_init, "_traffic_token_header_patch", False):
            return
    
        @wraps(current_init)
        def patched_init(self, *args, **kwargs):
            current_init(self, *args, **kwargs)
    
            token = getattr(self, "traffic_access_token", None)
            if not token:
                return
    
            extra_headers = getattr(
                self.connection_config,
                "_ConnectionConfig__extra_sandbox_headers",
                None,
            )
            if not isinstance(extra_headers, dict):
                raise RuntimeError(
                    "The current E2B SDK does not expose mutable extra sandbox headers. Upgrade to a supported version."
                )
    
            extra_headers["E2B-Traffic-Access-Token"] = token
    
        patched_init._traffic_token_header_patch = True
        SandboxBase.__init__ = patched_init
    
    
    # Usage example
    enable_traffic_access_token_header()
    
    sbx = Sandbox.create(
        template="code-interpreter",
        metadata={
            "security.agents.kruise.io/enable-jwt-auth": "true",
        },
    )
    
    command = sbx.commands.run("echo hello-from-envd")
    print(command.stdout)
    
    sbx.files.write("/tmp/jwt-auth-ok.txt", "authenticated through gateway")
    print(sbx.files.read("/tmp/jwt-auth-ok.txt"))
    sbx.kill()
    The combination of request headers (header-based routing and domain-based routing) follows the routing matching rules of SandboxGateway. For more information, see Configure routing rules.

JWT-based dynamic token authentication: authentication failure response

If JWT validation fails, for example because the token is invalid, expired, or does not match the target Sandbox, sandbox-gateway returns HTTP 403.

If a Sandbox is created with JWT-based dynamic token authentication enabled through metadata, but dynamic token authentication is not enabled on the gateway, sandbox-gateway returns HTTP 503.

FAQ

How to roll back on service failure

  1. In the console, under Add-ons, click Configuration for ack-sandbox-manager, and switch dataplaneService back to sandbox-manager.

  2. On the Network > Ingresses page, check whether the forwarding path of the gateway (such as ALB) has switched back to sandbox-manager.

  3. In the left navigation bar of the target cluster, select Operations > Log Center, and switch to the Application Logs tab.

  4. On the Application Logs page, set Logstore to ack-sandbox-manager-envoy, view the access log to confirm that the traffic has been switched back, and observe whether service traffic has returned to normal.

How to adjust the SandboxGateway specification

SandboxGateway instances are subject to the limitations of underlying network resources. Because SandboxGateway acts as a proxy, it handles both inbound and outbound traffic, which requires twice the underlying network bandwidth (see Limitations).

After evaluating your capacity requirements, adjust the specification in the following ways:

Important

Both adjustments increase fees: sandboxGateway.replicaCount sets the number of SandboxGateway pods, and sandboxGateway.resources sets the vCPU and memory of each pod. Confirm the billing impact before you make changes. For more information, see Billing overview.

  1. Increase the replica count of SandboxGateway instances. On the Configuration page of the ack-sandbox-manager add-on, adjust sandboxGateway.replicaCount.

  2. Adjust the instance specification to increase underlying bandwidth.

    On the Configuration page of the ack-sandbox-manager add-on, adjust the CPU and memory in sandboxGateway.resources.

    envoy.concurrency depends on resources.cpu: adjust envoy.concurrency whenever you change resources.cpu to keep SandboxGateway performance optimal.