# How CubeSandbox E2B SDK Compatibility Works for Seamless Migration

> Discover how CubeSandbox E2B SDK compatibility ensures seamless migration. It supports legacy variables and converts network policies, letting your E2B SDK code run without modification.

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

---

**CubeSandbox provides a compatibility layer that allows unmodified E2B SDK code to run by supporting legacy environment variables and automatically converting E2B-style network policy dictionaries into CubeSandbox's native rule format.**

Migrating between cloud sandbox providers typically requires extensive code refactoring, but TencentCloud/CubeSandbox eliminates this friction through comprehensive E2B SDK compatibility features. The CubeSandbox SDKs for Go, Python, and Node.js implement intelligent detection and translation layers that handle both authentication credentials and network policy configurations. This architecture ensures existing E2B deployments transition to the CubeSandbox control plane without requiring changes to application logic or infrastructure scripts.

## Environment Variable Fallback for Credentials

The Go SDK configuration builder implements a precedence-based environment variable resolver that maintains backward compatibility with existing E2B deployments. In [`sdk/go/config.go`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/go/config.go), the `firstEnv` helper function checks for `CUBE_*` variables first, then falls back to legacy `E2B_*` names.

This means deployments exporting `E2B_API_URL` or `E2B_API_KEY` continue functioning without modification, while new installations can adopt the `CUBE_*` naming convention. The implementation at lines 34-42 uses `firstEnv("CUBE_API_URL", "E2B_API_URL")` and `firstEnv("CUBE_API_KEY", "E2B_API_KEY")` to establish this priority order.

## Network Policy Shape Conversion

E2B represents network transformations as a dictionary mapping hosts to lists of transform objects, whereas CubeSandbox uses a native list of `Rule` objects. The compatibility layer detects the E2B shape at runtime and converts it transparently.

### Python SDK Implementation

In [`sdk/python/cubesandbox/_policy.py`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/python/cubesandbox/_policy.py), the functions `_is_e2b_per_host_rules` and `_convert_e2b_per_host_rules` handle the conversion logic at lines 69-98. The detection uses `isinstance(rules, dict)` to identify the E2B format, then expands each host entry into a `Rule` object.

The conversion generates deterministic rule names following the pattern `e2b-transform-<host>` and builds an `Inject` list from `transform.headers`. This converted structure feeds directly into the existing `_serialize_rule` function, ensuring the rest of the SDK processes native CubeSandbox formats exclusively.

### Node.js SDK Implementation

The Node.js SDK implements equivalent logic in [`sdk/node/src/policy.ts`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/node/src/policy.ts). The type guard `isE2BPerHostRules` distinguishes the dictionary shape using `!Array.isArray(rules)`, while `convertE2BPerHostRules` expands the dictionary into an array of `Rule` objects at lines 22-30.

Each generated rule receives the name `e2b-transform-<host>` and contains the header injection specifications derived from the original E2B transform definitions. This approach maintains audit traceability by making the origin of converted rules explicit in the configuration.

## Design Principles for Reliable Migration

The compatibility layer succeeds through several architectural decisions that prioritize explicit detection over heuristic parsing.

**Explicit Type Discrimination**

Both Python and Node.js SDKs use unambiguous type checks—`isinstance(rules, dict)` in Python and `!Array.isArray(rules)` in Node—to identify E2B formats. This prevents false positives that could arise from duck typing or property inspection.

**Pure Data Conversion**

Conversion functions return plain objects that feed directly into existing serializers (`_serialize_rule` in Python, `serializeRule` in Node.js). This thin wrapper approach keeps the compatibility layer testable and isolated from core request-building logic.

**Deterministic Rule Naming**

Generated rules follow the pattern `e2b-transform-<host>[-<index>]`, ensuring operators can trace converted configurations in logs and audit trails. This naming convention bridges the gap between E2B host-keyed dictionaries and CubeSandbox's ordered rule lists.

**Fail-Fast Validation**

The SDKs validate that only supported keys (specifically `headers`) appear in transform objects, with string values enforced. This strict validation prevents silent misconfigurations that could result in missing credential injections or security policy gaps.

## Practical Migration Examples

### Python with E2B-Style Network Dictionary

```python
from cubesandbox import Sandbox

with Sandbox.create(
    network={
        "allow_out": ["api.example.com"],
        "deny_out": ["0.0.0.0/0"],
        "rules": {
            "api.example.com": [
                {"transform": {"headers": {"X-Header": "SecretValue"}}},
            ],
        },
    },
) as sb:
    sb.run_code("import requests; requests.get('https://api.example.com/')")

```

The `rules` dictionary triggers `_is_e2b_per_host_rules` detection, which calls `_convert_e2b_per_host_rules` to produce a `Rule` that injects the specified header.

### Node.js with E2B Policies

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

await Sandbox.create({
  network: {
    allow_out: ["api.example.com"],
    deny_out: ["0.0.0.0/0"],
    rules: {
      "api.example.com": [
        { transform: { headers: { "X-Header": "SecretValue" } } },
      ],
    },
  },
});

```

The `normalizeRulesArg` function detects the dictionary shape, executes `convertE2BPerHostRules`, and passes the resulting `Rule[]` to the request serializer.

### Go with Environment Variable Fallback

```go
import "github.com/TencentCloud/CubeSandbox/sdk"

func main() {
    // Reads CUBE_API_URL or falls back to E2B_API_URL
    // Reads CUBE_API_KEY or falls back to E2B_API_KEY
    cfg := cubesandbox.NewConfigFromEnv()
    client := cubesandbox.NewClient(cfg)
    // ... use client as usual
}

```

The `NewConfigFromEnv` function in [`sdk/go/config.go`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/go/config.go) checks `CUBE_API_URL` first, then `E2B_API_URL`, applying the same precedence logic to the API key.

## Key Implementation Files

- **Python**: [`sdk/python/cubesandbox/_policy.py`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/python/cubesandbox/_policy.py) contains per-host transform detection and conversion logic.
- **Node.js**: [`sdk/node/src/policy.ts`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/node/src/policy.ts) implements type guards, conversion functions, and rule normalization.
- **Go**: [`sdk/go/config.go`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/go/config.go) handles environment variable precedence for API URL and key configuration.
- **Documentation**: [`sdk/python/README.md`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/python/README.md) documents the E2B-compatible network shape for end users.

## Summary

- CubeSandbox supports **legacy environment variables** (`E2B_API_KEY`, `E2B_API_URL`) with `CUBE_*` variables taking precedence.
- The SDKs **automatically convert** E2B-style host-keyed network dictionaries into CubeSandbox's native rule list format.
- **Deterministic rule naming** (`e2b-transform-<host>`) ensures converted policies remain traceable in audit logs.
- **Fail-fast validation** prevents silent misconfigurations by rejecting unsupported transform keys or non-string values.
- No code changes are required for migration—existing E2B SDK usage runs unmodified against the CubeSandbox control plane.

## Frequently Asked Questions

### Do I need to modify my existing E2B code to use CubeSandbox?

No. The CubeSandbox SDK detects E2B-style configurations at runtime and handles the conversion transparently. You only need to ensure your environment variables point to the CubeSandbox endpoint, or keep existing `E2B_API_URL` values—the SDK accepts both.

### Which environment variable takes precedence if both CUBE_API_KEY and E2B_API_KEY are set?

`CUBE_API_KEY` takes precedence. The Go SDK's `firstEnv` function in [`sdk/go/config.go`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/go/config.go) explicitly checks `CUBE_*` variables first, falling back to `E2B_*` only if the modern variants are absent. This allows gradual migration where new deployments use CubeSandbox naming while legacy scripts continue working.

### How does the SDK handle conflicting network policy formats?

The SDK uses explicit type discrimination to distinguish formats. In Python, `isinstance(rules, dict)` identifies E2B format, while in Node.js, `!Array.isArray(rules)` performs the same check. When detected, the compatibility layer converts the dictionary to a list of `Rule` objects with generated names like `e2b-transform-<host>`, preserving the original header injection logic.

### Are there performance implications when using the compatibility layer?

No. The conversion happens once during sandbox initialization and produces plain objects that feed directly into the existing serialization pipeline. The compatibility layer adds minimal overhead—essentially a single type check and object transformation—before the native CubeSandbox processing begins.