WeKnora/internal/sandbox/docker_integration_test.go

694 lines
23 KiB
Go
Raw Normal View History

//go:build docker_integration
// Conformance test for the Docker backend against a real daemon.
//
// It drives the same public surface as the E2B-protocol conformance suite
// (session-scoped script execution, shell commands, attachment staging,
// artifact listing, timeouts, teardown), because the point of the docker
// backend is to be indistinguishable from a remote one at that level. Anything
// asserted here that the E2B suite also asserts is deliberate duplication: a
// backend that passes one and fails the other is not interchangeable.
//
// Run with a reachable daemon and the standard sandbox image:
//
// docker build -f docker/Dockerfile.sandbox -t wechatopenai/weknora-sandbox:dev .
// DOCKER_INTEGRATION_IMAGE=wechatopenai/weknora-sandbox:dev \
// go test -tags=docker_integration ./internal/sandbox \
// -run '^TestDocker.*Integration' -count=1 -v -timeout=15m
package sandbox
import (
"bytes"
"context"
"fmt"
"os"
"path"
"strings"
"testing"
"time"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
"github.com/Tencent/WeKnora/internal/types"
)
const dockerIntegrationTenantID = 1
func dockerIntegrationConfig(t *testing.T) *Config {
t.Helper()
image := strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_IMAGE"))
if image == "" {
t.Skip("DOCKER_INTEGRATION_IMAGE is required for the docker conformance suite")
}
cfg := DefaultConfig()
cfg.Type = SandboxTypeDocker
cfg.DockerImage = image
cfg.DockerHost = strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_HOST"))
cfg.DefaultTimeout = 2 * time.Minute
applyDockerRuntimeDefaults(cfg)
return cfg
}
func newDockerIntegrationManager(t *testing.T, cfg *Config) *SessionBoundManager {
t.Helper()
client, err := NewDockerRemoteClient(cfg)
if err != nil {
t.Fatalf("build docker client: %v", err)
}
// Integration tests clean up their own sessions. Do not reclaim unrelated
// idle containers when using a shared developer daemon.
client.sweeper = nil
probeCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := client.Health(probeCtx); err != nil {
t.Skipf("docker daemon unreachable: %v", err)
}
manager, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: NewMemorySessionSandboxBindingStore(),
Checker: PermissiveSessionExistenceChecker{},
ConfigID: "docker-conformance",
SkipHealthProbe: true,
})
if err != nil {
t.Fatalf("NewSessionBoundManager: %v", err)
}
return manager
}
func TestDockerBackendConformanceIntegration(t *testing.T) {
cfg := dockerIntegrationConfig(t)
manager := newDockerIntegrationManager(t, cfg)
ctx, cancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
12*time.Minute,
)
defer cancel()
sessionID := fmt.Sprintf("docker-conformance-%d", time.Now().UnixNano())
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
2*time.Minute,
)
defer cleanupCancel()
if err := manager.DestroySession(cleanupCtx, sessionID); err != nil {
t.Errorf("DestroySession: %v", err)
}
})
counterPath := path.Join(SessionOutputRoot, "counter.txt")
t.Run("SessionScopedStatePersistsAcrossExecutions", func(t *testing.T) {
first := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(`
with open(%q, 'w') as handle:
handle.write('1')
print('wrote counter')
`, counterPath))
if !first.IsSuccess() {
t.Fatalf("first execution failed: %#v", first)
}
second := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(`
with open(%q) as handle:
print('counter=' + handle.read())
`, counterPath))
if !second.IsSuccess() || !strings.Contains(second.Stdout, "counter=1") {
t.Fatalf("session state did not persist: %#v", second)
}
})
t.Run("InstalledPackagesSurviveBetweenExecutions", func(t *testing.T) {
install := runDockerScript(t, ctx, manager, sessionID, `
import subprocess
print(subprocess.run(
['pip', 'install', '--quiet', '--no-cache-dir', '--user', 'cowsay==6.1'],
capture_output=True, text=True).returncode)
`)
if !install.IsSuccess() {
t.Fatalf("package install failed: %#v", install)
}
use := runDockerScript(t, ctx, manager, sessionID, `
import cowsay
print('cowsay-ok')
`)
if !use.IsSuccess() || !strings.Contains(use.Stdout, "cowsay-ok") {
t.Fatalf("installed package did not survive: %#v", use)
}
})
t.Run("ShellExecSharesTheSessionSandbox", func(t *testing.T) {
executor := manager.SessionShellExecutor()
if executor == nil {
t.Fatal("session shell executor is unavailable on a healthy docker backend")
}
result, err := executor.ExecShellCommand(
ctx, sessionID, "cat "+counterPath, SessionWorkspaceRoot, time.Minute, nil,
)
if err != nil {
t.Fatalf("ExecShellCommand: %v", err)
}
if !result.IsSuccess() || !strings.Contains(result.Stdout, "1") {
t.Fatalf("shell command did not observe the session sandbox: %#v", result)
}
})
t.Run("AttachmentStagingAndArtifactCollection", func(t *testing.T) {
files := manager.SessionFileStore()
if files == nil {
t.Fatal("session file store is unavailable on a healthy docker backend")
}
inputPath := path.Join(SessionInputRoot, "attachment.txt")
payload := []byte("attachment payload\n")
if err := files.WriteSessionInputFile(ctx, sessionID, inputPath, payload); err != nil {
t.Fatalf("WriteSessionInputFile: %v", err)
}
content, err := files.ReadSessionFile(ctx, sessionID, inputPath)
if err != nil {
t.Fatalf("ReadSessionFile: %v", err)
}
if !bytes.Equal(content, payload) {
t.Fatalf("staged attachment mismatch: got=%q want=%q", content, payload)
}
result := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(`
import os
target = os.path.join(os.environ['%s'], 'report.txt')
with open(target, 'w') as handle:
handle.write('artifact body')
print('artifact written')
`, skillOutputEnvVar))
if !result.IsSuccess() {
t.Fatalf("artifact-producing execution failed: %#v", result)
}
entries, err := files.ListSessionFiles(ctx, sessionID, SessionOutputRoot)
if err != nil {
t.Fatalf("ListSessionFiles: %v", err)
}
found := false
for _, entry := range entries {
if entry.Name == "report.txt" {
found = true
}
}
if !found {
t.Fatalf("artifact directory did not contain report.txt: %#v", entries)
}
if err := files.RemoveSessionInputPath(ctx, sessionID, inputPath); err != nil {
t.Fatalf("RemoveSessionInputPath: %v", err)
}
})
t.Run("TimeoutIsReportedAsKilled", func(t *testing.T) {
result := runDockerScriptWithTimeout(t, ctx, manager, sessionID, `
import time
time.sleep(60)
`, 5*time.Second)
if !result.Killed {
t.Fatalf("expected a killed result for an over-running script: %#v", result)
}
})
// The daemon does not stop a process when the client goes away, so the
// only proof that a timeout means anything is that nothing is left running.
t.Run("TimeoutActuallyStopsTheProcess", func(t *testing.T) {
executor := manager.SessionShellExecutor()
_, err := executor.ExecShellCommand(
ctx, sessionID, "sleep 120", SessionWorkspaceRoot, 3*time.Second, nil,
)
if err != nil {
t.Fatalf("ExecShellCommand: %v", err)
}
time.Sleep(2 * time.Second)
// Count processes whose command line is exactly "sleep 120", which the
// probe's own shell cannot match.
const probe = `n=0; for p in /proc/[0-9]*; do ` +
`cmd=$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null); ` +
`case "$cmd" in "sleep 120 ") n=$((n+1));; esac; done; echo "$n"`
survivors, err := executor.ExecShellCommand(
ctx, sessionID, probe, SessionWorkspaceRoot, 30*time.Second, nil,
)
if err != nil {
t.Fatalf("survivor probe: %v", err)
}
if got := strings.TrimSpace(survivors.Stdout); got != "0" {
t.Fatalf("timeout left %s 'sleep 120' process(es) running: %#v", got, survivors)
}
})
fix(sandbox): Docker 文件操作改走沙箱账号,堵住符号链接越权并回收僵尸进程 archive 接口(CopyToContainer / CopyFromContainer / ContainerStatPath)由 daemon 执行,它忽略 exec user 一律以 root 操作,并在解析路径时跟随符号链接。而沙箱账号对 /workspace 有写权限,调用侧的路径守卫(isUnderRoot、cleanSessionInputPath)又都是 字符串前缀比较,于是 `ln -s /root /workspace/output/esc` 之后, /workspace/output/esc/secret.txt 既能通过守卫,又会被 daemon 以 root 读出来。真机 验证过:非特权账号 cat 该路径是 Permission denied,docker cp 同一路径拿到明文。 WriteFile / ReadFile / Stat 改为以 DefaultSandboxExecUser 走 exec,能不能读写交给 内核判定,符号链接指向哪里都不再重要,也不存在「先校验后使用」之间被换掉链接的窗口 (这正是 realpath 预校验方案挡不住的)。Stat 用 find,它不跟随符号链接,因此链接如实 报告为 other 类型,read_sandbox_file 在尝试读取之前就会拒绝。两个 copy 端点从 dockerEngineAPI 接口里移除——留着未使用的入口等于把这一类问题继续敞着。 容器入口是 sleep,从不调用 wait(),后台进程活得比启动它的 exec 久就会变成没人回收的 僵尸,堆到 pids_limit 之后所有 exec 都会失败。补 HostConfig.Init 交给 tini。实测: 三个孤儿进程,不开 Init 留下三个 Z,开了之后为零。 同步订正文档与注释中过时的 root 表述:上一次提交已把 shell_exec 降权到沙箱账号,但 docs 仍写着「exec 默认以 root 运行」「shell_exec 默认就是 root」,并据此把活跃标记可被 无限刷新归因于「容器内 root 信任边界」——标记是 chmod 666,普通技能脚本就能刷新。
2026-08-24 03:51:21 +00:00
// The entrypoint is a plain `sleep`, which never calls wait(). A background
// process that outlives the exec which started it is reparented to PID 1,
// so without tini in front of it every such process becomes a permanent Z
// entry and a long session eventually exhausts PidsLimit. Measured on a
// real daemon: three orphans leave three zombies without HostConfig.Init
// and none with it.
t.Run("OrphanedProcessesAreReaped", func(t *testing.T) {
executor := manager.SessionShellExecutor()
for i := 0; i < 3; i++ {
if _, err := executor.ExecShellCommand(
ctx, sessionID, "(sleep 0.2 &) ; exit 0",
SessionWorkspaceRoot, 30*time.Second, nil,
); err != nil {
t.Fatalf("spawn orphan %d: %v", i, err)
}
}
time.Sleep(2 * time.Second)
const probe = `n=0; for p in /proc/[0-9]*; do ` +
`s=$(awk '{print $3}' "$p/stat" 2>/dev/null); ` +
`[ "$s" = "Z" ] && n=$((n+1)); done; echo "$n"`
zombies, err := executor.ExecShellCommand(
ctx, sessionID, probe, SessionWorkspaceRoot, 30*time.Second, nil,
)
if err != nil {
t.Fatalf("zombie probe: %v", err)
}
if got := strings.TrimSpace(zombies.Stdout); got != "0" {
t.Fatalf("PID 1 left %s zombie(s) unreaped: %#v", got, zombies)
}
})
}
// The idle sweeper reclaims a container by the mtime of its activity marker,
// and skill scripts run as the unprivileged sandbox user. A session that only
// ever runs scripts must still count as active, or it gets deleted underneath
// the user who is actively using it.
func TestDockerBackendScriptExecutionRefreshesActivityMarkerIntegration(t *testing.T) {
cfg := dockerIntegrationConfig(t)
manager := newDockerIntegrationManager(t, cfg)
ctx, cancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
5*time.Minute,
)
defer cancel()
sessionID := fmt.Sprintf("docker-activity-%d", time.Now().UnixNano())
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
time.Minute,
)
defer cleanupCancel()
_ = manager.DestroySession(cleanupCtx, sessionID)
})
first := runDockerScript(t, ctx, manager, sessionID, `print('one')`)
if !first.IsSuccess() {
t.Fatalf("first execution failed: %#v", first)
}
client, err := NewDockerRemoteClient(cfg)
if err != nil {
t.Fatalf("build docker client: %v", err)
}
summaries, err := client.List(ctx, RemoteListFilter{
Metadata: map[string]string{remoteMetadataSessionID: sessionID},
})
if err != nil || len(summaries) != 1 {
t.Fatalf("expected exactly one container: %v %#v", err, summaries)
}
feat(sandbox): add tenant-configurable network policy (#2995) * feat(sandbox): add the tenant network policy with its secrets and validation Administrators need control over sandbox network access, so a named sandbox config gains a network policy block. It lives inside the existing config JSONB, so there is no schema change and old rows read back as the zero value. Both booleans are phrased so that the zero value IS the intended default -- outbound open, inbound closed. That makes "no network block" and "explicitly saved defaults" provably the same thing, and avoids a tri-state pointer where nil would have to mean "allowed" for egress and "closed" for ingress. Injected header values are credentials, so they ride the encrypt-at-rest and mask-on-read path EnvVars already uses instead of a parallel mechanism. One CloneWithSecrets traversal serves encrypt, decrypt and mask so the three directions cannot disagree about which fields are secret. Validation runs at save time because the alternative is failing at sandbox-create time, where the admin no longer has the form in front of them. It rejects both what a provider would refuse and what a provider would accept without doing what the admin meant -- a domain allowlist with no deny-all fallback still leaves every unresolved destination reachable. * feat(sandbox): apply the network policy on both providers, persist the inbound token Resolve the stored policy into one fully specified provider-neutral policy so that nothing downstream re-derives a default. Both booleans come out non-nil on every path, including the nil-tenant one, because a partially specified policy would let the adapters fall back to their providers' more permissive defaults. The three inversions (deny-egress to allow-internet, public-inbound, rule-deny to rule-allow) happen in exactly one place. Every sandbox-creating path carries it, so sessions, skill installs and the deep connectivity check all run under the same config's policy rather than each wiring its own. Inbound access defaults to CLOSED, deliberately stricter than either provider's own default: a sandbox URL reachable by anyone who learns the ID is not a reasonable default for a tenant's workspace. Closing it makes the provider issue a per-sandbox traffic token, and only at create time -- so the token is stored with the session binding and replayed through Connect on every reconnect. Without that, a sandbox that was paused on TTL or rebound after a restart would answer 403 on every exec and file read, and 403 classifies as an authentication error rather than NotFound, so the binding would never be replaced and the session would stay wedged. Connect therefore takes a request struct instead of a bare ID, which gives the token a single documented way in rather than implicit state inside an adapter. Metadata-based recovery is the one reconnect path with no binding to read the token from. Rather than adopt a sandbox that would be permanently 403, it is deleted and replaced -- but only for providers that have the credential at all, since Docker has no inbound token and its containers are still adoptable. go-e2b keeps the token and never sends it, so for E2B the data-plane RoundTripper attaches the header from a process-local registry. Cube's SDK already does this itself. * fix(sandbox): classify data-plane traffic by authority shape, not the configured domain isDataPlane suffix-matched the configured sandbox domain, which was wrong in both directions. Both required a configured proxy_url, so E2B Cloud's default usage was unaffected; the affected deployments are exactly the self-hosted and E2B-compatible ones the gateway exists for. A configured gateway could be silently ignored. sandbox_domain is optional for E2B -- MissingRequiredFields asks only for api_key and template_id -- and with it empty the check returned false for everything. The general form is worse than the empty case: go-e2b's envdBaseURL prefers the domain the control plane reported over the client-wide one, so the authority actually dialled need not appear in the config at all. The failure is quiet whenever public DNS happens to resolve the sandbox domain, and the operator believes traffic is passing through a gateway that never sees it. Control-plane calls could be sent to the gateway. E2B's own defaults put the API host under the sandbox domain (api.e2b.app beneath e2b.app), so the suffix match classified every Create, Connect and List as data-plane traffic. That is loud where the gateway does not serve the API, but where it proxies both planes it succeeds while downgrading an X-API-Key request to plaintext for an http:// gateway. Cube was immune to the first problem, since it requires both fields, but not to this one. Classify on the "<port>-<sandboxID>.<domain>" shape both SDKs generate, using the SandboxIDFromDataPlaneHost helper that token injection on the very same request already relies on -- so routing and injection now agree by construction instead of applying two different rules. That helper exists precisely because the configured domain is unreliable here; it was simply never used for the routing half. The control host stays as an explicit exclusion. The shape test already rejects api.<domain>, so this only covers an API host that itself wears the shape, such as 8080-api.example.com. One existing assertion was replaced rather than kept: the E2B pool test proved that the Cube fields were ignored by asserting a cube.app authority was not data-plane traffic, which tested the domain matching rather than the field selection. It now asserts the transport dials the E2B gateway address and not the Cube one. * feat(sandbox): add the network policy editor to the sandbox config drawer The policy sits in the runtime step, directly under the settings it constrains, rather than in a step of its own. The existing execution timeouts were compressed into a two-column grid to make room, keeping each field's own label and its own tip -- the reason they were one per row was that three unlabelled numbers sharing a footnote gave no clue which one you were editing, and two columns with per-field tips does not regress that. Provider-specific sections are shown only for the backend that has them: the Cube L7 rule cards, E2B's per-host header transforms, and for Docker just the bridge/none selector, since Docker can only express the overall switch. Injected header values are write-only. A stored one shows as configured and is preserved when the input is left blank, which is how env-var secrets already behave. Renaming a rule or a header is the case worth care: the merge indexes credentials on the rule-and-header pair, so a rename means the old value can no longer be recovered. One helper decides both the placeholder text and whether the payload re-attaches the value, so the form cannot claim a credential is kept while the save blanks it. The add buttons use keys of their own instead of reusing the env-var table's "add variable", which read wrongly under a list of network destinations and which the i18n key check cannot catch, since the key exists in every bundle. * docs(sandbox): document the network policy and its inbound default change The existing network bullet described the pre-feature state -- both providers open by default, tunable only through the neutral policy at create time -- which is no longer true of the defaults or of the admin-facing surface. Three things needed writing down rather than restating. The inbound default flips from publicly reachable to credential-required. A deployment that relies on a browser or an external service reaching a sandbox port directly, rather than going through WeKnora, has to opt back in on that config. The binding store now holds a bearer credential in plaintext. Leaving it unencrypted was a deliberate trade -- per-reconnect crypto on the hot path against Redis's own access control -- and the trade is only sound if the requirement is actually stated, along with the code-side constraint it depends on: a binding or a handle is never logged whole, only the sandbox ID and whether a credential is present. On binding loss, a closed-inbound Cube or E2B config no longer adopts its old sandbox by metadata. The token went with the binding and the provider will not reissue it, so adoption would produce a session that answers 403 on every data-plane call with no way back. The sandbox is deleted and rebuilt, which costs the /workspace scratch. Docker has no such credential and still adopts. * fix(sandbox): fail closed when a closed-inbound create has no traffic token A Cube/E2B sandbox created without the inbound token would be bound anyway, then 403 on every data-plane call as an unreplaceable authentication error. Refuse the create, destroy the sandbox, and stop Docker from persisting inbound/egress radios it cannot honour. Canonicalize IPv4 /0 deny-all onto 0.0.0.0/0 and reject CR/LF in injected header names and values. * fix(sandbox): satisfy pre-push lint on the network policy files Unexport the data-plane host parser, drop file-level package docs that revive rejected, and lowercase error-string prefixes that staticcheck ST1005 treats as capitalized English. * fix(sandbox): persist rotated inbound tokens and stop misreporting restricted egress Connect can reissue the traffic token after pause/resume; write it back onto the binding so a restart does not restore a stale credential that 403s and cannot be replaced. Restore the volume-support i18n key, map Docker network_mode=none onto deny-egress, inject the E2B inbound header without a gateway pool, and fold header names when merging redacted secrets. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-03 02:49:46 +00:00
handle, err := client.Connect(ctx, RemoteConnectRequest{SandboxID: summaries[0].ID})
if err != nil {
t.Fatalf("Connect: %v", err)
}
// The container entrypoint makes the marker world-writable on purpose.
// Leaving it to whatever umask the daemon happens to run with would work
// on a host with umask 000 and silently stop tracking script executions on
// a host with umask 022.
if mode := dockerActivityMarkerStat(t, ctx, summaries[0].ID).Mode.Perm(); mode != 0o666 {
t.Fatalf("activity marker is %v, want 0666 so both root and %s can refresh it",
mode, DefaultSandboxExecUser)
}
before := dockerActivityMarkerMTime(t, ctx, summaries[0].ID)
// Exec directly as the unprivileged account: this asserts that the account
// running user code refreshes the marker itself, rather than relying on
// some other step happening to touch it first. The marker has one-second
// resolution on most filesystems.
time.Sleep(2 * time.Second)
result, err := client.Exec(ctx, handle, RemoteExecRequest{
Command: "echo",
Args: []string{"as-sandbox-user"},
User: DefaultSandboxExecUser,
Timeout: 30 * time.Second,
})
if err != nil || result.ExitCode != 0 {
t.Fatalf("exec as %s failed: %v %#v", DefaultSandboxExecUser, err, result)
}
after := dockerActivityMarkerMTime(t, ctx, summaries[0].ID)
if !after.After(before) {
t.Fatalf("an exec as %s did not refresh the activity marker: before=%s after=%s",
DefaultSandboxExecUser, before, after)
}
}
func dockerActivityMarkerMTime(t *testing.T, ctx context.Context, containerID string) time.Time {
t.Helper()
return dockerActivityMarkerStat(t, ctx, containerID).Mtime
}
func dockerActivityMarkerStat(
t *testing.T, ctx context.Context, containerID string,
) container.PathStat {
t.Helper()
api, err := sharedDockerEngineClients.get(dockerEndpoint{
Host: strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_HOST")),
Timeout: DefaultDockerHTTPTimeout,
})
if err != nil {
t.Fatalf("docker client: %v", err)
}
stat, err := api.ContainerStatPath(ctx, containerID,
client.ContainerStatPathOptions{Path: dockerActivityMarker})
if err != nil {
t.Fatalf("stat activity marker: %v", err)
}
return stat.Stat
}
// A session must survive the container being stopped underneath it: the
// filesystem is intact, so Connect restarts it rather than losing the state.
func TestDockerBackendResumesStoppedContainerIntegration(t *testing.T) {
cfg := dockerIntegrationConfig(t)
manager := newDockerIntegrationManager(t, cfg)
ctx, cancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
5*time.Minute,
)
defer cancel()
sessionID := fmt.Sprintf("docker-resume-%d", time.Now().UnixNano())
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
time.Minute,
)
defer cleanupCancel()
_ = manager.DestroySession(cleanupCtx, sessionID)
})
marker := path.Join(SessionOutputRoot, "resume.txt")
first := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(`
with open(%q, 'w') as handle:
handle.write('before-stop')
print('ok')
`, marker))
if !first.IsSuccess() {
t.Fatalf("seed execution failed: %#v", first)
}
client, err := NewDockerRemoteClient(cfg)
if err != nil {
t.Fatalf("build docker client: %v", err)
}
summaries, err := client.List(ctx, RemoteListFilter{
Metadata: map[string]string{remoteMetadataSessionID: sessionID},
})
if err != nil || len(summaries) != 1 {
t.Fatalf("expected exactly one container for the session: %v %#v", err, summaries)
}
// Stop it the way a host reboot or an operator would.
stopCtx, stopCancel := context.WithTimeout(ctx, time.Minute)
defer stopCancel()
if err := stopDockerContainerForTest(stopCtx, summaries[0].ID); err != nil {
t.Fatalf("stop container: %v", err)
}
second := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(`
with open(%q) as handle:
print('restored=' + handle.read())
`, marker))
if !second.IsSuccess() || !strings.Contains(second.Stdout, "restored=before-stop") {
t.Fatalf("session did not resume with its filesystem: %#v", second)
}
}
// A session owns /workspace, so it can replace its own artifact directory with
// a symlink pointing anywhere in the container. chown and chmod follow
// symlinks, so if the pre-execution bootstrap ran as root it would hand the
// session ownership of the link's target — /etc here, which is enough to
// rewrite passwd and give the sandbox account uid 0 on the next exec.
//
// Session-scoped containers are what make this reachable: the link planted by
// one execution is still there when the next one runs the bootstrap. Under the
// old one-shot `docker run --rm` the two never shared a filesystem.
func TestDockerBackendArtifactBootstrapDoesNotFollowSymlinkIntegration(t *testing.T) {
cfg := dockerIntegrationConfig(t)
manager := newDockerIntegrationManager(t, cfg)
ctx, cancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
5*time.Minute,
)
defer cancel()
sessionID := fmt.Sprintf("docker-chown-escape-%d", time.Now().UnixNano())
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
time.Minute,
)
defer cleanupCancel()
_ = manager.DestroySession(cleanupCtx, sessionID)
})
if first := runDockerScript(t, ctx, manager, sessionID, `print('seed')`); !first.IsSuccess() {
t.Fatalf("seed execution failed: %#v", first)
}
client, err := NewDockerRemoteClient(cfg)
if err != nil {
t.Fatalf("build docker client: %v", err)
}
summaries, err := client.List(ctx, RemoteListFilter{
Metadata: map[string]string{remoteMetadataSessionID: sessionID},
})
if err != nil || len(summaries) != 1 {
t.Fatalf("expected exactly one container for the session: %v %#v", err, summaries)
}
feat(sandbox): add tenant-configurable network policy (#2995) * feat(sandbox): add the tenant network policy with its secrets and validation Administrators need control over sandbox network access, so a named sandbox config gains a network policy block. It lives inside the existing config JSONB, so there is no schema change and old rows read back as the zero value. Both booleans are phrased so that the zero value IS the intended default -- outbound open, inbound closed. That makes "no network block" and "explicitly saved defaults" provably the same thing, and avoids a tri-state pointer where nil would have to mean "allowed" for egress and "closed" for ingress. Injected header values are credentials, so they ride the encrypt-at-rest and mask-on-read path EnvVars already uses instead of a parallel mechanism. One CloneWithSecrets traversal serves encrypt, decrypt and mask so the three directions cannot disagree about which fields are secret. Validation runs at save time because the alternative is failing at sandbox-create time, where the admin no longer has the form in front of them. It rejects both what a provider would refuse and what a provider would accept without doing what the admin meant -- a domain allowlist with no deny-all fallback still leaves every unresolved destination reachable. * feat(sandbox): apply the network policy on both providers, persist the inbound token Resolve the stored policy into one fully specified provider-neutral policy so that nothing downstream re-derives a default. Both booleans come out non-nil on every path, including the nil-tenant one, because a partially specified policy would let the adapters fall back to their providers' more permissive defaults. The three inversions (deny-egress to allow-internet, public-inbound, rule-deny to rule-allow) happen in exactly one place. Every sandbox-creating path carries it, so sessions, skill installs and the deep connectivity check all run under the same config's policy rather than each wiring its own. Inbound access defaults to CLOSED, deliberately stricter than either provider's own default: a sandbox URL reachable by anyone who learns the ID is not a reasonable default for a tenant's workspace. Closing it makes the provider issue a per-sandbox traffic token, and only at create time -- so the token is stored with the session binding and replayed through Connect on every reconnect. Without that, a sandbox that was paused on TTL or rebound after a restart would answer 403 on every exec and file read, and 403 classifies as an authentication error rather than NotFound, so the binding would never be replaced and the session would stay wedged. Connect therefore takes a request struct instead of a bare ID, which gives the token a single documented way in rather than implicit state inside an adapter. Metadata-based recovery is the one reconnect path with no binding to read the token from. Rather than adopt a sandbox that would be permanently 403, it is deleted and replaced -- but only for providers that have the credential at all, since Docker has no inbound token and its containers are still adoptable. go-e2b keeps the token and never sends it, so for E2B the data-plane RoundTripper attaches the header from a process-local registry. Cube's SDK already does this itself. * fix(sandbox): classify data-plane traffic by authority shape, not the configured domain isDataPlane suffix-matched the configured sandbox domain, which was wrong in both directions. Both required a configured proxy_url, so E2B Cloud's default usage was unaffected; the affected deployments are exactly the self-hosted and E2B-compatible ones the gateway exists for. A configured gateway could be silently ignored. sandbox_domain is optional for E2B -- MissingRequiredFields asks only for api_key and template_id -- and with it empty the check returned false for everything. The general form is worse than the empty case: go-e2b's envdBaseURL prefers the domain the control plane reported over the client-wide one, so the authority actually dialled need not appear in the config at all. The failure is quiet whenever public DNS happens to resolve the sandbox domain, and the operator believes traffic is passing through a gateway that never sees it. Control-plane calls could be sent to the gateway. E2B's own defaults put the API host under the sandbox domain (api.e2b.app beneath e2b.app), so the suffix match classified every Create, Connect and List as data-plane traffic. That is loud where the gateway does not serve the API, but where it proxies both planes it succeeds while downgrading an X-API-Key request to plaintext for an http:// gateway. Cube was immune to the first problem, since it requires both fields, but not to this one. Classify on the "<port>-<sandboxID>.<domain>" shape both SDKs generate, using the SandboxIDFromDataPlaneHost helper that token injection on the very same request already relies on -- so routing and injection now agree by construction instead of applying two different rules. That helper exists precisely because the configured domain is unreliable here; it was simply never used for the routing half. The control host stays as an explicit exclusion. The shape test already rejects api.<domain>, so this only covers an API host that itself wears the shape, such as 8080-api.example.com. One existing assertion was replaced rather than kept: the E2B pool test proved that the Cube fields were ignored by asserting a cube.app authority was not data-plane traffic, which tested the domain matching rather than the field selection. It now asserts the transport dials the E2B gateway address and not the Cube one. * feat(sandbox): add the network policy editor to the sandbox config drawer The policy sits in the runtime step, directly under the settings it constrains, rather than in a step of its own. The existing execution timeouts were compressed into a two-column grid to make room, keeping each field's own label and its own tip -- the reason they were one per row was that three unlabelled numbers sharing a footnote gave no clue which one you were editing, and two columns with per-field tips does not regress that. Provider-specific sections are shown only for the backend that has them: the Cube L7 rule cards, E2B's per-host header transforms, and for Docker just the bridge/none selector, since Docker can only express the overall switch. Injected header values are write-only. A stored one shows as configured and is preserved when the input is left blank, which is how env-var secrets already behave. Renaming a rule or a header is the case worth care: the merge indexes credentials on the rule-and-header pair, so a rename means the old value can no longer be recovered. One helper decides both the placeholder text and whether the payload re-attaches the value, so the form cannot claim a credential is kept while the save blanks it. The add buttons use keys of their own instead of reusing the env-var table's "add variable", which read wrongly under a list of network destinations and which the i18n key check cannot catch, since the key exists in every bundle. * docs(sandbox): document the network policy and its inbound default change The existing network bullet described the pre-feature state -- both providers open by default, tunable only through the neutral policy at create time -- which is no longer true of the defaults or of the admin-facing surface. Three things needed writing down rather than restating. The inbound default flips from publicly reachable to credential-required. A deployment that relies on a browser or an external service reaching a sandbox port directly, rather than going through WeKnora, has to opt back in on that config. The binding store now holds a bearer credential in plaintext. Leaving it unencrypted was a deliberate trade -- per-reconnect crypto on the hot path against Redis's own access control -- and the trade is only sound if the requirement is actually stated, along with the code-side constraint it depends on: a binding or a handle is never logged whole, only the sandbox ID and whether a credential is present. On binding loss, a closed-inbound Cube or E2B config no longer adopts its old sandbox by metadata. The token went with the binding and the provider will not reissue it, so adoption would produce a session that answers 403 on every data-plane call with no way back. The sandbox is deleted and rebuilt, which costs the /workspace scratch. Docker has no such credential and still adopts. * fix(sandbox): fail closed when a closed-inbound create has no traffic token A Cube/E2B sandbox created without the inbound token would be bound anyway, then 403 on every data-plane call as an unreplaceable authentication error. Refuse the create, destroy the sandbox, and stop Docker from persisting inbound/egress radios it cannot honour. Canonicalize IPv4 /0 deny-all onto 0.0.0.0/0 and reject CR/LF in injected header names and values. * fix(sandbox): satisfy pre-push lint on the network policy files Unexport the data-plane host parser, drop file-level package docs that revive rejected, and lowercase error-string prefixes that staticcheck ST1005 treats as capitalized English. * fix(sandbox): persist rotated inbound tokens and stop misreporting restricted egress Connect can reissue the traffic token after pause/resume; write it back onto the binding so a restart does not restore a stale credential that 403s and cannot be replaced. Restore the volume-support i18n key, map Docker network_mode=none onto deny-egress, inject the E2B inbound header without a gateway pool, and fold header names when merging redacted secrets. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-03 02:49:46 +00:00
handle, err := client.Connect(ctx, RemoteConnectRequest{SandboxID: summaries[0].ID})
if err != nil {
t.Fatalf("Connect: %v", err)
}
ownerOfEtc := func() string {
t.Helper()
result, err := client.Exec(ctx, handle, RemoteExecRequest{
Command: "stat",
Args: []string{"-c", "%U:%G", "/etc"},
User: DefaultSandboxExecUser,
Timeout: 30 * time.Second,
})
if err != nil || result.ExitCode != 0 {
t.Fatalf("stat /etc failed: %v %#v", err, result)
}
return strings.TrimSpace(result.Stdout)
}
before := ownerOfEtc()
if before != "root:root" {
t.Fatalf("/etc should start out root-owned, got %q", before)
}
// Exactly what a model with shell_exec can do: it owns /workspace.
plant, err := client.Exec(ctx, handle, RemoteExecRequest{
Shell: true,
Command: fmt.Sprintf(
"rm -rf %s && ln -s /etc %s", SessionOutputRoot, SessionOutputRoot,
),
User: DefaultSandboxExecUser,
Timeout: 30 * time.Second,
})
if err != nil || plant.ExitCode != 0 {
t.Fatalf("planting the symlink failed: %v %#v", err, plant)
}
// Any further execution runs the bootstrap against the planted path.
_, err = manager.Execute(ctx, &ExecuteConfig{
Script: "conformance.py", ScriptContent: `print('after')`,
SessionID: sessionID, Timeout: time.Minute, SkipValidation: true,
Env: map[string]string{skillOutputEnvVar: SessionOutputRoot},
})
if err == nil || !strings.Contains(err.Error(), "symlink") {
t.Fatalf("bootstrap must preserve and report the symlink before execution: %v", err)
}
if after := ownerOfEtc(); after != "root:root" {
t.Fatalf("the artifact bootstrap chowned through the symlink: /etc is now %q, want root:root",
after)
}
}
// stopDockerContainerForTest stops a container behind the adapter's back, the
// way a host reboot or an operator with a shell would.
func stopDockerContainerForTest(ctx context.Context, id string) error {
api, err := sharedDockerEngineClients.get(dockerEndpoint{
Host: strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_HOST")),
Timeout: DefaultDockerHTTPTimeout,
})
if err != nil {
return err
}
grace := 5
_, err = api.ContainerStop(ctx, id, client.ContainerStopOptions{Timeout: &grace})
return err
}
func runDockerScript(
t *testing.T,
ctx context.Context,
manager *SessionBoundManager,
sessionID, source string,
) *ExecuteResult {
t.Helper()
return runDockerScriptWithTimeout(t, ctx, manager, sessionID, source, 3*time.Minute)
}
func runDockerScriptWithTimeout(
t *testing.T,
ctx context.Context,
manager *SessionBoundManager,
sessionID, source string,
timeout time.Duration,
) *ExecuteResult {
t.Helper()
result, err := manager.Execute(ctx, &ExecuteConfig{
Script: "conformance.py",
ScriptContent: source,
SessionID: sessionID,
Timeout: timeout,
SkipValidation: true,
Env: map[string]string{skillOutputEnvVar: SessionOutputRoot},
})
if err != nil {
t.Fatalf("Execute: %v", err)
}
if result == nil {
t.Fatal("Execute returned no result")
}
t.Logf("execute exit=%d killed=%v stdout=%q stderr=%q err=%q",
result.ExitCode, result.Killed, result.Stdout, result.Stderr, result.Error)
return result
}
func TestDockerSkillSnapshotIntegration(t *testing.T) {
cfg := dockerIntegrationConfig(t)
client, err := NewDockerRemoteClient(cfg)
if err != nil {
t.Fatalf("build docker client: %v", err)
}
probeCtx, cancelProbe := context.WithTimeout(context.Background(), 15*time.Second)
defer cancelProbe()
if err := client.Health(probeCtx); err != nil {
t.Skipf("docker daemon unreachable: %v", err)
}
if !client.Capabilities().SupportsSnapshots {
t.Fatal("docker backend must advertise snapshot support")
}
ctx, cancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
5*time.Minute,
)
defer cancel()
builder, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: cfg.DockerImage,
Metadata: map[string]string{"weknora.test": "skill-snapshot"},
})
if err != nil {
t.Fatalf("Create builder: %v", err)
}
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute)
defer cleanupCancel()
_ = client.Delete(cleanupCtx, builder.ID())
})
skillDir := SkillsImageRoot + "/itest"
skillFile := skillDir + "/SKILL.md"
seed, err := client.Exec(ctx, builder, RemoteExecRequest{
Command: fmt.Sprintf(
"mkdir -p %s && echo skill-ok > %s && chown %s:%s %s %s",
skillDir, skillFile, DefaultSandboxExecUser, DefaultSandboxExecUser,
SkillsImageRoot, skillDir,
),
Shell: true,
User: "root",
Timeout: time.Minute,
})
if err != nil || seed == nil || seed.ExitCode != 0 {
t.Fatalf("seed skill tree: err=%v result=%#v", err, seed)
}
ref, err := client.CreateSnapshot(ctx, builder.ID(), "weknora-sk-itest-g1")
if err != nil {
t.Fatalf("CreateSnapshot: %v", err)
}
if ref.ID == "" {
t.Fatal("CreateSnapshot returned an empty id")
}
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute)
defer cleanupCancel()
_ = client.DeleteSnapshot(cleanupCtx, ref.ID)
})
if err := client.Delete(ctx, builder.ID()); err != nil {
t.Fatalf("Delete builder: %v", err)
}
booted, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: ref.ID,
Metadata: map[string]string{"weknora.test": "skill-snapshot-boot"},
})
if err != nil {
t.Fatalf("Create from snapshot: %v", err)
}
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute)
defer cleanupCancel()
_ = client.Delete(cleanupCtx, booted.ID())
})
check, err := client.Exec(ctx, booted, RemoteExecRequest{
Command: "cat " + skillFile,
Shell: true,
User: DefaultSandboxExecUser,
Timeout: 30 * time.Second,
})
if err != nil || check == nil || check.ExitCode != 0 || !strings.Contains(check.Stdout, "skill-ok") {
t.Fatalf("snapshot did not carry the skill: err=%v result=%#v", err, check)
}
listed, err := client.ListSnapshots(ctx, "")
if err != nil {
t.Fatalf("ListSnapshots: %v", err)
}
found := false
for _, item := range listed {
if item.ID == ref.ID {
found = true
break
}
}
if !found {
t.Fatalf("ListSnapshots missing %s: %#v", ref.ID, listed)
}
templates, err := client.ListTemplates(ctx)
if err != nil {
t.Fatalf("ListTemplates: %v", err)
}
for _, item := range templates {
if dockerCanonicalSnapshotID(item.ID) == ref.ID {
t.Fatalf("skill snapshot %s leaked into the template catalog", ref.ID)
}
}
}