How Per-Sandbox Traffic Tokens Harden Network Policies in CubeSandbox

When network.allow_public_traffic is set to false, CubeSandbox generates a unique UUID v4 token for each sandbox that must be presented in request headers to access public endpoints, effectively creating a cryptographic gate enforced by CubeProxy.

CubeSandbox, Tencent Cloud's open-source sandbox environment, implements defense-in-depth network security through per-sandbox traffic tokens. This mechanism allows developers to completely disable public inbound access while maintaining programmatic accessibility through cryptographically unique tokens that are validated at the proxy layer.

Token Generation and Storage Architecture

When you create a sandbox with restricted network access, the platform generates a cryptographically secure token that follows the sandbox lifecycle.

CubeMaster Type Definition

In the CubeMaster service, the sandbox struct definition includes the TrafficAccessToken field to persist the generated token:

Source

API Model Definition

The CubeAPI component defines the token in its Rust models as an optional string field exposed to clients:

Source

Documentation and Lifecycle

The restriction capability is documented in the official guide, which explains that setting network.allow_public_traffic to false triggers token generation during sandbox creation. The token is returned in the creation response under the JSON field trafficAccessToken and is immutable for the sandbox's lifetime.

Source

This feature was introduced in version 0.5.0 as "Traffic access token gating" for hardened network policies.

Source

Token Enforcement Architecture

The enforcement of traffic tokens occurs at the edge proxy layer, ensuring unauthorized requests never reach the sandbox environment.

CubeProxy Lua Validation

CubeProxy, the reverse proxy fronting each sandbox, executes a Lua script that extracts and validates tokens from incoming requests. The script checks for the token in two possible HTTP headers:

-- CubeProxy/lua/sandbox_backend.lua
local provided = ngx.var.http_e2b_traffic_access_token
               or ngx.var.http_cube_traffic_access_token

Source

If the header is missing or the provided value does not match the sandbox's stored token, CubeProxy immediately returns HTTP 403 Forbidden before the request reaches the sandbox container.

Security-First Logging

The token is intentionally redacted from all proxy and application logs to prevent accidental credential leakage in log aggregation systems.

SDK Implementation and Access

Both the Python and Node.js SDKs provide first-class support for retrieving and automatically injecting traffic tokens.

Python SDK Token Property

The Python SDK exposes the token via the traffic_access_token property in the Sandbox class:


# sdk/python/cubesandbox/sandbox.py

@property
def traffic_access_token(self) -> str | None:
    """Returns the traffic access token for this sandbox, if restricted."""
    return self._data.get("trafficAccessToken")

Source

Automatic Header Injection

When making requests to sandbox endpoints, the SDK automatically attaches the appropriate headers. The Python implementation defines a helper method:

def _traffic_token_headers(self):
    headers = {}
    if self.traffic_access_token:
        headers["e2b-traffic-access-token"] = self.traffic_access_token
    return headers

Source

The Node.js SDK implements equivalent logic in the _traffic_token_headers() method to ensure consistent behavior across languages.

Source

Practical Implementation Examples

Python SDK Example

Create a restricted sandbox and access its public endpoints using the generated token:

from cubesandbox import Sandbox
import requests

# Create sandbox with public traffic disabled

with Sandbox.create(network={"allow_public_traffic": False}) as sb:
    token = sb.traffic_access_token
    print(f"Token acquired: {token[:8]}...")  # Token is a UUID v4

    
    # Access the sandbox's public URL

    url = f"https://{sb.get_host(49999)}/"
    response = requests.get(
        url, 
        headers={"e2b-traffic-access-token": token}
    )
    print(response.status_code)  # 200 if token valid, 403 if missing/invalid

Node.js SDK Example

The Node.js SDK provides equivalent functionality for TypeScript and JavaScript applications:

import { Sandbox } from "cubesandbox";

async function accessRestrictedSandbox() {
  const sb = await Sandbox.create({ 
    network: { allow_public_traffic: false } 
  });
  
  const token = sb.trafficAccessToken;
  if (!token) throw new Error("Expected token for restricted sandbox");
  
  const url = `https://${sb.getHost(49999)}/`;
  const response = await fetch(url, {
    headers: { "e2b-traffic-access-token": token }
  });
  
  console.log(response.status); // 200 on success, 403 on invalid token
}

accessRestrictedSandbox();

Raw HTTP with cURL

For direct API access without SDKs, include the token in the request headers:


# Create sandbox and extract TOKEN from response

TOKEN="your-uuid-v4-token-here"

# Access the sandbox endpoint

curl -H "e2b-traffic-access-token: $TOKEN" \
     https://49999-<sandbox-id>.cube.app/

If the header is omitted or the token is incorrect, the proxy returns:

HTTP/1.1 403 Forbidden
Content-Type: text/plain

Traffic access token mismatch

Summary

  • Per-sandbox tokens are UUID v4 strings generated when network.allow_public_traffic is set to false, creating a cryptographic identity for each sandbox instance.
  • Proxy-level enforcement occurs in CubeProxy/lua/sandbox_backend.lua, which validates the e2b-traffic-access-token or cube-traffic-access-token headers before forwarding requests.
  • SDK integration provides seamless access via traffic_access_token properties in Python and Node.js, with automatic header injection for authenticated requests.
  • Security hardening includes complete token redaction from logs and immediate 403 responses for missing or mismatched tokens, ensuring zero-trust network access.

Frequently Asked Questions

What happens if I request a restricted sandbox without the traffic token?

CubeProxy returns HTTP 403 Forbidden immediately, preventing the request from reaching the sandbox container. The response body typically indicates a token mismatch, and the event is logged with the client IP but with the token value redacted to prevent credential leakage.

Can I rotate or regenerate the traffic access token after sandbox creation?

No. According to the current implementation in CubeMaster/pkg/service/sandbox/types/types.go, the token is generated once during sandbox creation and persists for the sandbox's entire lifetime. To obtain a new token, you must create a new sandbox instance with allow_public_traffic: false; there is no API endpoint for token rotation of existing sandboxes.

Is the traffic access token the same as my CubeSandbox API key?

No. The API key authenticates your requests to the CubeSandbox management API (CubeMaster/CubeAPI), while the traffic access token authorizes inbound HTTP traffic to the sandbox itself. The traffic token is specific to each sandbox instance and is meaningless to the management API, providing isolation between infrastructure authentication and runtime network policies.

Does enabling public traffic restriction affect outbound connections from the sandbox?

No. The allow_public_traffic flag only controls inbound traffic to the sandbox's public endpoints. Outbound connections initiated from within the sandbox to external services remain unaffected by this policy, as the token validation only occurs on the ingress path through CubeProxy.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →