# How Network Policies Are Hardened Using Per-Sandbox Traffic Tokens

> CubeSandbox hardens network policies with unique traffic tokens for enhanced security. Learn how per-sandbox tokens prevent unauthorized access in this technical deep dive.

- Repository: [Tencent Cloud/CubeSandbox](https://github.com/TencentCloud/CubeSandbox)
- Tags: architecture
- Published: 2026-07-10

---

**CubeSandbox hardens network policies by issuing a cryptographically unique UUID v4 traffic access token to each sandbox created with `network.allow_public_traffic` set to `false`, requiring this token in every inbound request header to prevent unauthorized public access.**

When running untrusted code in cloud environments, publicly exposed sandbox endpoints present a significant attack surface. The TencentCloud/CubeSandbox platform mitigates this risk through an automatic **per-sandbox traffic token** mechanism that transforms open network policies into gated, token-authenticated ingress. According to the CubeSandbox source code, this hardening occurs transparently when developers disable public traffic during sandbox creation.

## Token Generation at Sandbox Creation

When the `network.allow_public_traffic` configuration is set to `false`, CubeMaster generates a unique **traffic access token** using UUID v4. This token is stored in the sandbox's data structure under the `trafficAccessToken` field and returned in the API response.

The token definition exists in the CubeMaster service types, where the `Sandbox` struct includes the field [`TrafficAccessToken`](https://github.com/TencentCloud/CubeSandbox/blob/master/CubeMaster/pkg/service/sandbox/types/types.go). Similarly, the CubeAPI models define this as [`traffic_access_token`](https://github.com/TencentCloud/CubeSandbox/blob/master/CubeAPI/src/models/mod.rs) in the sandbox response payload. As documented in the [restrict public access guide](https://github.com/TencentCloud/CubeSandbox/blob/master/docs/guide/restrict-public-access.md), this feature was introduced in v0.5.0 to enable traffic access token gating.

If `allow_public_traffic` remains `true` (the default), no token is generated and the sandbox accepts unrestricted inbound connections.

## SDK Access to the Traffic Token

Both the Python and Node.js SDKs expose the token through convenient properties that abstract the underlying API response parsing.

### Python SDK Implementation

In the Python SDK, the [`Sandbox.traffic_access_token`](https://github.com/TencentCloud/CubeSandbox/blob/master/sdk/python/cubesandbox/sandbox.py#L6-L22) property retrieves the token from the sandbox data dictionary:

```python
@property
def traffic_access_token(self) -> Optional[str]:
    """Returns the traffic access token if public traffic is restricted."""
    return self._data.get("trafficAccessToken")

```

When making requests, the SDK automatically includes the token via the [`_traffic_token_headers()`](https://github.com/TencentCloud/CubeSandbox/blob/master/sdk/python/cubesandbox/sandbox.py#L78-L86) method, which attaches the `e2b-traffic-access-token` header.

### Node SDK Implementation

The Node.js SDK implements similar functionality through the `trafficAccessToken` property and the [`_trafficTokenHeaders()`](https://github.com/TencentCloud/CubeSandbox/blob/master/sdk/node/src/sandbox.ts#L258-L307) method, which returns headers containing both `e2b-traffic-access-token` and `cube-traffic-access-token` for compatibility.

## Proxy Enforcement via CubeProxy

All inbound traffic to sandboxes routes through **CubeProxy**, a Lua-based reverse proxy that enforces token validation before forwarding requests to the sandbox container.

The enforcement logic resides in [[`CubeProxy/lua/sandbox_backend.lua`](https://github.com/TencentCloud/CubeSandbox/blob/main/CubeProxy/lua/sandbox_backend.lua)](https://github.com/TencentCloud/CubeSandbox/blob/master/CubeProxy/lua/sandbox_backend.lua#L36-L37), where the script extracts the token from incoming HTTP headers:

```lua
local provided = ngx.var.http_e2b_traffic_access_token
               or ngx.var.http_cube_traffic_access_token

```

CubeProxy compares the provided value against the sandbox's stored token. If the header is missing or the values mismatch, the proxy immediately returns **HTTP 403 Forbidden** without forwarding the request to the backend.

## Security and Logging Considerations

The traffic access token is **redacted from all logs** to prevent accidental exposure in log aggregation systems. This ensures that even if request logs are compromised, the authentication tokens remain protected.

Because each token is a UUID v4 generated at sandbox creation, tokens are cryptographically random and unique per sandbox, preventing token guessing or cross-sandbox replay attacks.

## Practical Implementation Examples

### Python SDK: Creating a Restricted Sandbox

```python
from cubesandbox import Sandbox
import requests

# Create sandbox with hardened network policy

with Sandbox.create(network={"allow_public_traffic": False}) as sb:
    token = sb.traffic_access_token
    assert token is not None, "Token should be present when public traffic is disabled"
    
    # Accessing the public URL requires the token header

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

```

### Node.js SDK: TypeScript Implementation

```typescript
import { Sandbox } from "cubesandbox";

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

```

### Raw HTTP with curl

For direct API access without SDKs:

```bash

# Create sandbox and extract token (example value)

TOKEN="550e8400-e29b-41d4-a716-446655440000"

# Request without token fails with 403

curl -I https://49999-<sandbox-id>.cube.app/

# HTTP/1.1 403 Forbidden

# Request with valid token succeeds

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

# HTTP/1.1 200 OK

```

## Summary

- **Network policies are hardened** by setting `network.allow_public_traffic` to `false`, which triggers automatic token generation in CubeMaster.
- **Per-sandbox tokens** are UUID v4 values stored in the sandbox data structure and exposed via SDK properties.
- **CubeProxy validates** every inbound request against the expected token using the `e2b-traffic-access-token` or `cube-traffic-access-token` headers, rejecting unauthorized requests with HTTP 403.
- **Security safeguards** include token redaction from logs and cryptographically random generation to prevent brute-force attacks.
- **SDK automation** handles header injection automatically, while raw HTTP clients must manually include the appropriate header.

## Frequently Asked Questions

### What happens if the traffic access token is missing or incorrect?

CubeProxy returns **HTTP 403 Forbidden** immediately, preventing the request from reaching the sandbox container. This enforcement happens at the edge proxy level before any application code executes, ensuring zero trust network access.

### Can I rotate or regenerate the traffic access token for a running sandbox?

No. The traffic access token is generated once during sandbox creation in CubeMaster and cannot be rotated dynamically. To obtain a new token, you must create a new sandbox instance with the `allow_public_traffic: false` configuration.

### Is the traffic access token required for internal sandbox communication?

No. The token is only enforced for **public inbound traffic** routed through CubeProxy. Internal communication between the sandbox and other services within the private network, or outbound connections from the sandbox, do not require the traffic access token.

### Which HTTP headers are accepted for the traffic token?

CubeProxy accepts two header variations for compatibility: **`e2b-traffic-access-token`** and **`cube-traffic-access-token`**. Both are checked in the Lua validation script, and either will authenticate the request if the value matches the sandbox's stored token.